Home › Learn › SQL › Aggregates

HAVING

Lesson 14 of 26. Filter groups after aggregating.

WHERE filters rows before grouping; HAVING filters groups after. "Customers with three or more orders" is a condition on a count, which only exists once the rows are grouped, so it goes in HAVING COUNT(*) >= 3. Both can appear in one query: WHERE to choose the rows that count, HAVING to choose which groups to show.

Putting an aggregate in WHERE is an error in every database; that is the tell that you need HAVING.

SELECT dept, COUNT(*) FROM employees GROUP BY dept HAVING COUNT(*) > 2;

Your task

Show the customer_id and the number of orders for every customer who placed three or more orders.

Hint 1

HAVING COUNT(*) >= 3

Show the solution
SELECT customer_id, COUNT(*) FROM orders GROUP BY customer_id HAVING COUNT(*) >= 3;

    Runs SQLite compiled to WebAssembly in this tab; the database is rebuilt before every run.