GROUP BY
How GROUP BY works
- Rows are split into groups with the same value(s) in the GROUP BY columns
- Aggregates are calculated for each group
- You get one result row per group
SELECT category_id, sum(amount)
FROM expenses
GROUP BY category_id;
The golden rule
Every column in SELECT must either:
- be in the GROUP BY, or
- be inside an aggregate function
(PostgreSQL allows other columns of a table if you group by its primary key: GROUP BY u.id lets you select u.name.)
Grouping by several columns
GROUP BY user_id, category_id → one row per user and category combination
Grouping by expressions
- By month:
GROUP BY date_trunc('month', spent_on) - By bucket:
GROUP BY CASE WHEN amount > 5000 THEN 'large' ELSE 'normal' END - By position or alias:
GROUP BY 1(PostgreSQL also allows an output alias)
NULL groups
All NULL values form one group (e.g. users with no city).
GROUP BY + JOIN
Most real reports join first, then group: total spending per category name, per city, etc.
Sorting the groups
Add ORDER BY total DESC — groups come out in no particular order otherwise.
Common mistakes
- Forgetting a column in GROUP BY → error
- Grouping by a column you don't need → too many rows
- Using WHERE to filter on an aggregate → use HAVING (next lesson)
Example
-- Total and count per user
SELECT user_id, count(*) AS expenses, sum(amount) AS total
FROM expenses
GROUP BY user_id
ORDER BY total DESC;
-- 3 | 8 | 24070.00
-- 2 | 7 | 22630.00
-- 1 | 10 | 21970.00
-- 4 | 6 | 7940.00
-- Per category NAME (join, then group)
SELECT c.name AS category, count(*) AS n, sum(e.amount) AS total
FROM expenses e
JOIN categories c ON c.id = e.category_id
GROUP BY c.name
ORDER BY total DESC;
-- Group by two columns: each user's spending per month
SELECT u.name,
to_char(date_trunc('month', e.spent_on), 'Mon') AS month,
sum(e.amount) AS total
FROM expenses e
JOIN users u ON u.id = e.user_id
GROUP BY u.name, date_trunc('month', e.spent_on)
ORDER BY u.name, date_trunc('month', e.spent_on);
-- Group by primary key lets you select other columns of that table
SELECT u.id, u.name, u.city, sum(e.amount) AS total
FROM users u JOIN expenses e ON e.user_id = u.id
GROUP BY u.id
ORDER BY total DESC;
-- NULLs form one group
SELECT city, count(*) FROM users GROUP BY city ORDER BY city NULLS LAST;
-- Kathmandu 2, Lalitpur 1, Pokhara 2, NULL 1
-- Group by a calculated bucket
SELECT CASE WHEN amount >= 3000 THEN 'Rs. 3000+' ELSE 'Under Rs. 3000' END AS bucket,
count(*)
FROM expenses
GROUP BY bucket;