CleverSphere

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. 1 · ORDER BY
  2. 2
  3. 3

List the 3 courses with the most credits: title and credits (ties by title).

courses

idtitlecreditslecturer
1Calculus3Huber
2Law6Meier
3Databases3Weber
4Marketing6Meier
+ More tables: students, grades

students

idnamemajorsemestercity
1DavidComputing6Basel
2AnnaComputing3Wien
3LenaChemistry1Wien
4ClaraComputing2Basel
5NoraComputing6Zürich
6BenBusiness7Berlin
7HannahBusiness8Berlin

grades

student_idcourse_idgrade
333.7
413.7
541.3
431.3
443
223.7
422.3
512.3
322.7
112.7
633.3
732.7
133.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

idtitlecreditslecturer
1Calculus3Meier
2Law4Keller
3Databases6Weber
4Statistics5Meier
+ More tables: students, grades

students

idnamemajorsemestercity
1AnnaChemistry4Wien
2FelixChemistry4Bern
3DavidLaw5Bern
4NoraBusiness1Basel
5JonasChemistry7Zürich
6EvaBusiness6Berlin
7GretaLaw1Berlin

grades

student_idcourse_idgrade
234
333.7
242.3
721.3
111.7
733.7
442.3
742.7
123.3
211.3
511
523.7
311.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.

Related

More topics