Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 404
Señor Reginold Francis Avatar asked Jan 12 '10 18:01

Señor Reginold Francis


People also ask

Can we use ORDER BY with multiple columns?

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.

How do I order columns in SQL?

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.

How do you order from highest to lowest in SQL?

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.


2 Answers

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 
like image 29
Thomas C. G. de Vilhena Avatar answered Sep 17 '22 16:09

Thomas C. G. de Vilhena


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.

like image 100
Ignacio Vazquez-Abrams Avatar answered Sep 16 '22 16:09

Ignacio Vazquez-Abrams