Sorting and limiting results
Without ORDER BY, a database may return rows in any order, and that order can change. If order matters, always sort explicitly.
ORDER BY
Sorting by several columns
Rows are sorted by the first column, and ties are broken by the next.
You can also sort by an alias or an expression:
LIMIT and OFFSET
LIMIT caps how many rows come back. It's perfect for "top N" queries.
OFFSET skips rows. Together they give you pagination: page 2 with 3 items per page skips 3.
Pro note:
OFFSETgets slow on big tables because the database still reads all the skipped rows. Large apps use keyset pagination instead:WHERE price < :last_seen_price ORDER BY price DESC LIMIT 20.
Different databases spell this slightly differently: SQL Server uses TOP 3 or OFFSET … FETCH, while PostgreSQL, MySQL and SQLite use LIMIT.
Order of clauses
Clauses must be written in this order:
SELECT columns
FROM table
WHERE row filter
ORDER BY sort columns
LIMIT n;Practice
- Show the 5 most recent orders (newest
order_datefirst). - Show the cheapest Electronics product.
1.Without ORDER BY, what order are rows returned in?
2.For page 3 with 10 rows per page, what do you use?