Databases do not guarantee the order of your results unless you tell them exactly
what order you want. That is what ORDER BY is for.
Sorting Ascending
To sort your results from smallest to largest (or A to Z), use ORDER BY
with ASC:
SELECT name, age, score FROM students ORDER BY score ASC;
ASC is actually optional because ascending is the default. So this
does the same thing:
SELECT name, age, score FROM students ORDER BY score;
Sorting Descending
Highest to lowest? Use DESC:
SELECT name, age, score FROM students ORDER BY score DESC;
Sorting by Multiple Columns
Here is where it gets interesting. You can sort by one column, and if there are ties, sort by another:
SELECT name, city, score FROM students ORDER BY city ASC, score DESC;
This sorts by city alphabetically first. Then within each city, it sorts by score from highest to lowest. This kind of multi-level sorting is extremely useful in real-world reporting.
Sorting by Column Position
You can also use numbers to refer to column positions. Handy for quick queries:
SELECT name, score FROM students ORDER BY 2 DESC;
The 2 means "the second column in my SELECT," which is score.
I do not use this often in production code because it is harder to read, but it is
useful when you are quickly testing things.