Database ORDER BY and LIMIT
What you will learn
- Why a result has no guaranteed order unless you ask
- How to sort with ORDER BY, ASC and DESC
- How to sort by more than one column
- How to take only some rows with LIMIT and OFFSET
This lesson runs on the sample database you chose in lesson 4.1. Use the Example data picker at the top to change it.
1. Rows have no built-in order
A table is a set of rows, not a numbered list. If you do not say how to order a result, the database may return rows in any order. It often looks sorted (for example by the id), but that is luck, not a promise. When order matters, always write ORDER BY.
2. ORDER BY
ORDER BY sorts the result. The default is ASC (ascending, smallest first); add DESC for the opposite.
SELECT name, price FROM products ORDER BY price LIMIT 5;
SELECT name, price FROM products ORDER BY price DESC LIMIT 5;
name price
------------ -----
Day backpack 4.5
Footrest 4.95
Glass jar 5.4
Steel pan 6.6
Wall planner 6.6
(5 rows)
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 LIMIT 5;
SELECT account_id, balance_cents FROM accounts ORDER BY balance_cents DESC LIMIT 5;
account_id balance_cents
---------- -------------
330 1300
23 2700
405 4300
331 4800
370 5300
(5 rows)
account_id balance_cents
---------- -------------
398 502080
243 432800
165 428004
238 401600
295 379900
(5 rows)
SELECT code, title FROM courses ORDER BY title LIMIT 5;
SELECT code, title FROM courses ORDER BY title DESC LIMIT 5;
code title
------ ----------------
SCI301 Biology
SCI201 Chemistry
HUM301 Civics
CS101 Computing Basics
CS301 Databases
(5 rows)
code title
------- ---------------
LANG101 Writing Skills
HUM101 World History
MATH301 Statistics
LANG201 Second Language
LANG102 Reading Circle
(5 rows)
Text sorts alphabetically, dates written as 2026-03-01 sort correctly because the year comes first.
3. Several columns
List more than one column: later columns break ties in earlier ones.
SELECT category_id, name, price FROM products ORDER BY category_id, price DESC LIMIT 8;
category_id name price
----------- ---------------- -----
2 Tea kettle 79.0
2 Ceramic mug 44.1
2 Wooden spoon set 29.5
2 Lunch box 29.5
2 Chopping board 26.4
2 Steel pan 6.6
2 Glass jar 5.4
3 Plant pot 42.9
(8 rows)
Categories are sorted from the lowest number up; inside each category the dearer product comes first.
SELECT account_type, account_id, balance_cents FROM accounts ORDER BY account_type, balance_cents DESC LIMIT 8;
account_type account_id balance_cents
------------ ---------- -------------
checking 243 432800
checking 238 401600
checking 295 379900
checking 186 371700
checking 178 371600
checking 122 364200
checking 127 361100
checking 200 360300
(8 rows)
Account types are sorted A to Z; inside each type the account with the biggest balance comes first.
SELECT department_id, code, credits FROM courses ORDER BY department_id, credits DESC, code LIMIT 8;
department_id code credits
------------- ------- -------
1 MATH101 4
1 MATH301 4
1 MATH201 3
2 SCI101 4
2 SCI201 4
2 SCI202 4
2 SCI301 3
3 LANG101 3
(8 rows)
Departments are sorted from the lowest number up; inside each department the course with the most credits comes first, and the code settles ties.
4. NULL in a sort
Orders that have not shipped have shipped_on set to NULL:
SELECT order_id, shipped_on FROM orders ORDER BY shipped_on, order_id LIMIT 5;
SELECT order_id, shipped_on FROM orders ORDER BY shipped_on DESC, order_id LIMIT 5;
order_id shipped_on
-------- ----------
4 NULL
15 NULL
16 NULL
23 NULL
24 NULL
(5 rows)
order_id shipped_on
-------- ----------
17 2026-10-05
543 2026-10-04
285 2026-10-01
836 2026-10-01
522 2026-09-30
(5 rows)
Some audit log rows have a note set to NULL:
SELECT log_id, note FROM audit_log ORDER BY note, log_id LIMIT 5;
SELECT log_id, note FROM audit_log ORDER BY note DESC, log_id LIMIT 5;
log_id note
------ ----
1 NULL
2 NULL
6 NULL
7 NULL
8 NULL
(5 rows)
log_id note
------ --------------
4 status changed
5 status changed
15 status changed
22 status changed
27 status changed
(5 rows)
A student's grade is NULL until the teacher has given one:
SELECT student_id, section_id, grade FROM enrollments ORDER BY grade, student_id, section_id LIMIT 5;
SELECT student_id, section_id, grade FROM enrollments ORDER BY grade DESC, student_id, section_id LIMIT 5;
student_id section_id grade
---------- ---------- -----
1 19 NULL
2 4 NULL
3 25 NULL
6 22 NULL
7 14 NULL
(5 rows)
student_id section_id grade
---------- ---------- -----
5 16 100.0
12 24 100.0
16 5 100.0
37 17 100.0
107 12 100.0
(5 rows)
In SQLite, NULL sorts first in ascending order and last in descending order. Do not rely on this: check the documentation of the system you use. The extra id column in ORDER BY fixes the order of rows that are tied; without it, their order is not defined by the query.
5. LIMIT and OFFSET
LIMIT n keeps only the first n rows. With ORDER BY it answers "top n" questions. OFFSET k skips the first k rows, which is how pages of results are made.
SELECT name, price FROM products ORDER BY price DESC LIMIT 3;
SELECT name, price FROM products ORDER BY price DESC LIMIT 3 OFFSET 3;
name price
------------ -----
Water bottle 86.9
Tea kettle 79.0
Highlighters 79.0
(3 rows)
name price
----------- -----
Foam roller 79.0
Drawing kit 53.9
Bookshelf 49.0
(3 rows)
The first query is "the three dearest products"; the second skips those three and shows the next three, "page 2".
SELECT account_id, balance_cents FROM accounts ORDER BY balance_cents DESC LIMIT 3;
SELECT account_id, balance_cents FROM accounts ORDER BY balance_cents DESC LIMIT 3 OFFSET 3;
account_id balance_cents
---------- -------------
398 502080
243 432800
165 428004
(3 rows)
account_id balance_cents
---------- -------------
238 401600
295 379900
186 371700
(3 rows)
The first query is "the three biggest balances"; the second skips those three and shows the next three, "page 2".
SELECT code, title, credits FROM courses ORDER BY credits DESC, code LIMIT 3;
SELECT code, title, credits FROM courses ORDER BY credits DESC, code LIMIT 3 OFFSET 3;
code title credits
------- ---------------------- -------
CS201 Programming 4
CS301 Databases 4
MATH101 Foundations of Algebra 4
(3 rows)
code title credits
------- --------------- -------
MATH301 Statistics 4
SCI101 General Science 4
SCI201 Chemistry 4
(3 rows)
The first query is "the three courses with the most credits"; the second skips those three and shows the next three, "page 2".
(LIMIT is the SQLite way to write this; other systems may use different words, so check your system's documentation.)
Worked example: the three newest rows
The three newest orders:
SELECT order_id, order_date FROM orders ORDER BY order_date DESC, order_id DESC LIMIT 3;
order_id order_date
-------- ----------
1953 2026-09-30
1330 2026-09-30
543 2026-09-30
(3 rows)
Sorting by date descending puts the newest first, order_id DESC settles ties, and LIMIT 3 keeps three rows.
The three newest ledger entries:
SELECT txn_id, txn_date, kind FROM transactions ORDER BY txn_date DESC, txn_id DESC LIMIT 3;
txn_id txn_date kind
------ ---------- ------------
7415 2026-09-30 transfer_in
7414 2026-09-30 transfer_out
7413 2026-09-30 deposit
(3 rows)
Sorting by date descending puts the newest first, txn_id DESC settles ties, and LIMIT 3 keeps three rows.
The three assignments due last:
SELECT assignment_id, title, due_date FROM assignments ORDER BY due_date DESC, assignment_id DESC LIMIT 3;
assignment_id title due_date
------------- ------ ----------
109 Quiz 2 2026-05-03
138 Essay 2026-05-02
163 Essay 2026-04-30
(3 rows)
Sorting by date descending puts the latest first, assignment_id DESC settles ties, and LIMIT 3 keeps three rows. (Everything is made up.)
Common mistakes
- Using
LIMITwithoutORDER BY. You get some rows, but not a meaningful "first". - Assuming a result is sorted because it looked sorted once.
- Forgetting
DESC. The default is ascending. - Sorting dates written in other formats such as
03/04/2026: they sort as text, not as dates. Use year-month-day.
Key takeaways
- Without
ORDER BY, row order is not guaranteed. ORDER BY column [DESC]; extra columns break ties.LIMIT nkeeps n rows;OFFSET kskips k rows.- Where
NULLsorts can differ between systems; check the documentation.
Practice
1. Write a query that lists something by name or title from A to Z.
Show answer
SELECT name FROM products ORDER BY name; lists the product names from A to Z.
Show answer
SELECT full_name FROM customers ORDER BY full_name; lists the customer names from A to Z.
Show answer
SELECT title FROM courses ORDER BY title; lists the course titles from A to Z.
2. Write a query for the single biggest (or cheapest) one.
Show answer
SELECT name, price FROM products ORDER BY price LIMIT 1; returns the cheapest product.
Show answer
SELECT account_id, balance_cents FROM accounts ORDER BY balance_cents DESC LIMIT 1; returns the account with the biggest balance.
Show answer
SELECT code, credits FROM courses ORDER BY credits DESC, code LIMIT 1; returns a course with the most credits (the code settles ties).
3. Why should you not use LIMIT without ORDER BY?
Show answer
Without an order, "the first rows" can be any rows.
4. What does ORDER BY a, b DESC do?
Show answer
It sorts by a first and, among rows with the same a, puts the highest b first.
5. Write the query for "page 2" if each page shows 5 rows ordered by name or title.
Show answer
SELECT name FROM products ORDER BY name LIMIT 5 OFFSET 5;
Show answer
SELECT full_name FROM customers ORDER BY full_name LIMIT 5 OFFSET 5;
Show answer
SELECT title FROM courses ORDER BY title LIMIT 5 OFFSET 5;
6. Why are dates written as 2026-03-01 easy to sort?
Show answer
The biggest unit (year) comes first, so sorting the text also sorts the dates.