ORDER BY
In the first chapter ORDER BY sorted rows by one column, and DESC reversed the order. That is enough as long as the values in the column don't repeat. But on the menu cappuccino and latte cost the same, 220.00 each. A query with ORDER BY price puts them side by side, but the DBMS doesn't promise which of the two comes first. In our run latte came before cappuccino, although it was added later.
A spreadsheet has sorting with levels for this case: "sort by price, then by name". The second level decides only where the first one gave a tie. ORDER BY with several columns works the same way in SQL.
Ascending and descending
The word after the column name sets the sort direction:
ASCis ascending; you can leave it out: it is the default direction;DESCis descending.
Numbers compare by size, dates from earlier to later, text alphabetically. ORDER BY price and ORDER BY price ASC give the same thing.
Several columns
The columns in ORDER BY are listed with commas. The DBMS sorts by the first column, and it turns to the next one only for rows where all the previous ones matched:
SELECT name, price
FROM menu_items
WHERE category = 'coffee'
ORDER BY price DESC, name; name | price
---------------+--------
Pumpkin latte | 320.00
Raf | 280.00
Flat white | 250.00
Cappuccino | 220.00
Latte | 220.00
Americano | 170.00
Espresso | 140.00
(7 rows)Let's go through what the DBMS did:
- It arranged the coffee by price, from the priciest to the cheapest.
- All rows but two have different prices, and
namedecides nothing for them. - Cappuccino and latte cost the same, so the second column decided their order: alphabetically
Cappuccinocomes beforeLatte.
Now the order is fully defined, and the query will return it on every run.
Each column has its own direction
DESC applies only to the column it follows. In the query above the price goes descending and the name ascending. You can mix directions any way you like:
SELECT category, name, price
FROM menu_items
WHERE price > 240
ORDER BY category, price DESC; category | name | price
----------+---------------+--------
coffee | Pumpkin latte | 320.00
coffee | Raf | 280.00
coffee | Flat white | 250.00
food | Syrniki | 310.00
food | Cheesecake | 290.00
(5 rows)The categories go alphabetically, and within each category the items go from the priciest to the cheapest. If you need both columns descending, write DESC after each: ORDER BY category DESC, price DESC.
A column not in SELECT
You can also sort by a column that is not in the result. The query SELECT name FROM menu_items WHERE category = 'food' ORDER BY price DESC returns only names: Syrniki, Cheesecake, Croissant. The prices aren't visible in the result, but the rows are arranged by them.
An alias in ORDER BY
ORDER BY can also name an alias from SELECT:
SELECT name, price + 30 AS new_price
FROM menu_items
WHERE category = 'food'
ORDER BY new_price DESC; name | new_price
------------+-----------
Syrniki | 340.00
Cheesecake | 320.00
Croissant | 190.00
(3 rows)The run order from the first chapter explains why this works. In terms of meaning, the query runs like this: FROM, WHERE, SELECT, ORDER BY. The alias new_price appears in SELECT, and ORDER BY comes after it and already knows the name. WHERE comes before SELECT, so the condition WHERE new_price > 300 ends in an error: there is no such column yet.
Here the spreadsheet analogy breaks down. Sorting in a spreadsheet rearranges the rows of the file itself. ORDER BY orders only the query result, and the rows in the menu_items table still have no order of their own.
Common mistake
A query with DISTINCT was sorted by a column that is not in SELECT:
SELECT DISTINCT category
FROM menu_items
ORDER BY price; -- ✗ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select listThe message says that with DISTINCT you can sort only by the selected columns. One coffee row in the result stands for seven table rows with prices from 140.00 to 320.00. The DBMS doesn't know which of these prices to place it by. Sort by what is in the result: ORDER BY category.
Key points
ORDER BY a, bsorts bya, and bybonly the rows with the samea.DESCapplies to the one column it follows; without it the order is ascending.- You can sort by a column not in
SELECTand by an alias fromSELECT:ORDER BYruns afterSELECT. - With
DISTINCTyou sort only by the selected columns.