Sorting with ORDER BY
Rows come back in whatever order suits the server. That is fine for a dozen students and useless for a merit list. order by arranges the resultset — and, like an alias, it changes only what you are shown, never the table.
1Ascending order
Alphabetical. asc is the default — leave it out entirely and you get the same result. It is worth writing anyway, because it says out loud which way you meant.
2Descending order
The merit list — highest first:
order by percent desc, desc means descending. In desc students; it is short for describe and shows the table's structure. Same three letters, completely unrelated jobs. The one place they can be confused is an exam question that mentions both.3Where the NULLs go
Notice Bhim and Pema at the bottom of that list. Sort the same column ascending and they move to the top:
MySQL sorts NULL as lower than every real value: first when ascending, last when descending. This is the one context where NULLs are not simply dropped — they are still here, all twelve rows, just parked at one end.
order by percent desc puts the students with no result at the bottom, which is usually what you want. Sorting ascending would open the list with two blank rows.4Sorting by two columns
Give several columns, separated by commas. The second is used only to break ties in the first — here, group by class, and within each class put the highest scorer first:
Each column gets its own direction — grade asc and percent desc in the same query. Read it as: sort by grade; wherever two students share a grade, put the higher mark first.
5Where the clause goes
select <columns> from <table> where <condition> order by <column> asc|desc;
order by is always last. Sorting happens after the rows have been chosen, which is the order the query is written in too. Putting it before the where is a syntax error.
6Recap
Smallest first. asc is the default and can be left out.
Largest first. Not the same desc as describe.
b breaks ties in a. Each gets its own direction.
Sort as lowest: first ascending, last descending.
Which sorting direction is used if you write neither asc nor desc?
In order by percent desc, what does desc mean?
What does order by grade asc, percent desc do?