HAVING
Filter groups after they are aggregated. WHERE filters rows before.
Syntax
SELECT … GROUP BY column HAVING condition_on_an_aggregate;
Example
SELECT customer_id, COUNT(*) AS orders FROM orders WHERE customer_id IS NOT NULL GROUP BY customer_id HAVING COUNT(*) >= 2;
Customers who placed at least two orders.
Tables used: orders. Try it in a lesson below.
Common mistakes
- Put conditions on plain columns in WHERE, which is faster. Use HAVING only for conditions on aggregates.