SQL multiple column ordering
How can I sort by multiple columns in SQL and in different directions. column1
would be sorted descending, and column2
ascending.
ORDER BY column1 DESC, column2
This sorts everything by column1
(descending) first, and then by column2
(ascending, which is the default) whenever the column1
fields for two or more rows are equal.
The other answers lack a concrete example, so here it goes:
Given the following People table:
FirstName | LastName | YearOfBirth
----------------------------------------
Thomas | Alva Edison | 1847
Benjamin | Franklin | 1706
Thomas | More | 1478
Thomas | Jefferson | 1826
If you execute the query below:
SELECT * FROM People ORDER BY FirstName DESC, YearOfBirth ASC
The result set will look like this:
FirstName | LastName | YearOfBirth
----------------------------------------
Thomas | More | 1478
Thomas | Jefferson | 1826
Thomas | Alva Edison | 1847
Benjamin | Franklin | 1706
SELECT *
FROM mytable
ORDER BY
column1 DESC, column2 ASC