The SQL ORDER BY clause is used to sort the result-set, it can only be used in SELECT statements.
SQL ORDER BY Syntax
SELECT Columns FROM tables ORDER BY Column1 ASC|DESC {, Column2 ASC|DESC}+
The {}+ means that we can repeat it one or more times.
ACS means that the result-set will be sorted in ascending order.
DESC means that the result-set will be sorted in descending order.
The default is ASC.
SQL ORDER BY Example
Table: Employees
EmployeeId | FirstName | LastName | Department | Salary |
---|---|---|---|---|
203 | Mazojys | Fxoj | Finance | 78000 |
204 | Jozzh | Lnanyo | Finance | 45800 |
205 | Syllauu | Dfaafk | Finance | 55000 |
206 | Gecrrcc | Srlkrt | Finance | 75000 |
302 | Jssme | Bdnaa | Development | 75000 |
303 | Dnnaao | Errllov | Development | 55000 |
304 | Tyoysww | Osk | Development | 49000 |
Select all the records from the table Employees and sort the result-set by salary:
SELECT * FROM Employees ORDER BY Salary
The result-set will look like:
EmployeeId | FirstName | LastName | Department | Salary |
---|---|---|---|---|
204 | Jozzh | Lnanyo | Finance | 45800 |
304 | Tyoysww | Osk | Development | 49000 |
205 | Syllauu | Dfaafk | Finance | 55000 |
303 | Dnnaao | Errllov | Development | 55000 |
206 | Gecrrcc | Srlkrt | Finance | 75000 |
302 | Jssme | Bdnaa | Development | 75000 |
203 | Mazojys | Fxoj | Finance | 78000 |
Example 2
Select all the records from the table Employees, but sort the result-set descending by salary:
SELECT * FROM Employees ORDER BY Salary DESC
The result-set will look like:
EmployeeId | FirstName | LastName | Department | Salary |
---|---|---|---|---|
203 | Mazojys | Fxoj | Finance | 78000 |
206 | Gecrrcc | Srlkrt | Finance | 75000 |
302 | Jssme | Bdnaa | Development | 75000 |
205 | Syllauu | Dfaafk | Finance | 55000 |
303 | Dnnaao | Errllov | Development | 55000 |
304 | Tyoysww | Osk | Development | 49000 |
204 | Jozzh | Lnanyo | Finance | 45800 |
Example 3
Select all the records from the table Employees and sort the result-set by salary, if salary is same, sort by last name:
SELECT * FROM Employees ORDER BY Salary, LastName
The result-set will look like:
EmployeeId | FirstName | LastName | Department | Salary |
---|---|---|---|---|
204 | Jozzh | Lnanyo | Finance | 45800 |
304 | Tyoysww | Osk | Development | 49000 |
205 | Syllauu | Dfaafk | Finance | 55000 |
303 | Dnnaao | Errllov | Development | 55000 |
302 | Jssme | Bdnaa | Development | 75000 |
206 | Gecrrcc | Srlkrt | Finance | 75000 |
203 | Mazojys | Fxoj | Finance | 78000 |