HAVING


HAVING clause

When we need to filter the results of a GROUP BY query even further, we can use the HAVING clause. The HAVING clause specifies a search condition for a group.

The HAVING clause is similar to the WHERE clause, but it operates on groups after they've been grouped, rather than rows before they've been grouped.

SELECT album_id, count(id) as songs_count
FROM songs
GROUP BY album_id
HAVING songs_count > 5; -- This works in Postgres!

The difference between WHERE and HAVING:

  • A WHERE condition is applied to all the data in a query before it's grouped by a GROUP BY clause.

  • A HAVING condition is only applied to the grouped rows that are returned after a GROUP BY is applied.


Last updated