Reading data
Sorting and limiting
Goal: Sort results and return the top rows · 7 min
ORDER BY sorts the result: ASC (ascending, default) or DESC (descending). Several columns break ties: ORDER BY category, price DESC.
LIMIT n returns only the first n rows; OFFSET k skips k rows (used for pagination: page 3 with 10 per page → LIMIT 10 OFFSET 20).
The logical order of a query is: FROM → WHERE → SELECT → ORDER BY → LIMIT. That is why you can sort by an alias defined in SELECT.
Worked example: The two most expensive products
- Sort by price descending.
- Take only 2 rows.
- Result: Laptop, Desk.
SELECT name, price FROM products ORDER BY price DESC LIMIT 2;Output:
Laptop | 900.0
Desk | 300.0