Lesson Description
WHERE filters rows; HAVING filters groups.
Lesson 3 of 4
Progress: 0/3 exercises solved (0%)
Solve all exercises below to unlock the next lesson.
Lesson Description
WHERE filters rows; HAVING filters groups.
Easy Project
Mini project: Create a hiring shortlist query that filters by role, salary range, and hire date with deterministic ordering.
WHERE filters individual rows before grouping. HAVING filters entire groups after aggregation.
SELECT grouping_column, aggregate_function(col) AS alias
FROM table_name
GROUP BY grouping_column
HAVING aggregate_condition;
SELECT department_id, COUNT(*) AS headcount
FROM employees
GROUP BY department_id
HAVING COUNT(*) >= 5
ORDER BY headcount DESC;
-- WHERE filters rows before grouping
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
WHERE hire_date > '2000-01-01' -- only recent hires
GROUP BY department_id
HAVING AVG(salary) > 8000; -- only departments with high avg salary
FROM — identify source tableWHERE — filter individual rowsGROUP BY — form groupsHAVING — filter groupsSELECT — compute output columnsORDER BY — sortLIMIT / OFFSET — paginateIn most databases (including PostgreSQL), you cannot reference a SELECT alias in HAVING because SELECT runs after HAVING. Repeat the aggregate expression:
-- CORRECT
HAVING COUNT(*) >= 5
-- ERROR in most databases
HAVING headcount >= 5
HAVING without GROUP BY operates on the whole table as one group.HAVING.This lesson is part of Aggregations & Grouping. Focus on the core idea in HAVING — filter on aggregates, then validate with deliberate practice.
What to master
Common mistakes
High-level strategy
Task ladder
Transparent data checks
Retention loop
Logical reasoning for commands
GROUP BY
Why: Defines one output row per grouping key.
Memory cue: Group key = output row identity.
HAVING
Why: Filters after aggregates are calculated.
Memory cue: WHERE before groups, HAVING after groups.
COUNT / SUM / AVG
Why: Converts row-level data into business metrics.
Memory cue: Measure only after grain is correct.
Concept check
3 quick questions. One at a time. Instant score at the end.
Return department_id and employee_count for departments with 5 or more employees.
From the store sandbox, return category_id and avg_price (rounded to 2 decimal places) for product categories whose average price is above 50.
From the hospital sandbox, return each specialty and doctor_count for specialties that have more than 2 doctors, ordered by specialty.
Lesson 3 of 4
0/3 solved (0%)
Finish this lesson to unlock next.