GROUP BY vs ORDER BY, explained visually
Compare sorting album rows, combining them into genre totals, and sorting those totals.
Grouping and sorting explorer
6 input rows ยท 6 result rows. Sorts the albums by genre, then title. Each album still has its own row.
Original album rows
| genre | title | stock |
|---|---|---|
| Jazz | Night Bus | 7 |
| Indie | Static Bloom | 4 |
| Electronic | Soft Circuit | 0 |
| Jazz | Blue Hour | 3 |
| Indie | Coastline | 8 |
| Ambient | Low Tide | 2 |
Query result
| genre | title | stock |
|---|---|---|
| Ambient | Low Tide | 2 |
| Electronic | Soft Circuit | 0 |
| Indie | Coastline | 8 |
| Indie | Static Bloom | 4 |
| Jazz | Blue Hour | 3 |
| Jazz | Night Bus | 7 |
SQL for this result
SELECT genre, title, stock
FROM albums
ORDER BY genre, title;Sorting keeps the album rows
ORDER BY genre, title puts albums of the same genre next to one another and sorts their titles within each genre. Night Bus and Blue Hour still appear as two Jazz rows, with stock of seven and three respectively.
Grouping produces one total per genre
GROUP BY genre collects those same two albums into one Jazz group. SUM(stock) adds their stock and returns ten in a single Jazz row. GROUP BY defines which rows contribute to each result. To guarantee the order of those results, add ORDER BY.
Use both to rank the summaries
GROUP BY genre gives you one row per genre. Then ORDER BY total_stock DESC places Indie first with twelve copies, ahead of Jazz with ten. That order answers which genre has the most stock while keeping the result at one row per genre.
