Filtering and Sorting · Lesson 15 of 64

SQL LIMIT and OFFSET

What you will learn

  • How LIMIT keeps only the first rows
  • How OFFSET skips rows, to build pages
  • Why a stable ORDER BY is needed with both
  • How to write a top N query

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Edit any query and press Run. Reset data puts the original rows back.

1. LIMIT

LIMIT n keeps the first n rows of the result. It comes last in the query. You have used it to keep results short:

SELECT customer_id, first_name, last_name FROM customers ORDER BY customer_id LIMIT 3;
customer_id  first_name  last_name
-----------  ----------  ---------
          1  Vik         Ahmed
          2  Wanda       Ahmed
          3  Dana        Costa
(3 rows)
SELECT customer_id, full_name FROM customers ORDER BY customer_id LIMIT 3;
customer_id  full_name
-----------  -----------
          1  Chen Park
          2  Rafi Uddin
          3  Grace Kamau
(3 rows)
SELECT student_id, first_name, last_name FROM students ORDER BY student_id LIMIT 3;
student_id  first_name  last_name
----------  ----------  ---------
         1  Vera        Khan
         2  Elena       Haque
         3  Chloe       Garcia
(3 rows)

LIMIT with no ORDER BY returns "some" rows, not the first by any rule. Always combine them (lesson 2.6).

2. Top N

"The five most expensive", "the three newest": sort so the wanted rows come first, then limit:

SELECT name, price FROM products ORDER BY price DESC, product_id LIMIT 5;
name          price
------------  -----
Water bottle   86.9
Tea kettle     79.0
Highlighters   79.0
Foam roller    79.0
Drawing kit    53.9
(5 rows)
SELECT account_id, balance_cents FROM accounts ORDER BY balance_cents DESC, account_id LIMIT 5;
account_id  balance_cents
----------  -------------
       398         502080
       243         432800
       165         428004
       238         401600
       295         379900
(5 rows)
SELECT student_id, first_name, birth_date FROM students ORDER BY birth_date DESC, student_id LIMIT 5;
student_id  first_name  birth_date
----------  ----------  ----------
       197  Omar        2013-12-31
       211  Chen        2013-12-22
       115  Ines        2013-12-21
       334  Wei         2013-11-08
       270  Elena       2013-11-03
(5 rows)

The second sort column (product_id and so on) breaks ties so the five rows are always the same ones.

3. OFFSET: skip rows

OFFSET m skips the first m rows. With LIMIT n it gives page-like slices. Page 1 is the first 3 rows, page 2 skips 3 and shows the next 3, and so on:

SELECT customer_id, last_name FROM customers ORDER BY customer_id LIMIT 3 OFFSET 0;
SELECT customer_id, last_name FROM customers ORDER BY customer_id LIMIT 3 OFFSET 3;
SELECT customer_id, last_name FROM customers ORDER BY customer_id LIMIT 3 OFFSET 6;
customer_id  last_name
-----------  ---------
          1  Ahmed
          2  Ahmed
          3  Costa
(3 rows)

customer_id  last_name
-----------  ---------
          4  Nair
          5  Rossi
          6  Nair
(3 rows)

customer_id  last_name
-----------  ---------
          7  Rahman
          8  Patel
          9  Lee
(3 rows)
SELECT customer_id, full_name FROM customers ORDER BY customer_id LIMIT 3 OFFSET 0;
SELECT customer_id, full_name FROM customers ORDER BY customer_id LIMIT 3 OFFSET 3;
SELECT customer_id, full_name FROM customers ORDER BY customer_id LIMIT 3 OFFSET 6;
customer_id  full_name
-----------  -----------
          1  Chen Park
          2  Rafi Uddin
          3  Grace Kamau
(3 rows)

customer_id  full_name
-----------  -----------
          4  Mei Bianchi
          5  Farid Lee
          6  Farid Park
(3 rows)

customer_id  full_name
-----------  -----------
          7  Olga Garcia
          8  Chen Kamau
          9  Grace Kamau
