ORDER By Clause in SQL

In SQL, ORDER BY clause in SQL is used to sort the retrieved data. It is used to sort the Result-Set.

The Order by clause by default sort data in ascending order. To sort data in descending order DESC keyword is used with order by clause in SQL.

 

SQL Syntax :

SELECT column_name, column_name
FROM table_name
ORDER BY column_name ASC|DESC;

ORDER BY clause in SQL

We have seen in syntax that we can use the ORDER BY keyword with the column name. The result – set will be sorted on the basis of this column name. Suppose we use the ORDER BY with salary then all records will be sort on the basis of salary. By Default ORDER BY sort the result in ascending order.

 

Example Query –  Sort the Employees table on the basis of salary.

SQL> Select * from Employees ORDER BY Salary;

 

The above query will sort the result set in ascending order of salary.

Another query to sort Employees table on the basis of First_Name.

SQL> Select * from Employees ORDER BY First_Name;

 

ORDER BY Descending Example

We use ‘DESC’ keyword with order by clause to sort the result set in descending order.

 

Example Query –  Sort the Employees table on the basis of salary in descending order.

SQL> Select * from Employees ORDER BY Salary DESC;

The above query will sort the result set in descending order of salary.

 

Another query to sort Employees table on the basis of First_Name.

SQL> Select * from Employees ORDER BY First_Name DESC;

 

ORDER BY Multiple Columns Example

We can also sort the result set on the basis of several columns. We can use multiple expression with ORDER BY clause.

 

Example Query –  Sort the Employees table on the basis of salary and First_Name.

SQL> Select * from Employees ORDER BY Salary , First_Name;

 

Example Query –  Sort the Employees table on the basis of salary in ascending order and First_Name in descending.

SQL> Select * from Employees ORDER BY Salary ASC, First_Name DESC;

 

You can see, We use ASC keyword to sort the result-set explicitly.

0 Comment

Leave a Reply