Overview
Aggregation collapses many rows into one per group: COUNT, SUM, AVG, MIN, MAX. GROUP BY defines the groups, HAVING filters groups after aggregation.
Core concepts
Logical evaluation order (what you can reference where):
FROM / JOIN -> WHERE -> GROUP BY -> HAVING -> SELECT (incl. window functions) -> DISTINCT -> ORDER BY -> LIMITSo WHERE cannot use aggregates or select-list aliases, while HAVING can use aggregates. Every non-aggregated column in SELECT must appear in GROUP BY (PostgreSQL also allows columns functionally dependent on a grouped primary key).
COUNT(*)counts rows;COUNT(col)skipsNULLs;COUNT(DISTINCT col)counts distinct non-null values.SUMandAVGof an empty or all-NULLset returnNULL, not 0: wrap withCOALESCE(SUM(x), 0).GROUPING SETS,ROLLUPandCUBEproduce subtotals in one pass.
Worked example
SELECT country,
count(*) AS orders,
sum(amount) AS revenue,
sum(amount) FILTER (WHERE status = 'refunded') AS refunded
FROM orders o JOIN customers c ON c.id = o.customer_id
GROUP BY ROLLUP (country);FILTER is PostgreSQL syntax for conditional aggregation; the portable form is SUM(CASE WHEN status = 'refunded' THEN amount END). ROLLUP (country) adds a grand-total row where country is NULL; use GROUPING(country) to tell it apart from a real NULL.
How it works (internals)
Two strategies: hash aggregate (build a hash table keyed by the group columns; needs memory, no sort) and sort/stream aggregate (sort or use an index so equal keys are adjacent, then fold). Columnar engines like ClickHouse specialise heavily on this operation.
Pitfalls and production notes
- Averaging averages is wrong; keep
SUMandCOUNTand divide at the end. HAVINGwith a non-aggregate predicate works but belongs inWHERE(filters earlier, can use indexes).- Integer division: in PostgreSQL and SQL Server
sum(int)/count(*)is integer division; cast one side.
Practice questions
- Why does
SELECT name, count(*) FROM customersfail? - How would you get the top 3 countries by revenue, including ties?
- What does
AVG(x)return when half the values areNULL?
References
- PostgreSQL manual, Aggregate Functions: https://www.postgresql.org/docs/current/functions-aggregate.html