ORDER BY
By default the rows come back in whatever order the table happens to hold them. ORDER BY sorts them by a column before they reach you.
name station price
Bifteki grill 18
Baklava pastry 7
Melitzanosalata salad 16
Loukoumades pastry 9
Souvlaki grill 11
Dakos salad 14It goes on the very end, after WHERE if you have one. ORDER BY price sorts smallest to largest, which is what you get unless you say otherwise.
Query
SELECT name, price
FROM dishes
ORDER BY price;↓ result
name price
Baklava 7
Loukoumades 9
Souvlaki 11
Dakos 14
Melitzanosalata 16
Bifteki 18Add DESC to flip it and go largest to smallest. ASC is the default, and spells out ascending if you ever want to be explicit.
Query
SELECT name, price
FROM dishes
ORDER BY price DESC;↓ result
name price
Bifteki 18
Melitzanosalata 16
Dakos 14
Souvlaki 11
Loukoumades 9
Baklava 7It sorts text too, running A to Z.
Query
SELECT name
FROM dishes
ORDER BY name;↓ result
name
Baklava
Bifteki
Dakos
Loukoumades
Melitzanosalata
SouvlakiYou can also sort by more than one column. List them separated by commas and SQL sorts by the first one, then uses the next to break any ties. This groups every dish by station, and puts the cheapest first inside each group.
Query
SELECT name, station, price
FROM dishes
ORDER BY station, price;↓ result
name station price
Souvlaki grill 11
Bifteki grill 18
Baklava pastry 7
Loukoumades pastry 9
Dakos salad 14
Melitzanosalata salad 16You can flip each column on its own, too: ORDER BY station, price DESC keeps the stations in A to Z order but lists the priciest dish first inside each one.
ORDER BY only changes the order of the rows, never which rows or columns you get. With SELECT, WHERE and ORDER BY you can already answer most of what the rail throws at you.
