Friday, December 21, 2012

SQL ORDER BY


SQL ORDER BY

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 for using SQL ORDER BY clause to sort data is:

SELECT column-list 

FROM table_name [WHERE condition] 

[ORDER BY column1 [, column2, .. columnN] [DESC]];

database table "employee";
idnamedeptagesalarylocation
100RameshElectrical2425000Bangalore
101HrithikElectronics2835000Bangalore
102HarshaAeronautics2835000Mysore
103SoumyaElectronics2220000Bangalore
104PriyaInfoTech2530000Mangalore
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;
The output would be like
namesalary
--------------------
Soumya20000
Ramesh25000
Priya30000
Hrithik35000
Harsha35000
The query first sorts the result according to name and then displays it.
You can also use more than one column in the ORDER BY clause.
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;
The output would be like:
namesalary
--------------------------
Soumya20000
Ramesh25000
Priya30000
Harsha35000
Hrithik35000
NOTE:The columns specified in ORDER BY clause should be one of the columns selected in the SELECT column list.
You can represent the columns in the ORDER BY clause by specifying the position of a column in the SELECT list, instead of writing the column name.
The above query can also be written as given below,
SELECT name, salary FROM employee ORDER BY 1, 2;
By default, the ORDER BY Clause sorts data in ascending order. If you want to sort the data in descending order, you must explicitly specify it as shown below.
SELECT name, salary 
FROM employee 
ORDER BY name, salary DESC; 
The above query sorts only the column 'salary' in descending order and the column 'name' by ascending order.
If you want to select both name and salary in descending order, the query would be as given below.
SELECT name, salary 
FROM employee 
ORDER BY name DESC, salary DESC; 

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; 
The output for the above query is as follows.
namesalarynew_salary
---------------------------------
Hrithik3500037000
Harsha3500037000
Priya3000036000
NOTE:Aliases defined in the SELECT Statement can be used in ORDER BY Clause.

No comments:

Post a Comment

Thank you :
- kareem