The SQL ORDER
BY clause is used to sort the
data in ascending or descending order, based on one or more columns.
The ORDER BY keyword sorts the records in
ascending order by default. To sort the records in a descending order, you can
use the DESC keyword.
Syntax:
The basic syntax of ORDER BY clause
is as follows:
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in
the ORDER BY clause. Make sure whatever column you are using to sort, that
column should be in column-list.
Example:
Here is the EMPLOYEE1 table:
ID
|
NAME
|
START_DATE
|
END_DATE
|
SALARY
|
CITY
|
1
|
A
|
01/01/2016 00:00:00
|
01/06/2016 00:00:00
|
10,000
|
BOMBAY
|
2
|
B
|
02/01/2016 00:00:00
|
07/03/2016 00:00:00
|
10,000
|
KOLKATA
|
3
|
C
|
03/01/2016 00:00:00
|
08/06/2016 00:00:00
|
10,000
|
CHENNAI
|
4
|
D
|
01/01/2016 00:00:00
|
07/06/2016 00:00:00
|
10,000
|
DELHI
|
5
|
E
|
01/01/2016 00:00:00
|
09/06/2016 00:00:00
|
12,000
|
NOIDA
|
6
|
F
|
01/01/2016 00:00:00
|
08/06/2016 00:00:00
|
15,000
|
BHUBANESWAR
|
7
|
G
|
01/01/2016 00:00:00
|
07/06/2016 00:00:00
|
11,000
|
PUNE
|
8
|
A
|
01/01/2016 00:00:00
|
06/06/2016 00:00:00
|
10,000
|
GOA
|
8
|
B
|
01/01/2016 00:00:00
|
06/06/2016 00:00:00
|
10,000
|
DELHI
|
1) Sort the employee1 table by salary of the employee in
ascending order:
SELECT name, salary FROM EMPLOYEE1 ORDER BY salary;
The output would
be like:
NAME
|
SALARY
|
A
|
10,000
|
B
|
10,000
|
C
|
10,000
|
D
|
10,000
|
B
|
10,000
|
A
|
10,000
|
G
|
11,000
|
E
|
12,000
|
F
|
15,000
|
2)Sort the
employee1 table by salary of the employee in descending order:
SELECT name, salary FROM EMPLOYEE1 ORDER BY salary DESC;
The output would
be like:
NAME
|
SALARY
|
F
|
15,000
|
E
|
12,000
|
G
|
11,000
|
C
|
10,000
|
D
|
10,000
|
B
|
10,000
|
A
|
10,000
|
A
|
10,000
|
B
|
10,000
|
3)Sort the
employee1 table by name and salary of the employee:
SELECT name, salary FROM EMPLOYEE1 ORDER BY NAME, SALARY;
The output would
be like:
NAME
|
SALARY
|
A
|
10,000
|
A
|
10,000
|
B
|
10,000
|
B
|
10,000
|
C
|
10,000
|
D
|
10,000
|
E
|
12,000
|
F
|
15,000
|
G
|
11,000
|
No comments:
Post a Comment