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 -> LIMIT

So 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) skips NULLs; COUNT(DISTINCT col) counts distinct non-null values.
  • SUM and AVG of an empty or all-NULL set return NULL, not 0: wrap with COALESCE(SUM(x), 0).
  • GROUPING SETS, ROLLUP and CUBE produce 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 SUM and COUNT and divide at the end.
  • HAVING with a non-aggregate predicate works but belongs in WHERE (filters earlier, can use indexes).
  • Integer division: in PostgreSQL and SQL Server sum(int)/count(*) is integer division; cast one side.

Practice questions

  1. Why does SELECT name, count(*) FROM customers fail?
  2. How would you get the top 3 countries by revenue, including ties?
  3. What does AVG(x) return when half the values are NULL?

References

sql-window-functions · sql-joins · query-planning