ORDER BY clause in SQL
The ORDER BY clause in SQL is used to sort the result set of a query by one or more columns. We can sort the results in ascending order (default) or descending order.
SQL Syntax
FROM table_name [WHERE condition]
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], …;
Default Order: Ascending (ASC).
Descending Order: Use DESC keyword.
Example: Let’s create an employees table.
SQL
CREATE TABLE Employees ( EmployeeID INT, Name VARCHAR(20), Age int, Salary VARCHAR(10), Department VARCHAR(25), Gender VARCHAR(1) );
Load the data into the Employees table.
SQL
insert into Employees values (1, ‘Ashish’, 24, ‘25000’, ‘Electrical’, ‘M’), (2, ‘Kirshan’, 32, ‘30000’, ‘Electrical’, ‘M’), (3, ‘Anjali’, 20, ‘25000’, ‘Electronics’, ‘F’), (4, ‘Manjulika’, 30, ‘15000’, ‘Electrical’, ‘F’), (5, ‘Katrina’, 37, ‘18000’, ‘Computer’, ‘F’), (6, ‘Esha’, 37, ‘20000’, ‘Computer’, ‘F’), (7, ‘Ankita’, 20, ‘9000’, ‘Electronics’, ‘M’), (8, ‘Meenakshi’, 30, ‘15000’, ‘Computer’, ‘F’), (9, ‘Alia’, 37, ‘16000’, ‘Electronics’, ‘F’);
By executing the following query we can see the data in the table:
SQL
The above query returned the following result:
Table: Employees
EmployeeID | Name | Age | Salary | Department | Gender |
---|---|---|---|---|---|
1 | Ashish | 24 | 25000 | Electrical | M |
2 | Kirshan | 32 | 30000 | Electrical | M |
3 | Anjali | 20 | 25000 | Electronics | F |
4 | Manjulika | 30 | 15000 | Electrical | F |
5 | Katrina | 37 | 18000 | Computer | F |
6 | Esha | 37 | 20000 | Computer | F |
7 | Ankita | 20 | 9000 | Electronics | M |
8 | Meenakshi | 30 | 15000 | Computer | F |
9 | Alia | 37 | 16000 | Electronics | F |
Sorting by a Single Column (Ascending Order) By default, the ORDER BY clause sorts the results in ascending order.
SQL
FROM employees
ORDER BY salary;
This query will sort the employees by their salary in ascending order.
EmployeeID | Name | Salary |
---|---|---|
4 | Manjulika | 15000 |
8 | Meenakshi | 15000 |
9 | Alia | 16000 |
5 | Katrina | 18000 |
6 | Esha | 20000 |
1 | Ashish | 25000 |
3 | Anjali | 25000 |
2 | Kirshan | 30000 |
7 | Ankita | 9000 |
SQL
FROM employees
ORDER BY salary;
The above query will also work even if we are not selecting the salary column from the table.
Sorting by a Single Column (Descending Order) To sort the results in descending order, you use the DESC keyword.
SQL
FROM employees
ORDER BY salary DESC;
This query will sort the employees by their salary in descending order.
EmployeeID | Name | Salary |
---|---|---|
7 | Ankita | 9000 |
2 | Kirshan | 30000 |
3 | Anjali | 25000 |
1 | Ashish | 25000 |
6 | Esha | 20000 |
5 | Katrina | 18000 |
9 | Alia | 16000 |
8 | Meenakshi | 15000 |
4 | Manjulika | 15000 |