LIMIT restricts how many rows a query returns — essential for pagination and top-N reports.
Syntax (MySQL / PostgreSQL)
SELECT columns FROM table_name
ORDER BY column
LIMIT row_count;
-- with an offset, for pagination
SELECT columns FROM table_name
ORDER BY column
LIMIT row_count OFFSET skip_count;
Dialect Note: SQL Server
-- SQL Server uses TOP instead of LIMIT
SELECT TOP 5 name, salary FROM employees ORDER BY salary DESC;
-- SQL Server pagination uses OFFSET ... FETCH
SELECT name FROM employees
ORDER BY salary DESC
OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY;
Example
SELECT name, salary FROM employees
ORDER BY salary DESC
LIMIT 2;
Output: the 2 highest-paid employees only.
Pagination Example
-- Page 1 (rows 1-10)
SELECT * FROM employees ORDER BY id LIMIT 10 OFFSET 0;
-- Page 2 (rows 11-20)
SELECT * FROM employees ORDER BY id LIMIT 10 OFFSET 10;
LIMIT Always Needs ORDER BY to Be Meaningful
LIMIT without ORDER BY returns some arbitrary 5 rows — not necessarily the first 5 by any logical order, and not guaranteed to be consistent across runs. Always pair LIMIT with an explicit ORDER BY when the specific rows matter.
Practical Use Case
"Top 5 products this month," paginated API results, sampling a large table during development without pulling millions of rows.
Common Mistakes
- Using
LIMITwithoutORDER BYand assuming it always returns the "first" rows - Large
OFFSETvalues on big tables can get slow, since the database still has to scan and discard the skipped rows — keyset pagination is a better approach at scale, but out of scope here
Interview Relevance
A very common request is "find the 2nd highest salary" — solvable with LIMIT 1 OFFSET 1 after sorting descending, though window functions like DENSE_RANK handle ties more correctly.
Practice Question
Write a query to get the 3rd and 4th highest-paid employees (i.e., skip the top 2, then take 2 more).