← SQL and databases

Sorting with ORDER BY

Put the results in the order you want.

Start this lesson

A table has no guaranteed order. If you want rows sorted, say so with ORDER BY at the end of the query. ASC means smallest first (A to Z, oldest date first) and is the default; DESC means largest first. You can sort by several columns: the second one only breaks ties in the first.

SELECT name, grade_level FROM students
ORDER BY grade_level, name;

Sorts students by grade level. Within the same grade level, names are sorted A to Z.

ORDER BY comes after WHERE: SELECT … FROM … WHERE … ORDER BY …. The clauses always go in this order.

Even if a table looks sorted when you run SELECT *, that is luck. Only ORDER BY promises an order.