Skip to content

The HAVING Clause

Siim Kinks edited this page Mar 21, 2017 · 3 revisions

The HAVING clause is commonly used to further restrict data resulting from a previously issued GROUP BY clause.

For example, selecting only those authors that have written at least two books:

SQL SqliteMagic
  SELECT AUTHOR_ID, COUNT(*)
    FROM BOOK
GROUP BY AUTHOR_ID
  HAVING count(*) >= 2
import static com.siimkinks.sqlitemagic.BookTable.BOOK;
import static com.siimkinks.sqlitemagic.Select.count;

CompiledSelect<Book, Select.SelectN> compiledSelect = Select
        .columns(BOOK.AUTHOR_ID, count())
        .from(BOOK)
        .groupBy(BOOK.AUTHOR_ID)
        .having(count().greaterOrEqual(2L))
        .compile();

Query created above can be used to define a SQL view, for example.

See Next

Clone this wiki locally