Coding Now – Best AI & Full Stack Courses in Delhi NCR | 100% Placement
Limited Offer: Get 50% OFF on AI & Full Stack Courses
📞 Call Now: +91 9667708830
Back to SQL Notes
Topic #211

SQL LIMIT Clause

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 LIMIT without ORDER BY and assuming it always returns the "first" rows
  • Large OFFSET values 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).

Related SQL Notes

Want to go beyond the notes?

Join CodingNow's SQL course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available
💬 Talk to Advisor
1
WhatsApp

Latest from Our Blog

Insights on AI, Data Science, Full Stack & Career

View All Articles →