SQL Kitchen

Lesson · Recipe № 004

ORDER BY

Lesson 4
Recipe

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    14

It 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          18

Add 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          7

It sorts text too, running A to Z.

Query

SELECT name
FROM dishes
ORDER BY name;

↓ result

name
Baklava
Bifteki
Dakos
Loukoumades
Melitzanosalata
Souvlaki

You 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    16

You 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.

On the rail · tonight's orders

ORDER 010

for the specials board


Giorgos wants the specials board rewritten to show off the priciest dishes first.

Your query returns

The name and price of every dish, priciest first.


ORDER 011

for front of house


Front of house wants a clean menu they can hand to guests without hunting for anything.

Your query returns

The name of every dish, sorted A to Z.


ORDER 012

for the prep sheet


Giorgos wants the prep sheet grouped by station, with the priciest dish in each station first.

Your query returns

Every dish with its station and price, sorted by station (A to Z), priciest first within each station.