GROUP BY & HAVING
The word that tells you a question needs group by is almost always each: the average salary of each department, the number of employees in each job. One answer row per group, instead of one for the whole table.
1One row per group
▶Show the answer
Four distinct jobs, so four rows. The counts add to twelve, the whole table.
▶Show the answer
Look at the NULL row. Lata Gurung has no department, and group by puts all the NULLs together into a group of their own rather than dropping them. Four groups, not three.
group by treats NULL as a value for grouping purposes, even though nothing is equal to NULL anywhere else in SQL. If a paper’s table has a blank in the grouping column, expect an extra group in the answer — and note that department 40, which has no employees at all, does not appear. A group only exists if a row put it there. Do not read anything into where the NULL group appears: a query with no order by has no guaranteed row order, and this one happens to list it first.2HAVING — filtering the groups
where throws out rows before grouping. having throws out whole groups afterwards, and it is the only one of the two allowed to mention an aggregate.
▶Show the answer
The NULL group had only one member, so having removed it — which is a neat demonstration that having runs after the grouping, not before.
50000.▶Show the answer
3Using both in one query
They are not alternatives — a query can have both, and then the order of events matters. where filters the rows, then the survivors are grouped.
25000, display the average salary of each department.▶Show the answer
Compare department 30 with question 2: the average rose from 37000 to 43500, because Gopal Das on 24000 was removed by the where before the averaging happened.
| The condition is about… | Use | Runs |
|---|---|---|
| One row on its own (salary > 25000) | where | Before grouping |
| A whole group (count(*) > 2) | having | After grouping |
| An aggregate of any kind | having | where cannot see aggregates at all |
4Sorting a grouped result
▶Show the answer
order by comes last, after group by, and it may sort by an aggregate. Note that four clerks out-earn two analysts in total while earning far less each — a nice reminder that sum and avg answer different questions.
A table has 12 rows; one row has NULL in the grouping column. How many groups does GROUP BY produce if the other 11 rows use 3 values?
Which clause can contain count(*) > 2?
In 'where salary > 25000 group by deptno', when is the where applied?