C.W.K.
Stream
Lesson 14 of 16 · published

HAVING: Filtering After Aggregation

~10 min · queries, aggregation

Level 0Schema Seedling
0 XP0/86 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

WHERE filters rows; HAVING filters groups

WHERE is row-level — it runs before grouping. HAVING is group-level — it runs after aggregation. The two coexist happily: WHERE narrows the input to GROUP BY; HAVING narrows the output.

The execution pipeline you'll memorise

FROM / JOIN     →  raw combined rows
WHERE           →  filter individual rows
GROUP BY        →  collapse into groups
HAVING          →  filter groups
SELECT          →  pick columns, compute, alias
ORDER BY        →  sort
LIMIT / OFFSET  →  cap output

This order explains every "why doesn't my query work" question you'll have. Aggregates can't appear in WHERE because aggregates don't exist yet at WHERE time. Aliases defined in SELECT can't be used in WHERE because SELECT runs after WHERE.

Code

WHERE + HAVING together·sql
SELECT u.name,
       COUNT(o.id)  AS order_count,
       SUM(o.total) AS total_spent
FROM   users u
JOIN   orders o ON o.user_id = u.id
WHERE  o.status = 'paid'              -- row filter
GROUP  BY u.name
HAVING COUNT(o.id) >= 3                -- group filter
   AND SUM(o.total) > 500;
HAVING with multiple conditions·sql
-- Products averaging below 3 stars but with at least 5 reviews
SELECT p.title,
       COUNT(r.id)            AS review_count,
       ROUND(AVG(r.rating), 2) AS avg_rating
FROM   products p
JOIN   reviews r ON r.product_id = p.id
GROUP  BY p.title
HAVING AVG(r.rating) < 3 AND COUNT(r.id) >= 5
ORDER  BY avg_rating;

External links

Exercise

Write a query with WHERE, GROUP BY, HAVING, ORDER BY, and LIMIT — all five — that finds the top 10 customers by total spend on completed orders, restricted to customers with at least 5 orders.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.