Explain ORDER BY in Sql
In SQL, the ORDER BY
clause is used to sort the result set of a query by one or more columns. You can specify whether to sort in ascending (ASC
) or descending (DESC
) order. By default, the ORDER BY
clause sorts in ascending order.
Basic Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
Example
Assume we have a table named Employees
with the following data:
EmployeeID |
FirstName |
LastName |
Age |
Salary |
1 |
John |
Doe |
30 |
50000 |
2 |
Jane |
Smith |
25 |
60000 |
3 |
Alice |
Johnson |
30 |
55000 |
4 |
Bob |
Brown |
28 |
45000 |
Query to Sort by Age (Ascending)
SELECT * FROM Employees
ORDER BY Age;
Output:
EmployeeID |
FirstName |
LastName |
Age |
Salary |
4 |
Bob |
Brown |
28 |
45000 |
2 |
Jane |
Smith |
25 |
60000 |
3 |
Alice |
Johnson |
30 |
55000 |
1 |
John |
Doe |
30 |
50000 |
Query to Sort by Age (Descending)
SELECT * FROM Employees
ORDER BY Age DESC;
Output:
EmployeeID |
FirstName |
LastName |
Age |
Salary |
3 |
Alice |
Johnson |
30 |
55000 |
1 |
John |
Doe |
30 |
50000 |
4 |
Bob |
Brown |
28 |
45000 |
2 |
Jane |
Smith |
25 |
60000 |
Query to Sort by Multiple Columns
SELECT * FROM Employees
ORDER BY Age ASC, Salary DESC;
Output:
EmployeeID |
FirstName |
LastName |
Age |
Salary |
4 |
Bob |
Brown |
28 |
45000 |
2 |
Jane |
Smith |
25 |
60000 |
3 |
Alice |
Johnson |
30 |
55000 |
1 |
John |
Doe |
30 |
50000 |
Here, the result set is first sorted by Age
in ascending order. If there are ties in the Age
, it further sorts by Salary
in descending order.