SQLab Hub
Lesson 11 · LIMIT
Lesson 11 · Fundamentals

SQL LIMIT, TOP and FETCH: Return the First N Rows

LIMIT restricts how many rows a query returns. Together with ORDER BY it answers "top N" questions such as the five most expensive products, and with OFFSET it splits a long result into pages. SQL Server writes it as TOP, and standard SQL as FETCH FIRST.

Top N & OFFSET LIMIT vs TOP vs FETCH ▶ Runnable Playground examples 🧪 5 practice exercises 📝 10-question quiz ⏱ ~15 min

What Does LIMIT Do?

Without LIMIT, a query returns every matching row. With it, you get at most the number you ask for:

SQLite · runs in the Playground
SELECT id, first_name, last_name, city
FROM users
ORDER BY id
LIMIT 5;

▶ Run this query in the SQL Playground

The first five users by id
idfirst_namelast_namecity
1JenniferTorresHouston
2DonnaAdamsFort Worth
3KennethYoungAustin
4MichaelCarterSan Antonio
5RobertCampbellNew York
✓ 5 rows · real output from the Playground database
SQL · syntax (SQLite, PostgreSQL, MySQL)
SELECT columns
FROM table
[WHERE ...]
[ORDER BY ...]
LIMIT n [OFFSET m];

LIMIT is applied last, after WHERE, GROUP BY, HAVING and ORDER BY. The database builds and sorts the result, then hands back the first n rows. If fewer rows match, you simply get fewer.

Top N With ORDER BY

LIMIT on its own takes whichever rows the database finds first, and that can change from run to run. For a meaningful "top N", sort first. The three highest salaries:

SQLite · runs in the Playground
SELECT first_name, last_name, department, salary
FROM employees
ORDER BY salary DESC
LIMIT 3;

▶ Run this query in the SQL Playground

Three highest-paid employees
first_namelast_namedepartmentsalary
StevenNguyenMarketing204449
NancyThompsonCustomer Success203999
JohnLeeOperations203467
✓ 3 rows · real output from the Playground database

Top N also works on grouped results. The five customers who spent the most:

SQLite · runs in the Playground
SELECT user_id,
       COUNT(*) AS orders,
       ROUND(SUM(total), 2) AS spent
FROM orders
GROUP BY user_id
ORDER BY spent DESC
LIMIT 5;

▶ Run this query in the SQL Playground

Top five customers by spend
user_idordersspent
118415384.26
77514593.17
124412059.32
98311837.52
54411780.53
✓ 5 rows · real output from the Playground database
Ties at the cut-off. If the 5th and 6th rows have the same value, LIMIT 5 picks one of them arbitrarily. Add a tie-breaker to ORDER BY (such as id) for a stable answer, or use RANK() when every tied row should be included. See RANK and DENSE_RANK.

Skipping Rows With OFFSET

OFFSET m skips the first m rows before LIMIT counts. LIMIT 3 OFFSET 2 returns rows 3, 4 and 5:

SQLite · runs in the Playground
SELECT first_name, last_name, salary
FROM employees
ORDER BY salary DESC
LIMIT 3 OFFSET 2;

▶ Run this query in the SQL Playground

Third to fifth highest salaries
first_namelast_namesalary
JohnLee203467
DonnaJohnson199029
MatthewWilson196530
✓ 3 rows · real output from the Playground database

A common use is the Nth highest value. The second-highest distinct order total:

SQLite · runs in the Playground
SELECT DISTINCT total
FROM orders
ORDER BY total DESC
LIMIT 1 OFFSET 1;

▶ Run this query in the SQL Playground

Second-highest order total
total
4980.63
✓ 1 row · real output from the Playground database

DISTINCT matters: without it, two orders with the same top total would make the "second" value equal to the first.

Pagination

To show results in pages of a fixed size, use LIMIT page_size OFFSET (page_number - 1) * page_size. With 5 products per page, page 3 is:

