ORDER BY and LIMIT
ORDER BY sorts the result. ASC is smallest first (the default), DESC is largest first.
Data in a table has no guaranteed order. ORDER BY decides how results are sorted - cheapest first, newest first - and LIMIT keeps only the top few. Together they answer "top 10" questions, and power things like "latest orders" lists.
Example
SELECT name, price FROM products ORDER BY price DESC;
-- Result:
-- name | price
-- -------------------+------
-- Smart Watch | 3999
-- Wireless Earbuds | 1499
-- Denim Jeans | 1299
-- Table Lamp | 899
-- Yoga Mat | 799
-- Python Book | 599
-- Cotton T-shirt | 499
-- Steel Water Bottle | 349
-- Notebook Pack | 199▶ Try it yourselfSort by more than one column
Example
SELECT name, category, price FROM products ORDER BY category, price DESC;
-- Result:
-- name | category | price
-- -------------------+-------------+------
-- Python Book | Books | 599
-- Notebook Pack | Books | 199
-- Smart Watch | Electronics | 3999
-- Wireless Earbuds | Electronics | 1499
-- Denim Jeans | Fashion | 1299
-- Cotton T-shirt | Fashion | 499
-- Table Lamp | Home | 899
-- Steel Water Bottle | Home | 349
-- Yoga Mat | Sports | 799▶ Try it yourselfLIMIT: only the first few rows
Combine ORDER BY and LIMIT to get a "top N" list. OFFSET skips rows - useful for pages of results.
Example
SELECT name, price FROM products ORDER BY price DESC LIMIT 3;
-- Result:
-- name | price
-- -----------------+------
-- Smart Watch | 3999
-- Wireless Earbuds | 1499
-- Denim Jeans | 1299▶ Try it yourselfExample
SELECT name, price FROM products ORDER BY price DESC LIMIT 3 OFFSET 3;
-- Result:
-- name | price
-- ------------+------
-- Table Lamp | 899
-- Yoga Mat | 799
-- Python Book | 599▶ Try it yourselfSQL Server uses
SELECT TOP 3 ... and Oracle uses FETCH FIRST 3 ROWS ONLY instead of LIMIT. The idea is the same.Key points
- ORDER BY col ASC/DESC sorts results.
- LIMIT keeps the first N rows.
- Without ORDER BY, row order isn't guaranteed.
📝 Test yourself
1. Which shows the most expensive product first?
2. What does LIMIT 5 OFFSET 10 return?
3. Fill in the keyword that sorts the result:
SELECT * FROM products BY price;
