GROUP BY and HAVING

Aggregation is where a result set changes grain on purpose. One row per employee becomes one row per department, and the engine needs to know what to do with every column you asked for.

The rule that generates the error you have seen

Every column in SELECT must either appear in GROUP BY or be wrapped in an aggregate.

SELECT department_id, name, count(*)
FROM employee
GROUP BY department_id;
ERROR:  column "employee.name" must appear in the GROUP BY clause or be used in an aggregate function

The reason is that the question has no answer. Engineering collapsed to one row and holds both Alice and Bob — so which name should that row show? Postgres refuses. MySQL historically picked one arbitrarily and returned it, which is worse: the query runs, the number looks plausible, and the name belongs to whichever row the engine happened to see first.

Decide what you meant:

SELECT department_id, count(*) AS headcount, max(salary) AS top_salary
FROM employee
GROUP BY department_id
ORDER BY department_id;

Or keep the names by aggregating them into one value:

SELECT department_id, string_agg(name, ', ' ORDER BY name) AS members
FROM employee
GROUP BY department_id
ORDER BY department_id;

string_agg takes its own ORDER BY, which is worth knowing — without it the order inside the string is whatever the engine produced, and a value that changes between runs is a value you cannot test.

Grouping by more than one column

SELECT d.building, e.department_id, count(*) AS headcount
FROM employee e
JOIN department d ON d.id = e.department_id
GROUP BY d.building, e.department_id
ORDER BY d.building, e.department_id;

The grain is now one row per (building, department) pair. Adding a column to GROUP BY always makes groups smaller and more numerous — it never changes the total of a count(*) across all rows, which is a useful sanity check.

HAVING filters groups, WHERE filters rows

From the order of operations: WHERE is step 2, GROUP BY step 3, HAVING step 4.

SELECT department_id, count(*) AS headcount
FROM employee
WHERE hired_on >= '2020-01-01'
GROUP BY department_id
HAVING count(*) > 1
ORDER BY department_id;

WHERE drops employees hired before 2020. HAVING then drops departments with fewer than two of the survivors. An aggregate in WHERE is an error, because at step 2 no groups exist yet:

SELECT department_id FROM employee WHERE count(*) > 1 GROUP BY department_id;

Put a non-aggregate condition in HAVING and it is legal but misleading — HAVING department_id = 1 works and is just a WHERE written late, which costs nothing at runtime and costs a reader a double-take.

The count trap over an outer join

This one appears in real reports. The intent is “how many sales per employee, including employees with none”:

SELECT e.name, count(*) AS sales
FROM employee e
LEFT JOIN sale s ON s.employee_id = e.id
GROUP BY e.name
ORDER BY e.name;

Alice shows 1. She has no sales at all. The LEFT JOIN produced one row for her with every sale column NULL, and count(*) counts rows, so it counted that placeholder.

Count a column from the nullable side instead:

SELECT e.name, count(s.id) AS sales
FROM employee e
LEFT JOIN sale s ON s.employee_id = e.id
GROUP BY e.name
ORDER BY e.name;

Alice shows 0. count(s.id) counts non-null values, and there are none. This is the count(*) versus count(column) distinction from the NULL lesson in the one place it reliably bites: after a LEFT JOIN, count the joined table’s key, never *.

Sums have the mirror problem — sum over no rows is NULL, not 0 — so wrap them:

SELECT e.name, coalesce(sum(s.amount), 0) AS revenue
FROM employee e
LEFT JOIN sale s ON s.employee_id = e.id
GROUP BY e.name
ORDER BY revenue DESC, e.name;

FILTER, instead of CASE inside an aggregate

Conditional aggregation is usually written with CASE:

SELECT count(*) AS total,
       count(CASE WHEN salary > 90000 THEN 1 END) AS well_paid
FROM employee;

Postgres has clearer syntax for exactly this:

SELECT count(*) AS total,
       count(*) FILTER (WHERE salary > 90000) AS well_paid
FROM employee;

Same answer, and the intent is on the surface. FILTER works on any aggregate, which makes “sum of this subset and that subset side by side” a one-line query rather than a pair of nested CASEs.

Try it

The count(*) versus count(s.id) pair is the one to run in the SQL playground. Alice going from 1 to 0 is the whole lesson.

Drill it with Sales per employee including the quiet ones.

Interview questions

1. Why must every selected column be grouped or aggregated? Because a group collapses many rows into one, and an ungrouped, unaggregated column has many candidate values with no rule for choosing. Postgres rejects it; engines that pick arbitrarily return a plausible wrong answer.

2. What is the difference between WHERE and HAVING? WHERE filters rows before grouping, HAVING filters groups after. Aggregates are legal in HAVING and illegal in WHERE.

3. After a LEFT JOIN, why does count(*) return 1 for a row with no matches? The outer join emits one row with NULLs for the unmatched side, and count(*) counts rows regardless of content. Counting the joined table’s primary key instead returns 0.

4. sum() over a group with no matching rows returns what? NULL, not 0. Wrap it in coalesce when a numeric default is wanted; count() differs and returns 0.

5. Does adding a column to GROUP BY change the total row count of the underlying table? No. It makes groups finer, so there are more of them with fewer rows each, but sum(count(*)) across all groups is unchanged. That makes it a quick check that a grouping change did not drop rows.

6. When would you use FILTER over CASE inside an aggregate? Whenever the aggregate is conditional. count(*) FILTER (WHERE cond) states the intent directly and composes with any aggregate, where nested CASEs obscure it and are easy to get subtly wrong with NULLs.

Next

Subqueries and CTEs — naming an intermediate result so the query reads top to bottom.