GROUP BY Multiple Columns
GROUP BY on multiple columns creates groups for each unique COMBINATION of those columns. This lets you analyze data along multiple dimensions simultaneously — orders per user per status, revenue per product per month.
Multi-Column Grouping
- GROUP BY col1, col2 — groups by unique (col1, col2) pairs
- Each unique combination forms its own group
- Useful for cross-tabulation / pivot-style analysis
- Order of columns in GROUP BY doesn't affect results (only presentation)
- More columns = more groups = more granular data
Multi-Column GROUP BY Examples
-- Orders per user per status (2-column group)
SELECT
user_id,
status,
COUNT(*) AS order_count,
SUM(total_amount) AS revenue
FROM orders
GROUP BY user_id, status
ORDER BY user_id, status;
-- Products grouped by tier AND stock level category
SELECT
CASE WHEN price < 100 THEN 'Budget' ELSE 'Premium' END AS tier,
CASE WHEN stock < 100 THEN 'Low' ELSE 'High' END AS stock_level,
COUNT(*) AS products,
AVG(price) AS avg_price
FROM products
GROUP BY
CASE WHEN price < 100 THEN 'Budget' ELSE 'Premium' END,
CASE WHEN stock < 100 THEN 'Low' ELSE 'High' END;
-- Monthly revenue by payment method
SELECT
DATE_FORMAT(paid_at, '%Y-%m') AS month, -- MySQL
-- TO_CHAR(paid_at, 'YYYY-MM') AS month -- PostgreSQL
payment_method,
SUM(amount) AS revenue,
COUNT(*) AS transactions
FROM payments
WHERE paid_at IS NOT NULL
GROUP BY DATE_FORMAT(paid_at, '%Y-%m'), payment_method
ORDER BY month DESC;Quick Quiz
Tip
Tip
Practice GROUP BY Multiple Columns in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
GROUP BY collapses rows by a column — aggregates summarize each group
Common Mistake
Warning
A common mistake with GROUP BY Multiple Columns is skipping edge case testing — empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready sql code.
Practice Task
Note
Practice Task — (1) Write a working example of GROUP BY Multiple Columns from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Key Takeaways
- GROUP BY on multiple columns creates groups for each unique COMBINATION of those columns.
- GROUP BY col1, col2 — groups by unique (col1, col2) pairs
- Each unique combination forms its own group
- Useful for cross-tabulation / pivot-style analysis