SQLite · runs in the Playground
SELECT id, name, price
FROM products
ORDER BY id
LIMIT 5 OFFSET 10;

▶ Run this query in the SQL Playground

Page 3 of the product list, 5 per page
idnameprice
11Blender Pro 1200W1732.92
12Ergonomic Desk Mat XL1749.7
13Retinol Eye Cream 30ml684.54
14Play Kitchen Deluxe1840.63
15Japanese Green Tea 50 bags1810.45
✓ 5 rows · real output from the Playground database
PageLIMIT 5 OFFSET ...Rows
101 to 5
256 to 10
31011 to 15
n(n - 1) × 5...

Keyset pagination for large tables

OFFSET has to read and throw away every skipped row, so page 10,000 is slow. Keyset (or "seek") pagination remembers the last row of the previous page and continues from there, which an index can serve directly:

SQLite · runs in the Playground
SELECT id, name, price
FROM products
WHERE id > 10      -- the last id shown on the previous page
ORDER BY id
LIMIT 5;

▶ Run this query in the SQL Playground

The same page 3, found by the last id instead of OFFSET
idnameprice
11Blender Pro 1200W1732.92
12Ergonomic Desk Mat XL1749.7
13Retinol Eye Cream 30ml684.54
14Play Kitchen Deluxe1840.63
15Japanese Green Tea 50 bags1810.45
✓ 5 rows · real output from the Playground database

It returns the same rows as the OFFSET version, but the cost no longer grows with the page number. The trade-off: you can only move to the next or previous page, not jump straight to page 400.

LIMIT vs TOP vs FETCH FIRST

The idea is the same everywhere; the syntax is not:

DatabaseFirst 5 rowsRows 11 to 15
SQLite, MySQL, PostgreSQL... ORDER BY x LIMIT 5LIMIT 5 OFFSET 10 (MySQL also LIMIT 10, 5)
SQL ServerSELECT TOP 5 ... ORDER BY xORDER BY x OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY
Standard SQL (PostgreSQL, Oracle 12c+, SQL Server 2012+, DB2)ORDER BY x FETCH FIRST 5 ROWS ONLYOFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY
Oracle 11g and olderWHERE ROWNUM <= 5 (applied before ORDER BY, so sort in a subquery)Nested subqueries with ROWNUM
SQL · SQL Server and standard SQL
-- SQL Server
SELECT TOP 5 first_name, salary
FROM employees
ORDER BY salary DESC;

-- SQL Server: include rows tied with the 5th
SELECT TOP 5 WITH TIES first_name, salary
FROM employees
ORDER BY salary DESC;

-- Standard SQL
SELECT first_name, salary
FROM employees
ORDER BY salary DESC
FETCH FIRST 5 ROWS ONLY;

SQLite (the Playground) supports LIMIT and OFFSET but not TOP or FETCH FIRST.

LIMIT and Performance

SituationEffect of LIMIT
ORDER BY on an indexed columnThe database reads the first N entries of the index and stops: very fast
ORDER BY on an unindexed columnIt still sorts, but can keep just the best N rows while doing so
GROUP BY or DISTINCT before LIMITThe grouping has to finish first; LIMIT only cuts the output
Large OFFSETEvery skipped row is still read; prefer keyset pagination

Common LIMIT Mistakes

Five errors and how to avoid them.

1. LIMIT without ORDER BY

❌ Arbitrary rows
SQL
SELECT * FROM orders
LIMIT 5;  -- "the latest orders"?
✅ Defined order
SQL
SELECT * FROM orders
ORDER BY order_date DESC, id DESC
LIMIT 5;

Without ORDER BY the database returns whichever rows it reaches first.

2. Sorting the wrong way for "top"

❌ The three lowest salaries
SQL
SELECT * FROM employees
ORDER BY salary
LIMIT 3;
✅ The three highest
SQL
SELECT * FROM employees
ORDER BY salary DESC
LIMIT 3;

