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
FirstName | LastName | Address | Age |
Sylvia | Neupane | Kathmandu | 10 |
Rahul | Bhattarai | Pokhara | 22 |
Ubina | Thapa | Mirmee | 23 |
Saurab | Rai | Pokhara | 10 |
Sylvia | Gurung | Butwal | 21 |
The following SQL statement selects all Employees from the "EmployeeInfo" table, sorted by the "FirstName" column:
SELECT * FROM EmployeeInfo ORDER BY FristName;
Output
FirstName | LastName | Address | Age |
Rahul | Bhattarai | Pokhara | 22 |
Saurab | Rai | Pokhara | 10 |
Sylvia | Neupane | Kathmandu | 10 |
Sylvia | Gurung | Butwal | 21 |
Ubina | Thapa | Mirmee | 23 |
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
FirstName | LastName | Address | Age |
Ubina | Thapa | Mirmee | 23 |
Sylvia | Neupane | Kathmandu | 10 |
Sylvia | Gurung | Butwal | 21 |
Saurab | Rai | Pokhara | 10 |
Rahul | Bhattarai | Pokhara | 22 |
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
FirstName | LastName | Address | Age |
Ubina | Thapa | Mirmee | 23 |
Sylvia | Gurung | Butwal | 21 |
Sylvia | Neupane | Kathmandu | 10 |
Saurab | Rai | Pokhara | 10 |
Rahul | Bhattarai | Pokhara | 22 |
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;