SQL ยท Chapter 10 of 42
SQL LIMIT / TOP
LIMIT restricts how many rows a SELECT returns. It's called `LIMIT` in MySQL/PostgreSQL/SQLite, `TOP` in SQL Server, and `FETCH FIRST n ROWS ONLY` in standard SQL.
Pair with ORDER BY for predictable results.
Syntax
SELECT ... FROM table ORDER BY col LIMIT n [OFFSET m];Pagination
`LIMIT 10 OFFSET 20` skips the first 20 rows and returns the next 10 โ page 3 of 10-row pages.
Vendor differences
MySQL/Postgres: `LIMIT n`. SQL Server: `SELECT TOP n`. Oracle 12c+: `FETCH FIRST n ROWS ONLY`.
Example 1 (sql)
SELECT name FROM users ORDER BY signed_up_at DESC LIMIT 5;Output
5 newest usersFetch the 5 most recent signups.
Example 2 (sql)
SELECT * FROM products ORDER BY id LIMIT 10 OFFSET 20;Output
rows 21..30Page 3 (10 per page).
Key points
- Always combine LIMIT with ORDER BY.
- OFFSET skips rows for pagination.
- MySQL/PG: LIMIT; SQL Server: TOP.
- OFFSET can be slow on huge tables โ consider keyset pagination.
๐ก Note: Without ORDER BY, LIMIT returns any 10 rows โ the database is free to choose an efficient order.
