Ordering grouped results
- SQL course
- Intermediate
- Lesson 28/115
- 4 min
Sort grouped results.
GROUP BY with ordering
You sort the GROUP BY result with ORDER BY. You can put the highest total first.
SELECT category, SUM(price) AS total
FROM products
GROUP BY category
ORDER BY total DESC;This query puts the highest total on top.
category, SUM(price) AS total is selected from products. Rows are grouped by category; aggregate functions are computed per group. The result is sorted by total in descending order.
GROUP BY with ordering — details
ORDER BY can sort by the aggregate result or an alias. DESC is descending, ASC is ascending.
For example, ORDER BY COUNT(*) DESC puts the largest category at the top; if you gave an alias you can also write ORDER BY total DESC.
Practice GROUP BY with ordering
Sort category totals with ORDER BY total DESC.
Starter code
-- ordered group
SELECT category, SUM(price) AS total
FROM products
GROUP BY categorySample solution
SELECT category, SUM(price) AS total
FROM products
GROUP BY category
ORDER BY total DESC;Expected output
category total Elektronik 1500 Kitap 200
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Add ORDER BY
SELECT category, SUM(price) AS total
FROM products
GROUP BY category
____ total DESC;
SELECT category, SUM(price) AS total
FROM products
GROUP BY category
ORDER BY total DESC;
Explanation: ORDER BY is the right answer.
2 Ordering grouped results: match the terms
| Term | Meaning |
|---|---|
ORDER BY |
sort |
DESC |
descending |
ASC |
ascending |
GROUP BY |
group |
3 What makes ordering descending?
- NULL
- ASC
- DESC Correct answer
- DISTINCT
Explanation: DESC gives descending order.