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

SELECT column1, column2
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

SELECT * FROM Employees;

The above query returned the following result:

Table: Employees

EmployeeIDNameAgeSalaryDepartmentGender
1Ashish2425000ElectricalM
2Kirshan3230000ElectricalM
3Anjali2025000ElectronicsF
4Manjulika3015000ElectricalF
5Katrina3718000ComputerF
6Esha3720000ComputerF
7Ankita209000ElectronicsM
8Meenakshi3015000ComputerF
9Alia3716000ElectronicsF

Sorting by a Single Column (Ascending Order) By default, the ORDER BY clause sorts the results in ascending order.

SQL

SELECT EmployeeID, name, salary
FROM employees
ORDER BY salary;

This query will sort the employees by their salary in ascending order.

EmployeeIDNameSalary
4Manjulika15000
8Meenakshi15000
9Alia16000
5Katrina18000
6Esha20000
1Ashish25000
3Anjali25000
2Kirshan30000
7Ankita9000

SQL

SELECT EmployeeID, name
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

SELECT EmployeeID, name, salary
FROM employees
ORDER BY salary DESC;

This query will sort the employees by their salary in descending order.

EmployeeIDNameSalary
7Ankita9000
2Kirshan30000
3Anjali25000
1Ashish25000
6Esha20000
5Katrina18000
9Alia16000
8Meenakshi15000
4Manjulika15000