ORDER BY sorts the rows in a result set. Without it, a database makes no promise about what order rows come back in.
Basic Sorting
R Code
SELECT name, score FROM students ORDER BY score; -- ascending by default
Output
name | score Nadia | 65 Zayn | 76 Rafi | 88 Meera | 92
Descending Order
R Code
SELECT name, score FROM students ORDER BY score DESC;
Output
name | score Meera | 92 Rafi | 88 Zayn | 76 Nadia | 65
Sorting by Multiple Columns
Ties on the first sort column are broken by the second, and so on.
R Code
SELECT class, name, score FROM students ORDER BY class ASC, score DESC;
Output
class | name | score A | Meera | 92 A | Rafi | 88 B | Zayn | 76 B | Nadia | 65
Sorting by Column Position
R Code
SELECT name, score FROM students ORDER BY 2 DESC; -- sorts by the 2nd selected column, score
⚠ Common Mistake
Sorting by a column NUMBER (like ORDER BY 2) is fragile - if someone reorders the SELECT list later, the sort silently changes meaning. Prefer naming the column explicitly (ORDER BY score) except in quick, throwaway queries.Advanced: Custom Sort Order with CASE
🚀 Advanced Example
A CASE expression inside ORDER BY lets you define a custom, non-alphabetical sort priority.R Code
SELECT name, class FROM students ORDER BY CASE class WHEN "B" THEN 1 WHEN "A" THEN 2 ELSE 3 END;
Output
name | class Zayn | B Nadia | B Rafi | A Meera | A
Key Points
- ORDER BY sorts ascending (ASC, the default) or descending (DESC).
- List multiple columns to break ties: earlier columns take priority.
- Prefer naming columns explicitly rather than sorting by position number.
- A CASE expression inside ORDER BY enables custom, non-alphabetical sort priorities.