SQL Challenger
All SQL guides

GROUP BY vs ORDER BY, explained visually

Compare sorting album rows, combining them into genre totals, and sorting those totals.

Grouping and sorting explorer

Choose a query

6 input rows ยท 6 result rows. Sorts the albums by genre, then title. Each album still has its own row.

Original album rows

genretitlestock
JazzNight Bus7
IndieStatic Bloom4
ElectronicSoft Circuit0
JazzBlue Hour3
IndieCoastline8
AmbientLow Tide2

Query result

genretitlestock
AmbientLow Tide2
ElectronicSoft Circuit0
IndieCoastline8
IndieStatic Bloom4
JazzBlue Hour3
JazzNight Bus7

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.

Try a related challenge