Aggregates on the whole table
SELECT COUNT(*) AS all_rows,
COUNT(city) AS rows_with_city,
COUNT(DISTINCT city) AS different_cities
FROM customers;| all_rows | rows_with_city | different_cities |
|---|---|---|
| 8 | 7 | 5 |
Three different answers from one table, because of the NULL city. This is a favourite interview question.
GROUP BY: one row per group
15 order rows
- DELIVERED
- DELIVERED
- CANCELLED
- …
Group by status
Rows with the same status go in one bucket
Aggregate each bucket
- DELIVERED → 12
- PLACED → 1
- RETURNED → 1
- CANCELLED → 1
SELECT status, COUNT(*) AS orders
FROM orders
GROUP BY status
ORDER BY orders DESC;| status | orders |
|---|---|
| DELIVERED | 12 |
| PLACED | 1 |
| RETURNED | 1 |
| CANCELLED | 1 |
SELECT product_id,
SUM(quantity) AS units_sold,
SUM(quantity * unit_price) AS revenue
FROM order_items
GROUP BY product_id
ORDER BY revenue DESC;| product_id | units_sold | revenue |
|---|---|---|
| 3 | 5 | 24995.00 |
| 1 | 5 | 9995.00 |
| 5 | 3 | 3897.00 |
| 4 | 7 | 3493.00 |
| 2 | 10 | 2990.00 |
Product 3 (Smartwatch) earns the most; product 2 (Phone Case) sells the most units. Different questions, different winners.
The GROUP BY rule
-- ❌ order_date is neither in GROUP BY nor inside an aggregate
SELECT customer_id, order_date, COUNT(*)
FROM orders
GROUP BY customer_id;Every column in SELECT must be in GROUP BY or inside an aggregate. A customer has many order dates; which one should the database show? Pick one: MAX(order_date) for the latest.
HAVING: filter the groups
SELECT customer_id, COUNT(*) AS orders
FROM orders
GROUP BY customer_id
HAVING COUNT(*) >= 3;| customer_id | orders |
|---|---|
| 2 | 3 |
| 1 | 3 |
Notice the rows came back as 2 then 1: without ORDER BY, the order isn't guaranteed.
SELECT customer_id, COUNT(*) AS delivered_orders
FROM orders
WHERE status = 'DELIVERED' -- 1. filter ROWS first
GROUP BY customer_id
HAVING COUNT(*) >= 2 -- 2. then filter GROUPS
ORDER BY customer_id;| customer_id | delivered_orders |
|---|---|
| 1 | 3 |
| 2 | 2 |
| 4 | 2 |
| 6 | 2 |
| WHERE | HAVING | |
|---|---|---|
| Filters | Rows | Groups |
| Runs | Before GROUP BY | After GROUP BY |
| Can use aggregates | No | Yes |
| Example | status = 'DELIVERED' | COUNT(*) >= 2 |
Conditional aggregation: many metrics in one query
SELECT DATE_TRUNC('month', order_date)::date AS month,
COUNT(*) AS orders,
SUM(CASE WHEN status = 'DELIVERED' THEN 1 ELSE 0 END) AS delivered,
SUM(CASE WHEN status IN ('CANCELLED', 'RETURNED') THEN 1 ELSE 0 END) AS lost
FROM orders
GROUP BY DATE_TRUNC('month', order_date)
ORDER BY month;| month | orders | delivered | lost |
|---|---|---|---|
| 2026-04-01 | 8 | 6 | 1 |
| 2026-05-01 | 7 | 6 | 1 |
This pattern builds report tables in one pass over the data. PostgreSQL also supports the shorter COUNT(*) FILTER (WHERE status = 'DELIVERED').
ROLLUP: subtotals and a grand total
SELECT COALESCE(p.category, 'ALL CATEGORIES') AS category,
SUM(oi.quantity * oi.unit_price) AS revenue
FROM order_items oi
JOIN products p ON p.product_id = oi.product_id
GROUP BY ROLLUP (p.category)
ORDER BY revenue;| category | revenue |
|---|---|
| Accessories | 10380.00 |
| Electronics | 34990.00 |
| ALL CATEGORIES | 45370.00 |
ROLLUP adds a total row (where category is NULL, which we label). CUBE and GROUPING SETS give other combinations of subtotals.
🎯 Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1What's the difference between COUNT(*), COUNT(1) and COUNT(column)?Fresher+
Q2Can you use an alias from SELECT in HAVING?Fresher+
Q3How do you get the number of orders and delivered orders per month in one query?1–3 yrs+
Q4Does AVG include NULLs?1–3 yrs+
Q5Find customers whose every order was delivered.3+ yrs+
Key takeaways
- ✓GROUP BY + aggregates turn detail rows into summaries.
- ✓HAVING filters summaries; WHERE filters raw rows.
- ✓Conditional aggregation builds many metrics in one pass.
- ✓Next: combining tables with JOINs.
Frequently asked questions
What does GROUP BY do?
It puts rows with the same value(s) into groups, so aggregate functions like COUNT and SUM give one result per group instead of one for the whole table.
COUNT(*) vs COUNT(column) vs COUNT(DISTINCT column)?
COUNT(*) counts rows. COUNT(column) counts rows where that column isn't NULL. COUNT(DISTINCT column) counts different non-NULL values.
Can I use WHERE with GROUP BY?
Yes. WHERE filters rows before grouping; HAVING filters the groups afterwards. Use both when you need both.
Why do I get 'must appear in the GROUP BY clause'?
Every selected column must either be in GROUP BY or inside an aggregate. Otherwise the database doesn't know which of the group's many values to show.
What is conditional aggregation?
Putting a CASE (or FILTER) inside an aggregate to count or sum only some rows, like SUM(CASE WHEN status = 'DELIVERED' THEN 1 ELSE 0 END). It creates several metrics in one pass.
🧠 Quick check: GROUP BY and HAVING
1. 8 customers, one has a NULL city. COUNT(city) returns...
2. Keep only customers with 3+ orders. Use...
3. SELECT customer_id, order_date, COUNT(*) FROM orders GROUP BY customer_id fails because...
4. Which counts only delivered orders in the same query as all orders?
Checking your access…