Skip to content

Beginner: asking questions · SELECT: filtering and sorting · topic 9 of 62 · 30 min

ORDER BY, LIMIT and OFFSET

Explanation

Without ORDER BY, rows come back in no promised order. ORDER BY sorts by one or more columns, each ASC (smallest first, the default) or DESC. LIMIT keeps the first n rows and OFFSET skips some, which gives top-N lists and pages. SQLite puts NULLs first in ascending order unless you write NULLS LAST.

Why ORDER BY?

A table is a set of rows with no built-in order. The order you see without ORDER BY is whatever was fastest for the database today, and it can change after an update or a new index. If the order matters, say so with ORDER BY.

sql
SELECT name, price FROM products ORDER BY price DESC;
-- Running Shoes        | 2499
-- Bluetooth Earbuds    | 1999
-- Pressure Cooker 3L   | 1450
-- ...
DESC means descending: biggest first. ASC (ascending, smallest first) is the default.

Sorting by many columns

List several columns, each with its own direction. The second column is used only to break ties in the first, the third only to break ties in the first two, and so on.

sql
SELECT name, city, marks FROM students ORDER BY city, marks DESC;
-- Priya Nair  | Chennai   | 91
-- Divya Kumar | Delhi     | 88
-- Ravi Kumar  | Delhi     | 67
-- ...
-- Asha Verma  | Pune      | 76
-- Imran Khan  | Pune      | 58
-- Sneha Patil | Pune      | NULL
Cities A to Z; inside each city, highest marks first. DESC applies only to marks.

Text is sorted by character codes by default in SQLite, so capital letters come before small letters: 'Zebra' sorts before 'apple'. Store names in a consistent case, or sort with ORDER BY name COLLATE NOCASE.

Where do NULLs go?

SQLite treats NULL as smaller than every value. So NULLs come first in ASC and last in DESC. Other databases differ: PostgreSQL and Oracle put NULLs last in ASC, while MySQL and SQL Server put them first. SQLite (since 3.30) and PostgreSQL let you choose with NULLS FIRST or NULLS LAST.

sql
SELECT name, marks FROM students ORDER BY marks NULLS LAST;
-- Arjun Reddy | 45
-- ...
-- Priya Nair  | 91
-- Sneha Patil | NULL
Without NULLS LAST, Sneha would be first.

LIMIT: top-N lists

sql
SELECT name, price FROM products ORDER BY price DESC LIMIT 3;
-- Running Shoes      | 2499
-- Bluetooth Earbuds  | 1999
-- Pressure Cooker 3L | 1450
The three most expensive products. LIMIT without ORDER BY gives "any 3 rows", which is rarely what you want.

OFFSET: pages

OFFSET skips rows before LIMIT starts counting. Apps use it for pages: with page_size rows per page, page n is LIMIT page_size OFFSET (n − 1) × page_size. Page 1 has OFFSET 0, page 2 OFFSET page_size, and so on.

sql
-- 3 students per page, sorted by name. Page 2:
SELECT id, name FROM students ORDER BY name LIMIT 3 OFFSET 3;
-- 4 | Imran Khan
-- 8 | Karan Mehta
-- 3 | Priya Nair
Tip: A large OFFSET is slow, because the database still reads and throws away all the skipped rows. Big apps use "keyset" paging instead (WHERE name > last_name_seen), which module 10 covers.

Ties

Anita Desai and Vikram Singh both earn 95000. In ORDER BY salary DESC LIMIT 5, which of them is fifth? The database may pick either, and the choice can change. Add a tie-breaker column, such as ORDER BY salary DESC, name, so the result is always the same. PostgreSQL 13 and later can also keep every tied row with FETCH FIRST 5 ROWS WITH TIES.

Other dialects

DatabaseFirst 3 rows
SQLite, PostgreSQL, MySQLORDER BY price DESC LIMIT 3
SQL ServerSELECT TOP 3 ... ORDER BY price DESC
SQL standard (PostgreSQL, Oracle 12c+, SQL Server with OFFSET)ORDER BY price DESC FETCH FIRST 3 ROWS ONLY