(3 rows)
SELECT student_id, last_name FROM students ORDER BY student_id LIMIT 3 OFFSET 0;
SELECT student_id, last_name FROM students ORDER BY student_id LIMIT 3 OFFSET 3;
SELECT student_id, last_name FROM students ORDER BY student_id LIMIT 3 OFFSET 6;
student_id  last_name
----------  ---------
         1  Khan
         2  Haque
         3  Garcia
(3 rows)

student_id  last_name
----------  ---------
         4  Meyer
         5  Torres
         6  Patel
(3 rows)

student_id  last_name
----------  ---------
         7  Ito
         8  Abdi
         9  Tanaka
(3 rows)

The formula for page number p with n rows per page is LIMIT n OFFSET (p - 1) * n. SQLite also accepts the short form LIMIT m, n (the offset first), but the long form is clearer and works in more databases.

4. Pages need a stable order

Pages only make sense if the order stays the same between requests. Without ORDER BY, page 2 could repeat or skip rows. With a unique column at the end of the sort (the id), each row lands on exactly one page.

A caution for later: a big OFFSET makes the database read and throw away all the skipped rows, so page 5,000 is slow. Lesson 7.8 of Database Fundamentals shows keyset paging (WHERE id > last_seen_id), which avoids it.

In other databases. PostgreSQL and MySQL also support LIMIT and OFFSET. The SQL standard way to limit rows is FETCH FIRST n ROWS ONLY; its availability differs between products, so check the documentation of the one you use.

5. The last rows, and the middle

To get the last rows, sort the other way and limit: ORDER BY id DESC LIMIT 3. To get "the third to fifth", skip two and take three:

SELECT product_id, name, price FROM products ORDER BY price DESC, product_id LIMIT 3 OFFSET 2;
product_id  name          price
----------  ------------  -----
        18  Highlighters   79.0
        37  Foam roller    79.0
        44  Drawing kit    53.9
(3 rows)
SELECT account_id, balance_cents FROM accounts ORDER BY balance_cents DESC, account_id LIMIT 3 OFFSET 2;
account_id  balance_cents
----------  -------------
       165         428004
       238         401600
       295         379900
(3 rows)
SELECT student_id, first_name, birth_date FROM students ORDER BY birth_date DESC, student_id LIMIT 3 OFFSET 2;
student_id  first_name  birth_date
----------  ----------  ----------
       115  Ines        2013-12-21
       334  Wei         2013-11-08
       270  Elena       2013-11-03
(3 rows)

Worked example: a "next page" button

A page lists 10 customers at a time, newest first.

Page Query ending
1 ORDER BY joined_on DESC, customer_id LIMIT 10 OFFSET 0
2 ORDER BY joined_on DESC, customer_id LIMIT 10 OFFSET 10
3 ORDER BY joined_on DESC, customer_id LIMIT 10 OFFSET 20

Same query, only the offset changes. The customer_id at the end makes the order stable even when many customers joined on the same day. The table is made up.

Common mistakes

  • LIMIT without ORDER BY. "First" means nothing without an order.
  • No tie-break column, so pages overlap or skip rows.
  • Counting the offset from 1. OFFSET 0 is the first page's start.
  • Very large offsets on big tables.
  • Writing LIMIT before ORDER BY. LIMIT is last.

Key takeaways

  • LIMIT n keeps n rows; OFFSET m skips m rows first.
  • Top N = ORDER BY the measure DESC (plus a tie-break) and LIMIT N.
  • Page p of size n: LIMIT n OFFSET (p - 1) * n, with a stable order.
  • Large offsets are slow; keyset paging is the cure.

Practice

1. Write a query for the three cheapest products.

Show answer

SELECT name, price FROM products ORDER BY price, product_id LIMIT 3;

2. What does LIMIT 5 OFFSET 10 return?

Show answer

Rows 11 to 15 of the sorted result: it skips ten rows and keeps five.

3. What are LIMIT and OFFSET for page 4 with 20 rows per page?

Show answer

LIMIT 20 OFFSET 60, because (4 - 1) * 20 = 60.

4. Why should the ORDER BY of a paged query end with a unique column?

Show answer

So rows with equal values always keep the same order and each row appears on exactly one page.

5. How do you get the last three rows by id?

Show answer

ORDER BY id DESC LIMIT 3.

6. Why is a very large OFFSET slow?

Show answer

The database still reads all the skipped rows before returning the page.