SQL Multi-Column Grouping Tutorial

SQL Tutorial: Grouping by multiple columns 👇 In the last post we covered GROUP BY with a single column. That gives you a one-dimensional view — revenue by category, trips by city. But what if you need both dimensions at once? That's where multi-column grouping comes in. 🔹 Check combinations before you group Before writing your query, always inspect what unique combinations exist: SELECT DISTINCT location, category FROM orders; 2 locations × 4 categories = 8 rows to expect. No surprises. 🔹 GROUP BY multiple columns Just add both columns to SELECT and GROUP BY: SELECT   location,   category,   COUNT(order_id)     AS order_count,   COUNT(DISTINCT user_id) AS user_count,   SUM(amount)       AS revenue,   AVG(amount)       AS avg_order_value FROM orders GROUP BY location, category ORDER BY location, revenue DESC; One row per combination. Every dimension visible at a glance. 🔹 The rule that catches everyone out Every column in SELECT that isn't inside an aggregate function MUST appear in GROUP BY. Break this rule and SQL throws an error immediately. 🔹 Multi-column sorting The order of columns in ORDER BY matters. Sorting by location first then revenue groups all rows by location with revenue ranked within each. Reverse the order and you get a completely different result. 🔹 Always include group size This one is underrated: a high average based on 10 rows is far less trustworthy than the same average based on 300 rows. Always include a COUNT in your summary so anyone reading it can judge reliability before making decisions. Next up: filtering data with WHERE. #SQL #PostgreSQL #DataAnalysis #LearningInPublic #TechTips

All SQL code from these posts is saved to my GitHub as I go: 🔗 https://github.com/aucampr/sql And if you want to know more about my work and experience: 🌐 https://ruanaucamp.me/

Like
Reply

To view or add a comment, sign in

Explore content categories