SQL reference

SQL ORDER BY: sort your results

In Excel, you'd reach for
fxData > Sort, with "Add Level" for a second column

ORDER BY sorts the result. ASC (the default) is smallest first, A to Z, oldest date first. DESC is largest first. List several columns to break ties, like adding sort levels in Excel.

Pair it with LIMIT for "top 10" lists. (SQL Server writes SELECT TOP 10 instead.)

SQL order of execution: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT, with the Excel equivalent of each step
The order SQL runs a query in, with the Excel step each one is like. Download · Save to Pinterest

Syntax

SELECT columns
FROM table
ORDER BY col_1 DESC, col_2;
Try itEdit the query, then Run
namecategoryunit_price
Noise-Cancel HeadsetElectronics149
Webcam HDElectronics69
Standing DeskFurniture449
Ergo ChairFurniture329
Monitor ArmOffice89
Desk LampOffice39
Notebook PackStationery12
Gel Pens (10)Stationery9

8 rows

You can sort by a calculated column using its name from SELECT: SELECT region, SUM(quantity) AS units FROM orders GROUP BY region ORDER BY units DESC.

Your turn

List the 10 most recent signups: name and signup_date, newest first. Break ties by name A to Z.

This page on one card

SQL ORDER BY: sort your results: the Excel way (Data > Sort) and the SQL query, side by side
SQL ORDER BY: sort your results, on one card: the Excel way and the SQL. Download · Save to Pinterest
The practice data (7 tables)

See every column and sample rows