Lesson 13 of 30
43%
ORDER BY and LIMIT
ORDER BY sorts the result. LIMIT cuts it short.
The table on disk does not change. Only the answer you see is sorted.
A to Z and small to big
ASC is the default. DESC is reverse.
sql
Result
| name | age |
|---|---|
| Lin | 13 |
| Ada | 12 |
| Omar | 12 |
| Sam | 11 |
| Nia | 10 |
5 rows
Sort by two columns
First sort by city. If two rows share a city, sort those by name.
sql
Result
| name | city |
|---|---|
| Omar | Cairo |
| Sam | Kenya |
| Ada | London |
| Lin | Taipei |
| Nia | Unknown |
5 rows
LIMIT
LIMIT n keeps only the first n rows after sorting.
sql
Result
| name | age |
|---|---|
| Lin | 13 |
| Ada | 12 |
| Omar | 12 |
3 rows
OFFSET
OFFSET skips rows. Handy for page 2 of a list.
sql
Result
| name |
|---|
| Omar |
| Sam |
2 rows
Tip: Always ORDER BY if you use LIMIT. Without a sort, 'first 3' is not a promise.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.