SQL: ORDER BY and LIMIT
ORDER BY sorts the result, LIMIT restricts the rows.
Rules
- ORDER BY column ASC or DESC
- Several sort keys with commas
- LIMIT goes at the very end
Your turn
Three problems on this topic. You can run the query first.
- 1 · ORDER BY
- 2
- 3
List the 3 courses with the most credits: title and credits (ties by title).
courses
| id | title | credits | lecturer |
|---|---|---|---|
| 1 | Calculus | 3 | Huber |
| 2 | Law | 6 | Meier |
| 3 | Databases | 3 | Weber |
| 4 | Marketing | 6 | Meier |
+ − More tables: students, grades
students
| id | name | major | semester | city |
|---|---|---|---|---|
| 1 | David | Computing | 6 | Basel |
| 2 | Anna | Computing | 3 | Wien |
| 3 | Lena | Chemistry | 1 | Wien |
| 4 | Clara | Computing | 2 | Basel |
| 5 | Nora | Computing | 6 | Zürich |
| 6 | Ben | Business | 7 | Berlin |
| 7 | Hannah | Business | 8 | Berlin |
grades
| student_id | course_id | grade |
|---|---|---|
| 3 | 3 | 3.7 |
| 4 | 1 | 3.7 |
| 5 | 4 | 1.3 |
| 4 | 3 | 1.3 |
| 4 | 4 | 3 |
| 2 | 2 | 3.7 |
| 4 | 2 | 2.3 |
| 5 | 1 | 2.3 |
| 3 | 2 | 2.7 |
| 1 | 1 | 2.7 |
| 6 | 3 | 3.3 |
| 7 | 3 | 2.7 |
| 1 | 3 | 3.7 |
SQL
Any equivalent query counts. It is also checked on data you can’t see.
Worked example
List the 4 courses with the most credits: title and credits (ties by title).
courses
| id | title | credits | lecturer |
|---|---|---|---|
| 1 | Calculus | 3 | Meier |
| 2 | Law | 4 | Keller |
| 3 | Databases | 6 | Weber |
| 4 | Statistics | 5 | Meier |
+ − More tables: students, grades
students
| id | name | major | semester | city |
|---|---|---|---|---|
| 1 | Anna | Chemistry | 4 | Wien |
| 2 | Felix | Chemistry | 4 | Bern |
| 3 | David | Law | 5 | Bern |
| 4 | Nora | Business | 1 | Basel |
| 5 | Jonas | Chemistry | 7 | Zürich |
| 6 | Eva | Business | 6 | Berlin |
| 7 | Greta | Law | 1 | Berlin |
grades
| student_id | course_id | grade |
|---|---|---|
| 2 | 3 | 4 |
| 3 | 3 | 3.7 |
| 2 | 4 | 2.3 |
| 7 | 2 | 1.3 |
| 1 | 1 | 1.7 |
| 7 | 3 | 3.7 |
| 4 | 4 | 2.3 |
| 7 | 4 | 2.7 |
| 1 | 2 | 3.3 |
| 2 | 1 | 1.3 |
| 5 | 1 | 1 |
| 5 | 2 | 3.7 |
| 3 | 1 | 1.3 |
Worked solution
SELECT title, credits FROM courses ORDER BY credits DESC, title ASC LIMIT 4
Result on the sample data:
title | credits
Databases | 6
Statistics | 5
Law | 4
Calculus | 3
Typical mistake: LIMIT goes at the very end of the query.
Common questions
What order do the clauses go in?
SELECT, FROM, JOIN, WHERE, GROUP BY, HAVING, ORDER BY, LIMIT.
