← All lessons SQL from zero · Lesson 5 of 10
Sorting and the top few A table has no order of its own. Unless you ask, rows come back in whatever order is quickest for the database, and that can change. ORDER BY sorts the result. Numbers go smallest first, text goes A to Z, and dates go oldest first:
SELECT name, price
FROM products
ORDER BY price;Returns name | price
------------+------
Sketchbook | 9.75
Pond net | 12.5
Field guide | 18
Duck feeder | 24
Rain boots | 40
Bird bath | 45.5
Raincoat | 59
Binoculars | 120
(8 rows) Add DESC (descending) to go the other way: largest first, Z to A, newest first. ASC (ascending) is the default, so you rarely write it.
You can sort by more than one column. The second one only decides between rows that tie on the first. By category, then the dearest first within each:
SELECT category, name, price
FROM products
ORDER BY category, price DESC;Returns category | name | price
---------+-------------+------
Books | Field guide | 18
Books | Sketchbook | 9.75
Clothing | Raincoat | 59
Clothing | Rain boots | 40
Garden | Bird bath | 45.5
Garden | Duck feeder | 24
Garden | Pond net | 12.5
Outdoors | Binoculars | 120
(8 rows) LIMIT keeps only the first few rows. Together with ORDER BY it answers "top three" questions:
SELECT name, price
FROM products
ORDER BY price DESC
LIMIT 3;Returns name | price
-----------+------
Binoculars | 120
Raincoat | 59
Bird bath | 45.5
(3 rows) Always sort before you use LIMIT. Without ORDER BY, "the first three" means three rows the database happened to read first, which isn't a question anyone asks. (SQL Server writes SELECT TOP 3 instead of LIMIT 3; most other databases use LIMIT.)
The clauses always go in this order: SELECT, FROM, WHERE, ORDER BY, LIMIT. Leave out the ones you don't need, but don't swap them round.
Every product, cheapest first: name and price.
The tables customers (id, name, city, joined)products (id, name, category, price)orders (id, customer_id, ordered_on, status)order_items (order_id, product_id, qty)signups (id, email, name, signed_up_at)payments (id, order_id, amount, currency, paid_at)events (id, received_at, payload (JSON text))staff (id, name, role, manager_id, salary, hired)logins (customer_id, day)
More info Quick reference ORDER BY x Sort by x: smallest, A, oldest first. ORDER BY x DESC Largest, Z, newest first. ORDER BY a, b By a; b only breaks ties. LIMIT n Only the first n rows (TOP n in SQL Server). Clause order SELECT, FROM, WHERE, ORDER BY, LIMIT.
The other AI and data engineering courses Report a bug · Suggest a feature