Common mistakes

  • Using LIMIT without ORDER BY and expecting the "top" rows. Always sort first.
  • Putting DESC once and expecting it to apply to every column. ORDER BY city, marks DESC sorts city ascending.
  • Off-by-one page maths: page 2 with 10 per page is OFFSET 10, not OFFSET 20.
  • Forgetting where NULLs land. Add NULLS LAST (or NULLS FIRST) when it matters.
  • Writing ORDER BY 2 (the column position). It works, but breaks silently when someone changes the SELECT list. Use the column name.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

ORDER BY, LIMIT and OFFSET · 1/8

ORDER BY, LIMIT, OFFSET

Without ORDER BY, rows come back in no promised order. If order matters, ask for it.

Prefer a video by a teacher? Find free videos on “sql order by limit offset pagination nulls last” on YouTube ↗

In real life: Search results on a shopping app

When you sort a product list by "Price: High to Low" on a shopping app, the server runs a query with ORDER BY price DESC and a tie-breaker, and shows 20 results per page. Scrolling to page 3 asks the database for LIMIT 20 OFFSET 40, or, in bigger systems, for the next 20 after the last product you saw.

sql
SELECT id, name, price
FROM products
WHERE category = 'Electronics'
ORDER BY price DESC, id
LIMIT 20 OFFSET 0;   -- page 1
In SHOP this returns the Earbuds (1999) and the Power Bank (1299).

Practice (0/4 done)

Task 1 · Code · SQL

Show the 3 most expensive products, most expensive first. Return name and price.

Task 2 · Code · SQL

A list shows 3 students per page, sorted by name A to Z. Return page 2: columns id and name.

Task 3 · Code · SQL

List students by city A to Z, and inside each city by marks from highest to lowest. Return name, city and marks.

Task 4 · Code · SQL

List students from the lowest marks to the highest, but put the student with no marks at the END. Return name and marks.

Quick quiz

Question 1

1.Pages have 10 rows each. Which clause gives page 4?

Question 2

2.In ORDER BY city, marks DESC, how is city sorted?

Question 3

3.In SQLite, where do NULLs go in ORDER BY marks (ascending)?

Question 4

4.You run SELECT name FROM products LIMIT 3 with no ORDER BY. Which 3 rows do you get?

Question 5

5.Two employees tie on salary. How do you make ORDER BY salary DESC LIMIT 5 give the same rows every time?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Pages have 10 rows each. Which clause gives page 4?

Answer: LIMIT 10 OFFSET 30

Page n skips (n − 1) × 10 = 30 rows.

In ORDER BY city, marks DESC, how is city sorted?

Answer: Ascending, because DESC applies only to marks

Each column has its own direction, and ASC is the default.

In SQLite, where do NULLs go in ORDER BY marks (ascending)?

Answer: First

SQLite treats NULL as smaller than every value. Use NULLS LAST to move them.

You run SELECT name FROM products LIMIT 3 with no ORDER BY. Which 3 rows do you get?

Answer: Any 3 rows; the order is not promised

Without ORDER BY there is no guaranteed order.

Two employees tie on salary. How do you make ORDER BY salary DESC LIMIT 5 give the same rows every time?

Answer: Add a tie-breaker, such as ORDER BY salary DESC, id

A second sort column decides between tied rows.

What does ORDER BY marks DESC do?Related

Answer: Sorts from highest to lowest marks

DESC means descending: big to small.

From ORDER BY, LIMIT and DISTINCT

Your GROUP BY results came out sorted by city in SQLite. Is that guaranteed?Related

Answer: No; add ORDER BY if the order matters

Any order without ORDER BY is a side effect that can change.

From GROUP BY

Salaries are 100, 100, 90, 80. What does SELECT salary FROM t ORDER BY salary DESC LIMIT 1 OFFSET 1 return?Related

Answer: 100

Without DISTINCT the second row is the second 100. Add DISTINCT to get 90.

From Classic interview queries, part 1

A column is left out of an INSERT and has no DEFAULT and no NOT NULL. What value does it get?Related

Answer: NULL

With no default, a missing column becomes NULL.

From INSERT

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 1 more topic in “SELECT: filtering and sorting” before its exam: DISTINCT and how a query runs.
  2. Module 2 exam: SELECT, filtering and sorting · 15 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Functions, CASE and NULL. 62 topics left in the course before the final exam.

← Previous: IN, BETWEEN, LIKE and NULL