ORDER BY Clause

The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some databases sort the query results in an ascending order by default.

Syntax

The basic syntax of the ORDER BY clause is as follows −

SELECT column-list 
FROM table_name 
[WHERE condition] 
[ORDER BY column1, column2, .. columnN] [ASC | DESC];

You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort that column should be in the column-list.

Example

Consider the CUSTOMERS table having the following records −

IDNAMEAGEADDRESSSALARY
1Ramesh32Ahmedabad2000.00
2Khilan25Delhi1500.00
3kaushik23Kota2000.00
4Chaitali25Mumbai6500.00
5Hardik27Bhopal8500.00
6Komal22MP4500.00
7Muffy24Indore10000.00

The following code block has an example, which would sort the result in an ascending order by the NAME and the SALARY −

SQL> SELECT * FROM CUSTOMERS
ORDER BY NAME, SALARY;

This would produce the following result −

IDNAMEAGEADDRESSSALARY
4Chaitali25Mumbai6500.00
5Hardik27Bhopal8500.00
3kaushik23Kota2000.00
2Khilan25Delhi1500.00
6Komal22MP4500.00
7Muffy24Indore10000.00
1Ramesh32Ahmedabad2000.00

The following code block has an example, which would sort the result in the descending order by NAME.

SQL> SELECT * FROM CUSTOMERS
ORDER BY NAME DESC;

This would produce the following result −

IDNAMEAGEADDRESSSALARY
1Ramesh32Ahmedabad2000.00
7Muffy24Indore10000.00
6Komal22MP4500.00
2Khilan25Delhi1500.00
3kaushik23Kota2000.00
5Hardik27Bhopal8500.00
4Chaitali25Mumbai6500.00
sql rdbms order-by

Subscribe For More Content