shuffleet
Home
Practice
Problems
Lessons
Plans
Compete
Challenges
Interviews
Leaderboard
Progress
Skills
Analytics
Submissions
Account
Settings

GROUP BY and aggregation

Beginner · 3 min read

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_idcustomer_idstatusamountorder_ts
1c1paid10004-01 09:00
2c1paid4004-01 15:00
3c2paidNULL04-01 18:00
4c2refunded5004-02 10:00
5c3paid3004-02 11:00

Paid orders, one row per day:

daycount(*)count(amount)count(DISTINCT customer_id)sum(amount)
04-01322140
04-0211130

Three counts, three different questions: rows, rows where amount is known, and different customers.

Rows fall into one bucket per day, and each bucket becomes one row of counts and sums

In SQL

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 aggregating

With 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:

SQL
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 clause

Each 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 meant count(*). 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_ts gives one group per distinct time, often one per row.
  • Filtering on an aggregate in WHERE. WHERE sum(amount) > 100 is an error; that's what HAVING is for.
  • sum of nothing is NULL, not 0. A group whose amounts are all NULL sums to NULL. Wrap it in coalesce(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 WHERE and HAVING?" 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), not count(*), 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.