SQL ORDER By Keyword

The ORDER BY keyword is used to sort the result-set by one or more columns.

The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a descending order, you can use the DESC keyword.

SQL ORDER BY syntax:

	SELECT expressions   

FROM tables   

WHERE conditions   

ORDER BY expression [ASC | DESC];  

	

Let us take a CUSTOMERS table having the following records:

ID NAME AGE ADDRESS SALARY
1 Himani Gupta 21 Modinagar 22000
2 Shiva Tiwari 22 Bhopal 21000
3 Ajeet Bhargav 45 Meerut 65000
4 Ritesh Yadav 36 Azamgarh 36000
5 Balwant Singh 45 Varanasi 36000
6 Mahesh Sharma 26 Mathura 22000

This is an example that would sort the result in ascending order by NAME and SALARY.

SELECT * FROM CUSTOMERS ORDER BY NAME, SALARY;

This would produce the following result.

ID NAME AGE ADDRESS SALARY
3 Ajeet Bhargav 45 Meerut 65000
5 Balwant Singh 45 Varanasi 36000
1 Himani Gupta 21 Modinagar 22000
6 Mahesh Sharma 26 Mathura 22000
4 Ritesh Yadav 36 Azamgarh 26000
2 Shiva Tiwari 22 Bhopal 21000

This is an example to sort the result in descending order by NAME.

SELECT * FROM CUSTOMERS ORDER BY NAME DESC;