Beginner

77. ORDER BY with GROUP BY

Learn how to sort grouped and aggregated results using ORDER BY.

📘 Lesson 77 of 728 ⏱ 8 min 🎯 Beginner

ORDER BY can be used after GROUP BY to sort the summarized results. The results can be sorted by a grouping column or by an aggregate expression such as SUM, COUNT, or AVG.

Grouped results are often easier to understand when sorted. For example, a sales report can be sorted from the highest-selling region to the lowest-selling region.

A manager wants to see regions ranked by total sales from highest to lowest. ORDER BY can sort the SUM result in descending order.

SQL
SELECT
    Region,
    SUM(SalesAmount) AS TotalSales
FROM Sales
GROUP BY Region
ORDER BY TotalSales DESC;

This pattern is common in sales rankings, regional reports, department analysis, customer rankings, and dashboard preparation.

  • ORDER BY can sort grouped results.
  • Results can be sorted by aggregate values.
  • DESC sorts from high to low for numeric values.
  • ASC sorts from low to high.
  • ORDER BY normally appears after GROUP BY and HAVING.
Can ORDER BY be used with GROUP BY?

Yes. ORDER BY can sort the results produced by GROUP BY.

How do you rank regions by total sales?

Use GROUP BY Region with SUM(SalesAmount), then ORDER BY the total sales in descending order.

Have you finished this lesson?

Introduction to SQL – All Lessons