WHERE and HAVING at Different Stages

WHERE restricts individual inputs before grouping. HAVING restricts groups after their aggregate conditions are computed.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a report
  2. Try a threshold crossing together
  3. Trace which rows exist when groups are evaluated
  4. Build a fixture where the order changes the answer

Trace a report

A query can use WHERE to include only sales this year, then HAVING to keep only regions with total sales over 100. Grouping by one column defines which rows are summarized together.

Try a threshold crossing together

Two rows of 70 in one region have total 140. Filtering each row at over 100 would remove both. This is the difference between an item predicate and a condition on its group.[1]

Trace which rows exist when groups are evaluated

In a group A with readings two and nine, a row predicate of at least five removes two before aggregation. Group B with value six survives that filter but can fail a group requirement of total at least eight. See grouping by one column.

WITH measurements(group_id, amount) AS (VALUES ('A',2), ('A',9), ('B',6))
SELECT group_id, SUM(amount) FROM measurements WHERE amount >= 5
GROUP BY group_id HAVING SUM(amount) >= 8;
-- Expected: group A with sum 9.

Build a fixture where the order changes the answer

A report wanting full group totals for groups that have any qualifying row must retain the other rows. Compare it with the filtered-input report to confirm which definition is required.

References

  1. PostgreSQL Global Development Group, Queries ↩