TechnoLearnAcademy

TECHNOLEARN

SQL ORDER BY Clause

THE SQL ORDER BY clause is used to sort the result set of a query based on one or more columns.
The Order by clause can sort the result set either in ascending or descending order.
To sort in ascending order, use ASC, while for descending order, use DESC.
The default sorting order is ascending.

Syntax:      

                SELECT column1 , column2 , column3  FROM tablename                                                                                                                                                                              Order by columnname ; 
Let’s understand the order by clause with an example. For demonstration purposes, we will be using the table emp.
         Table Emp

Example:

   Objective: In this example, we will retrieve all the records from the table emp sorted by salary in ascending order. 
                      SELECT * FROM Tbl_Emp                                                                                                                                                                                   ORDER BY Salary ASC;
    Output:
Note: We can execute the aforementioned command using without ASC as well. If we do not specify ASC or DESC, the                   default sorting will be in ascending order.
                    SELECT * FROM Tbl_Emp                                                                                                                                                                                   ORDER BY Salary;

Example:

   Objective: In this example, we will retrieve all the records from the table emp sorted by salary in descending order. 
                      SELECT * FROM Tbl_Emp                                                                                                                                                                                   ORDER BY Salary DESC;
    Output:

Example:

   Objective: In this example, the table emp will be sorted primarily by Department in ascending order, and for rows with                          the same department, it will sort those rows by salary in descending order.
                      SELECT * FROM Tbl_Emp                                                                                                                                                                                   ORDER BY Department ASC, Salary DESC;
    Output:
Scroll to Top