ORDER BY is ascending by default, so LIMIT keeps the smallest values.

3. Off-by-one with OFFSET

❌ Skips page 2
SQL
-- page 2, 20 per page
LIMIT 20 OFFSET 40
✅ (page - 1) × size
SQL
LIMIT 20 OFFSET 20

Page 1 starts at OFFSET 0, so page n starts at (n - 1) × page size.

4. Using TOP in SQLite or MySQL

❌ Syntax error
SQL
SELECT TOP 5 * FROM products
ORDER BY price DESC;
✅ LIMIT
SQL
SELECT * FROM products
ORDER BY price DESC
LIMIT 5;

TOP is SQL Server syntax. The Playground runs SQLite.

5. Nth highest without DISTINCT

❌ May repeat the highest value
SQL
SELECT total FROM orders
ORDER BY total DESC
LIMIT 1 OFFSET 1;
✅ Distinct values first
SQL
SELECT DISTINCT total FROM orders
ORDER BY total DESC
LIMIT 1 OFFSET 1;

If two rows share the top value, the first version returns that value again.

LIMIT Cheat Sheet

TaskSQLite / PostgreSQL / MySQL
First N rowsORDER BY x LIMIT N
Top N highestORDER BY x DESC LIMIT N
Skip M, then NLIMIT N OFFSET M
Page p of size sLIMIT s OFFSET (p - 1) * s
Nth highest distinctSELECT DISTINCT x ... ORDER BY x DESC LIMIT 1 OFFSET N - 1
Next page (keyset)WHERE id > :last_id ORDER BY id LIMIT s

Practice LIMIT Queries

5 exercises on the real Playground tables.

Write each query yourself first. Every solution has been run against the Playground database.

  1. 1Easy Show the 5 cheapest products. Table: products

    Show solution
    SQLite · runs in the Playground
    SELECT name, price
    FROM products
    ORDER BY price
    LIMIT 5;

    ▶ Run this query in the SQL Playground

    Ascending order puts the lowest prices first.

  2. 2Easy Show the 3 most recent orders. Table: orders

    Show solution
    SQLite · runs in the Playground
    SELECT id, order_date, total
    FROM orders
    ORDER BY order_date DESC, id DESC
    LIMIT 3;

    ▶ Run this query in the SQL Playground

    id breaks ties between orders on the same date.

  3. 3Medium Show page 2 of the employee list sorted by last name, with 10 employees per page. Table: employees

    Show solution
    SQLite · runs in the Playground
    SELECT last_name, first_name, department
    FROM employees
    ORDER BY last_name, first_name, id
    LIMIT 10 OFFSET 10;

    ▶ Run this query in the SQL Playground

    Page 2 skips the first page of 10.

  4. 4Medium Find the third-highest distinct salary. Table: employees

    Show solution
    SQLite · runs in the Playground
    SELECT DISTINCT salary
    FROM employees
    ORDER BY salary DESC
    LIMIT 1 OFFSET 2;

    ▶ Run this query in the SQL Playground

    OFFSET 2 skips the two highest distinct salaries.

  5. 5Medium Show the 3 product categories with the most products. Table: products

    Show solution
    SQLite · runs in the Playground
    SELECT category, COUNT(*) AS products
    FROM products
    GROUP BY category
    ORDER BY products DESC, category
    LIMIT 3;

    ▶ Run this query in the SQL Playground

    LIMIT applies after grouping and sorting.

📝 Quiz — LIMIT

Test your understanding · 0/10 answered

Question 1 of 10

What does LIMIT do in SQL?

Question 2 of 10

Can LIMIT be used without ORDER BY?

Question 3 of 10

Which clause should come right before LIMIT for a predictable top N?

Question 4 of 10

What does OFFSET do?

Question 5 of 10

Which keyword does SQL Server use instead of LIMIT?

