Home / SQL / Reference / Querying

SQL ORDER BY

Sort the result.

Syntax

SELECT … FROM … ORDER BY col1 [ASC|DESC], col2 [ASC|DESC];

ASC (smallest first) is the default; DESC sorts largest first. Later columns break ties in earlier ones. Without ORDER BY, row order is not guaranteed.

Example

Query (on the shop database used in the SQL course)

SELECT name, category, price
FROM products
ORDER BY category, price DESC;

Result

namecategoryprice
Deep Learning (book)Books89.0
Python Crash Course (book)Books45.0
SQL Pocket GuideBooks25.0
27-inch monitorElectronics329.0
Noise-cancelling headphonesElectronics249.0
Mechanical keyboardElectronics119.0
USB-C hubElectronics49.0
Wireless mouseElectronics29.0
Standing deskFurniture549.0
Ergonomic chairFurniture399.0
Desk lampFurniture59.0
Coffee beans 1 kgGrocery32.0
Green tea, 100 bagsGrocery12.0
Gel pens, pack of 10Stationery11.0
A5 notebookStationery8.5

15 rows

Good to know. NULLs sort first in SQLite and last in PostgreSQL (add NULLS FIRST / NULLS LAST to choose).

Related

Learn it step by step in the free lesson SELECT: Choosing Columns, with exercises that check your queries.