find and solve || findandsolve.com
Please wait.....

The SQL ORDER BY Keyword

The SQL, ORDER BY keyword is used to sort the result-set in descending or ascending order. The ORDER BY keyword sorts the records in ascending order by default in SQL Server. If you want to sort the records in descending order, use the DESC keyword.


SQL ORDER BY Keyword


The ORDER BY statement in SQL is used to sort the fetched data in either descending or ascending according to single or multiple columns. 

  • By default ORDER BY sorts the data in ascending order.
  • You can use the keyword ASC to sort in ascending order and the keyword DESC to sort the data in descending order.


ORDER BY Syntax


SELECT <TableColumn1>, <TableColumn2>..  FROM  <TableName> 
[WHERE condition] 
[ORDER BY
<TableColumn1>, <TableColumn2>, .. columnN]
[ASC | DESC];


We can use more than one column in the ORDER BY clause. Make sure whatever column we are using to sort that column should be in the column list.


Example

Consider the EmployeeInfo table having the following records

FirstNameLastNameAddressAge
SylviaNeupaneKathmandu10
RahulBhattaraiPokhara22
UbinaThapaMirmee23
SaurabRaiPokhara10
SylviaGurungButwal21


The following SQL statement selects all Employees from the "EmployeeInfo" table, sorted by the "FirstName" column:


SELECT * FROM EmployeeInfo ORDER BY FristName;


Output

FirstNameLastNameAddressAge
RahulBhattaraiPokhara22
SaurabRaiPokhara10
SylviaNeupaneKathmandu10
SylviaGurungButwal21
UbinaThapaMirmee23


ORDER BY DESC Example


The following SQL statement selects all Employees from the "EmployeeInfo" table, sorted DESCENDING by the "FirstName" column:


SELECT * FROM EmployeeInfo ORDER BY FirstName DESC;


Output

FirstNameLastNameAddressAge
UbinaThapaMirmee23
SylviaNeupaneKathmandu10
SylviaGurungButwal21
SaurabRaiPokhara10
RahulBhattaraiPokhara22


ORDER BY Several Columns Example


The following SQL statement selects all Employees from the "EmployeeInfo" table, sorted by the "FirstName" and the "LastName" column. This means that it orders by FirstName, but if some rows have the same FirstName, it orders them by LastName:


SELECT * FROM EmployeeInfo ORDER BY FirstName, LastName;


Output

FirstNameLastNameAddressAge
UbinaThapaMirmee23
SylviaGurung Butwal21
SylviaNeupaneKathmandu10
SaurabRaiPokhara10
RahulBhattaraiPokhara22


ORDER BY Several Columns Example 2


The following SQL statement selects all Employees from the "EmployeeInfo" table, sorted ascending by the "FirstName" and descending by the "LastName" column:


SELECT * FROM EmployeeInfo ORDER BY FirstName ASC, LastName DESC;


Related information