What You'll Learn
You'll learn how to sort grouped and aggregated results so your summaries appear in a clear, meaningful order—like ranking categories from highest to lowest sales or alphabetically by region.
Why Sort Grouped Data?
When you use GROUP BY to create summaries, the rows come back in no guaranteed order. Sorting grouped results helps you quickly identify top performers, spot trends, and present findings logically to stakeholders.
Think of it like organizing class test scores: first you group by student (to calculate each student's average), then you sort by that average to see who scored highest.
How It Works
You can sort grouped results using any column in your SELECT list—either the grouping column itself or an aggregate value:
SELECT
department,
COUNT(*) AS employee_count
FROM employees
GROUP BY department
ORDER BY employee_count DESC;
This groups employees by department, counts them, then sorts departments by employee count (largest first).
You can also sort by the grouping column:
SELECT
region,
SUM(sales) AS total_sales
FROM orders
GROUP BY region
ORDER BY region;
This alphabetically sorts regions after calculating their total sales.
Multiple Sort Criteria
Combine multiple columns for nuanced ordering:
SELECT
category,
AVG(price) AS avg_price
FROM products
GROUP BY category
ORDER BY avg_price DESC, category;
This sorts by average price (high to low), then alphabetically by category for ties.
Real-World Use Case
"Show me top-selling product categories by revenue" requires grouping by category, summing revenue, and sorting descending—making insights immediately actionable.
Key Takeaway: Use ORDER BY after GROUP BY to sort your aggregated results by aggregate values or grouping columns, transforming raw summaries into ranked, presentation-ready insights.