The ORDER BY clause is used in a SELECT statement to sort results either in ascending or descending order. Oracle sorts query results in ascending order by default.
Syntax
SELECT column-list
FROM table_name [WHERE condition]
[ORDER BY column1 [, column2, .. columnN] [DESC]];
database table "employee";
id |
name |
dept |
age |
salary |
location |
100 |
Ramesh |
Electrical |
24 |
25000 |
Bangalore |
101 |
Hrithik |
Electronics |
28 |
35000 |
Bangalore |
102 |
Harsha |
Aeronautics |
28 |
35000 |
Mysore |
103 |
Soumya |
Electronics |
22 |
20000 |
Bangalore |
104 |
Priya |
InfoTech |
25 |
30000 |
Mangalore |
For Example: If you want to sort the employee table by salary of the employee, the sql query would be.
SELECT name, salary FROM employee ORDER BY salary;
If you want to sort the employee table by the name and salary, the query would be like,
SELECT name, salary FROM employee ORDER BY name, salary;
How to use expressions in the ORDER BY Clause?
Expressions in the ORDER BY clause of a SELECT statement.
For example: If you want to display employee name, current salary, and a 20% increase in the salary for only those employees for whom the percentage increase in salary is greater than 30000 and in descending order of the increased price, the SELECT statement can be written as shown below
SELECT name, salary, salary*1.2 AS new_salary
FROM employee
WHERE salary*1.2 > 30000
ORDER BY new_salary DESC;