Question 6 of 10

Which is the standard SQL syntax for limiting rows?

Question 7 of 10

Which rows does LIMIT 10 OFFSET 20 return?

Question 8 of 10

Why can a very large OFFSET be slow?

Question 9 of 10

Which query returns the three highest salaries?

Question 10 of 10

With 20 rows per page, which page is LIMIT 20 OFFSET 40?

LIMIT Interview Questions

Q1. How do you get the Nth highest value with LIMIT?

SELECT DISTINCT x FROM t ORDER BY x DESC LIMIT 1 OFFSET N - 1. DISTINCT stops repeated values from shifting the answer.

Q2. What is the difference between LIMIT, TOP and FETCH FIRST?

They do the same job. LIMIT (with OFFSET) is used by SQLite, MySQL and PostgreSQL; TOP by SQL Server, written after SELECT; FETCH FIRST n ROWS ONLY is the SQL standard, supported by PostgreSQL, Oracle 12c+, SQL Server 2012+ and DB2.

Q3. Why is OFFSET pagination slow for deep pages, and what is the alternative?

The database must produce and discard every skipped row. Keyset pagination filters on the last seen key (WHERE id > :last_id ORDER BY id LIMIT 20), which an index answers directly.

Q4. What happens with ties at the LIMIT boundary?

One of the tied rows is chosen arbitrarily. Add a unique tie-breaker to ORDER BY, use SQL Server's TOP ... WITH TIES, or use RANK() to include all tied rows.

Q5. When is LIMIT applied in the order of execution?

Last: after FROM, WHERE, GROUP BY, HAVING, SELECT and ORDER BY.

Frequently Asked Questions

What is LIMIT in SQL?

LIMIT is a clause, used by MySQL, PostgreSQL and SQLite, that restricts how many rows a query returns. SELECT * FROM employees LIMIT 5 returns at most five rows, however many match.

How does LIMIT work in SQL?

LIMIT is applied after every other clause: the database builds the result, sorts it if there is an ORDER BY, and then returns only the first n rows.

Can LIMIT be used without ORDER BY?

Yes, it is valid, but the rows you get are not guaranteed to be the same each time. Use ORDER BY whenever you care which rows come back.

What is LIMIT and OFFSET in SQL?

LIMIT sets how many rows to return; OFFSET sets how many to skip first. LIMIT 10 OFFSET 20 skips 20 rows and returns the next 10, rows 21 to 30. Together they are used for pagination.

How do I get the top 5 rows in SQL?

Combine ORDER BY with LIMIT: SELECT * FROM products ORDER BY price DESC LIMIT 5 returns the five most expensive products. In SQL Server use SELECT TOP 5 * FROM products ORDER BY price DESC.

What is the difference between LIMIT and TOP?

LIMIT is used by MySQL, PostgreSQL and SQLite and is written at the end of the query. TOP is the SQL Server equivalent and is written right after SELECT. Both restrict the number of rows returned.

What is FETCH FIRST ROWS ONLY?

FETCH FIRST n ROWS ONLY is the standard SQL way to limit rows, supported by PostgreSQL, Oracle 12c+, SQL Server 2012+ and DB2. It can follow OFFSET n ROWS to skip rows first. SQLite does not support it.

How do you paginate data in SQL?

Choose a page size, then use LIMIT page_size OFFSET (page_number - 1) * page_size. For deep pages on large tables, keyset pagination (WHERE id > last_id ORDER BY id LIMIT page_size) is faster.

Is LIMIT faster than fetching all rows?

Usually, yes. Fewer rows are sent to the client, and with an index on the ORDER BY column the database can stop after the first N rows. With GROUP BY or a large OFFSET, the work before the cut still has to be done.

What are common LIMIT interview questions?

LIMIT versus TOP, why LIMIT needs ORDER BY, what OFFSET does, how pagination works, how to find the Nth highest value and why large OFFSET values are slow.