Aggregation: GROUP BY and HAVING
Aggregate functions summarize many rows into one value. Without GROUP BY, all rows form one group; with it, one row comes out per group of equal values.
Aggregate functions
| Function | Result |
|---|---|
COUNT(*) | Number of rows |
COUNT(expr), COUNT(DISTINCT expr) | Number of non-NULL values, number of distinct values |
SUM, AVG | Sum, average (NULLs excluded) |
MIN, MAX | Minimum, maximum |
Order summary for one customer
SELECT COUNT(*) AS orders,
COUNT(DISTINCT status) AS statuses,
SUM(amt) AS total_amt,
MIN(ord_dt) AS first_dt,
MAX(ord_dt) AS last_dt
FROM orders
WHERE cust_id = 101
GROUP BY: grouping and summarizing
Rows with equal values in the GROUP BY columns are grouped together. SELECT may contain only the grouping columns and aggregate functions. An ungrouped column has several values within a group, so no single value can be picked.
Customer count by grade and region
SELECT grade, region, COUNT(*) AS cnt
FROM customers
GROUP BY grade, region
ORDER BY grade, region
HAVING: filtering groups
WHERE filters rows before grouping; HAVING filters groups after grouping. Conditions on aggregate results can go only in HAVING.
Customers with 20 or more orders
SELECT cust_id, COUNT(*) AS orders, SUM(amt) AS total_amt
FROM orders
WHERE cust_id BETWEEN 101 AND 200
GROUP BY cust_id
HAVING COUNT(*) >= 20
ORDER BY orders DESC, cust_id
Logical order of evaluation
A statement is written starting with SELECT, but its meaning is computed in the order below. Each step sees only the result of the previous steps.
| Order | Clause | What it does |
|---|---|---|
| 1 | FROM, JOIN | Build the rows to read |
| 2 | WHERE | Filter rows |
| 3 | GROUP BY | Group |
| 4 | HAVING | Filter groups |
| 5 | SELECT | Compute output expressions, assign aliases |
| 6 | ORDER BY | Sort |
| 7 | OFFSET, FETCH | Limit the row count |
So a SELECT alias can be used in ORDER BY, but by the standard not in WHERE or HAVING. PostgreSQL and Oracle 23ai allow aliases in GROUP BY; SQL Server does not. To work in all three DBs, repeat the expression.
Grouping by an expression
SELECT CASE WHEN amt >= 250000 THEN 'HIGH' ELSE 'LOW' END AS band,
COUNT(*) AS cnt
FROM orders
WHERE cust_id BETWEEN 101 AND 200
GROUP BY CASE WHEN amt >= 250000 THEN 'HIGH' ELSE 'LOW' END
ORDER BY band
Conditional aggregation
Putting CASE inside an aggregate function counts each condition separately in a single pass.
Counts by status in one row
SELECT cust_id,
COUNT(*) AS total,
COUNT(CASE WHEN status = 'DONE' THEN 1 END) AS done,
COUNT(CASE WHEN status = 'PAID' THEN 1 END) AS paid,
COUNT(CASE WHEN status = 'CANCELED' THEN 1 END) AS canceled
FROM orders
WHERE cust_id BETWEEN 101 AND 110
GROUP BY cust_id
ORDER BY cust_id
The standard also has the syntax COUNT(*) FILTER (WHERE status = 'DONE'). Only PostgreSQL supports it.
The type of an average
Average of an integer column
SELECT AVG(amt) AS avg_amt,
AVG(CAST(amt AS DECIMAL(12, 2))) AS avg_amt_dec
FROM orders
WHERE cust_id = 101
SQL Server returns AVG of an integer column as an integer, so the fractional part is lost. Oracle and PostgreSQL return a decimal.