Back to subject
MySQL/ORDER BY

Put Results in a Meaningful Order

Practical lesson

Let's read a sorted query and see exactly how the order was decided.

SELECT * FROM students ORDER BY age DESC; returns every student, sorted from oldest to youngest. Sara (17) comes before Ali (16), because DESC means largest values first.

If we'd written ORDER BY age without DESC, the same two rows would come back in the opposite order Ali (16) first, then Sara (17) since ascending is the default when no direction is given.

Notice ORDER BY didn't filter anything out; both students are still in the result, unlike WHERE from the last topic. Sorting and filtering are two separate, combinable jobs: WHERE decides which rows appear, ORDER BY decides what order they appear in.

In fact, you can use both together in one query: SELECT * FROM students WHERE age > 15 ORDER BY age DESC; filter first, then sort what's left. You'll get very comfortable combining clauses like this as the course continues.

Try it yourself
Code

Starter example

Code
SELECT * FROM students ORDER BY age DESC;
Live preview
+----+------+-----+
| id | name | age |
+----+------+-----+
| 2  | Sara | 17  |
| 1  | Ali  | 16  |
+----+------+-----+
2 rows in set