Sunday, 10 February 2013

SQL ORDER BY Clause Syntax and Examples

SQL Server ORDER BY Clause
The ORDER BY Clause is used to sort the result-set by a specified column.
The ORDER BY keyword sorts the records in ascending order by default.If you want to sort the records in a descending order, you can use the DESC keyword.

Syntax

SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC

Example :

Let us suppose we have a EMP Table as follows :
Emp_ID
E_Name
Job
Dept_ID
Salary
1001
Ravi Teja Reddy
Analyst
1
20000
1002
Karun
Team Lead
2
35000
1003
Ravi Kumar Rao
Analyst
1
10000
1004
Tamatam
Team Lead
3
25000
1005
Sai Kumar Teja
Analyst
2
15000
1006
William
Manager
3
50000
1007
Vikram Teja Reddy
Analyst
2
18000
1008
Varun
Team Lead
1
33000
1009
Smith
Team Lead
3
50000

--------------------------------------------------------------------------------------
Criteria - I :
ORDER BY ASC:
Now we want to select all the records from the above table EMP , however, we want to sort the data by Salary Ascending order[By default sort in ASC Order].We use the following SELECT statement:

SELECT * FROM EMP ORDER BY Salary


Result :
Emp_ID
E_Name
Job
Dept_ID
Salary
1003
Ravi Kumar Rao
Analyst
1
10000
1005
Sai Kumar Teja
Analyst
2
15000
1007
Vikram Teja Reddy
Analyst
2
18000
1001
Ravi Teja Reddy
Analyst
1
20000
1004
Tamatam
Team Lead
3
25000
1008
Varun
Team Lead
1
33000
1002
Karun
Team Lead
2
35000
1006
William
Manager
3
50000
1009
Smith
Team Lead
3
50000

--------------------------------------------------------------------------------------
Criteria - II :
ORDER BY DESC:
Now we want to select all the records from the above table EMP , however, we want to sort the data by Salary Descending orderWe use the following SELECT statement:

SELECT * FROM EMP ORDER BY Salary DESC

Result :
Emp_ID
E_Name
Job
Dept_ID
Salary
1006
William
Manager
3
50000
1009
Smith
Team Lead
3
50000
1002
Karun
Team Lead
2
35000
1008
Varun
Team Lead
1
33000
1004
Tamatam
Team Lead
3
25000
1001
Ravi Teja Reddy
Analyst
1
20000
1007
Vikram Teja Reddy
Analyst
2
18000
1005
Sai Kumar Teja
Analyst
2
15000
1003
Ravi Kumar Rao
Analyst
1
10000



Thanks,
TAMATAM

No comments:

Post a Comment

Follow Me by Email

ExcelKingdom-Popular Posts

ExcelKingdom-Random Posts