VillageSQL is a drop-in replacement for MySQL with extensions.
All examples on this page work on VillageSQL. Install Now →
ORDER BY is the
only thing that decides the order of a result.
Open the client with mysql -u root -p sakila before you start.
How ORDER BY works
SORT_COLUMN with the column to sort on. DIRECTION is either ASC
for smallest first or DESC for largest first. It is optional, and leaving it
out means ASC.
Examples
1) Sort by one column
2) Sort the other way
3) Break the tie with a second column
List sort columns in order of priority, separated by commas. Each one takes its own direction.rental_rate still leads, descending. Within each rate the shortest film comes
first. Films of equal length are still tied, so a fully decided order needs
enough columns to make every row unique.
4) Sort by an alias
ORDER BY can name a column alias from the same query.
Quote an alias with backticks, not single quotes
An alias holding a space has to be quoted, and here the 2 quoting styles stop agreeing. Single quotes make a string rather than a name, and sorting by a fixed string sorts nothing.'Rate'
as the 4 letter word and sorted every row by the same value. No error, no
warning, no sorting.
Backticks name the alias, and the sort happens:
Where NULL lands
A column can holdNULL, which records that no value is there at all. It is
not a zero and not an empty string. MySQL sorts NULL below every real value,
so ascending order puts the NULLs first. Of the 603 rows in address, 4 have
no address2.
NULL and below any text. Those 4 NULL rows
are tied with each other, so the order among them is not decided by this query.
DESC reverses it and the NULLs go to the bottom. This is the end of the same
result sorted the other way:
Summary
- Use
ORDER BYto decide the order of a result, because nothing else does. - Write
DESCfor largest first;ASCis the default. - List several sort columns, in priority order, to break ties.
- Quote an alias with backticks when sorting by it, because single quotes make a string.
- Expect
NULLfirst when sorting ascending, and last when sorting descending.
See also
- SELECT — the statement being sorted
- Column aliases — naming the column you sort by
- LIMIT — take the first few rows of a sorted result
- Pagination in MySQL — what sorting costs on a large table

