Joining and aggregating · core
GROUP BY, HAVING and conditional aggregation
GROUP BY collapses rows into one row per group so aggregates (COUNT, SUM, AVG, MIN, MAX) work per group, WHERE filters rows before grouping, HAVING filters groups after, and CASE inside an aggregate counts different conditions in one pass.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Every selected column must be grouped or aggregated (Postgres enforces this; it allows other columns only when you group by the primary key).
- WHERE runs before grouping (cheap: fewer rows to group); HAVING runs after and can use aggregates (HAVING COUNT(*) > 5).
- Conditional aggregation: SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END), COUNT(*) FILTER (WHERE status = 'paid') in Postgres. One pass instead of several queries.
- COUNT(DISTINCT user_id) counts unique values; it is more expensive on big tables.
- Group by several columns: GROUP BY city, date_trunc('day', created_at) for per-city daily totals.
- Duplicates: GROUP BY email HAVING COUNT(*) > 1.
- Joins before GROUP BY can multiply rows (fan-out); aggregate in a subquery first when you join one-to-many.
The red pen
Common traps: mistake → fix
Mistake: HAVING and WHERE are interchangeable
Fix: WHERE cannot use aggregates, and HAVING on plain columns wastes work.
Mistake: SELECT city, name, COUNT(*) ... GROUP BY city works
Fix: name is neither grouped nor aggregated; Postgres errors (MySQL might return an arbitrary name).
Easy to hard
Questions interviewers ask, easy to hard
- WHERE vs HAVING?
- Find cities with more than 10 completed shifts last week.
- Count paid and failed orders per day in one query.
- Find duplicate emails.
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.