In two sentences
GROUP BY sorts rows into buckets that share the same values, then an aggregate function (count, sum, avg,
min, max) turns each bucket into a single row. Every column you select must either define the bucket or be
aggregated over it.
See it
| order_id | customer_id | status | amount | order_ts |
|---|---|---|---|---|
| 1 | c1 | paid | 100 | 04-01 09:00 |
| 2 | c1 | paid | 40 | 04-01 15:00 |
| 3 | c2 | paid | NULL | 04-01 18:00 |
| 4 | c2 | refunded | 50 | 04-02 10:00 |
| 5 | c3 | paid | 30 | 04-02 11:00 |
Paid orders, one row per day:
| day | count(*) | count(amount) | count(DISTINCT customer_id) | sum(amount) |
|---|---|---|---|---|
| 04-01 | 3 | 2 | 2 | 140 |
| 04-02 | 1 | 1 | 1 | 30 |
Three counts, three different questions: rows, rows where amount is known, and different customers.
In SQL
SELECT
CAST(order_ts AS date) AS day,
count(*) AS orders,
count(amount) AS with_amount,
count(DISTINCT customer_id) AS customers,
sum(amount) AS revenue
FROM orders
WHERE status = 'paid' -- filters rows, before grouping
GROUP BY CAST(order_ts AS date)
HAVING sum(amount) > 100; -- filters groups, after aggregatingWith the HAVING, only 04-01 (140) is left. WHERE can't do that job: when it runs, there is no sum yet.
By month instead of day, group by the truncated timestamp:
SELECT date_trunc('month', order_ts) AS month, count(*) AS orders
FROM orders
GROUP BY date_trunc('month', order_ts);Select a column that is neither grouped nor aggregated and Trino refuses:
'order_ts' must be an aggregate expression or appear in GROUP BY clauseEach bucket has several order_ts; SQL won't pick one for you. Aggregate it (max(order_ts)), group by it, or
drop it.
Common mistakes
count(col)when you meantcount(*).count(amount)skips orders with a missing amount. Decide which question you're answering.- Grouping by a timestamp instead of its day.
GROUP BY order_tsgives one group per distinct time, often one per row. - Filtering on an aggregate in
WHERE.WHERE sum(amount) > 100is an error; that's whatHAVINGis for. sumof nothing is NULL, not 0. A group whose amounts are all NULL sums to NULL. Wrap it incoalesce(sum(amount), 0)when the report needs a number.- Joining before grouping and counting twice. If a join multiplied the rows, every sum is inflated. See Joins and fan-out.
What an interviewer asks next
- "What's the difference between
WHEREandHAVING?" Rows before grouping, groups after. - "How many orders per customer, including customers with none?" Start from customers, LEFT JOIN orders, and
count(o.order_id), notcount(*), so a customer without orders counts 0.
Go further
The PostgreSQL tutorial page on aggregates is short and works as written in Trino. Trino's page lists every
aggregate function, including count_if, approx_distinct and arbitrary.
Practise it
Daily Revenue Report is this lesson as a problem. Then Customer Summary: Recency, Frequency, Monetary, and Revenue Doubled Overnight: Fix the Fan-Out Join to see a GROUP BY count the same row twice.