Skip to the page

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.

The 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

  1. WHERE vs HAVING?
  2. Find cities with more than 10 completed shifts last week.
  3. Count paid and failed orders per day in one query.
  4. Find duplicate emails.

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview