How can I sort by multiple columns in SQL and in different directions. column1
would be sorted descending, and column2
ascending.
ORDER BY clause is used to sort the returned records in an order. By using ORDER BY clause, we can sort the result in ascending or descending order. This clause can be used with multiple columns as well.
Using SQL Server Management StudioIn Object Explorer, right-click the table with columns you want to reorder and select Design. Select the box to the left of the column name that you want to reorder. Drag the column to another location within the table.
The SQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With