Beginner: asking questions · SELECT: filtering and sorting · topic 9 of 62 · 30 min
ORDER BY, LIMIT and OFFSET
Explanation
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.
SELECT name, price FROM products ORDER BY price DESC;
-- Running Shoes | 2499
-- Bluetooth Earbuds | 1999
-- Pressure Cooker 3L | 1450
-- ...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.
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 | NULLText 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.
SELECT name, marks FROM students ORDER BY marks NULLS LAST;
-- Arjun Reddy | 45
-- ...
-- Priya Nair | 91
-- Sneha Patil | NULLLIMIT: top-N lists
SELECT name, price FROM products ORDER BY price DESC LIMIT 3;
-- Running Shoes | 2499
-- Bluetooth Earbuds | 1999
-- Pressure Cooker 3L | 1450OFFSET: 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.
-- 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 NairTies
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
| Database | First 3 rows |
|---|---|
| SQLite, PostgreSQL, MySQL | ORDER BY price DESC LIMIT 3 |
| SQL Server | SELECT 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
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.
SELECT id, name, price
FROM products
WHERE category = 'Electronics'
ORDER BY price DESC, id
LIMIT 20 OFFSET 0; -- page 1Practice (0/4 done)
Show the 3 most expensive products, most expensive first. Return name and price.
A list shows 3 students per page, sorted by name A to Z. Return page 2: columns id and name.
List students by city A to Z, and inside each city by marks from highest to lowest. Return name, city and marks.
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- DISTINCT and how a query runsSELECT: filtering and sorting · same module
- WHERE: comparison and logicSELECT: filtering and sorting · same module
- ORDER BY, LIMIT and DISTINCTBackend Development · Databases and SQL basics
- GROUP BYAggregation: GROUP BY and HAVING
- Classic interview queries, part 1Interview questions and practice projects
- INSERTChanging data, transactions and ACID
Questions people ask about this
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.
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.
A column is left out of an INSERT and has no DEFAULT and no NOT NULL. What value does it get?Related
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 more topic in “SELECT: filtering and sorting” before its exam: DISTINCT and how a query runs.
- Module 2 exam: SELECT, filtering and sorting · 15 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Functions, CASE and NULL. 62 topics left in the course before the final exam.