Vous êtes sur la page 1sur 2

SQL ORDER BY clause

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
ORDER BY { column-Name | ColumnPosition | Expression }
[ ASC | DESC ]
[ NULLS FIRST | NULLS LAST ]
[ , column-Name | ColumnPosition | Expression
[ ASC | DESC ]
[ NULLS FIRST | NULLS LAST ]
]*
Explanation
columnName
ColumnPositio
n

Expression

ASC
DESC
NULLS FIRST
NULLS LAST

By this you can short the rows according to value of the rows mentioned in
order by clause. The column-Name that you specify in the ORDER BY clause
does not need to be the SELECT list.
An integer that identifies the number of the column in the SelectItems in the
underlying query of the SELECT statement. ColumnPosition must be greater
than 0 and not greater than the number of columns in the result table.
In other words, if you want to order by a column, that column must be specified
in the SELECT list.
A sort key expression, such as numeric, string, and datetime
expressions. Expression can also be a row value expression such as a scalar
subquery or case expression.
Specifies that the results should be returned in ascending order. If the order is
not specified, ASC is the default.
Specifies that the results should be returned in descending order.
Specifies that NULL values should be returned before non-NULL values.
Specifies that NULL values should be returned after non-NULL values.

Database table "employee";

ID

10
0
10
1
10
2
10
3
10
4

NAME

DEPT

AG
E

SALAR
Y

LOCATION

Ramesh Electrical

24

25000

Bangalore

Hrithik

Electronics

28

35000

Bangalore

Harsha

Aeronautic
s
Electronics

28

35000

22

20000

InfoTech

25

30000

Soumy
a
Priya

Mangalore

Example using ODER BY column-Name


If you want to sort the employee table by salary of the employee, the sql query would be.

SELECTNAME,SALARY
FROMemployee
ORDERBYSALARY;

Example using ODER BY Column-Position


If you want to sort the employee table by position of NAME column of employee table, the
sql query would be.
SELECTNAME,DEPT,AGE
FROMemployee
ORDERBY2;

Example ODER BY null ordering


You can specify the position of NULL values using the null ordering specification:
SELECT*
FROMemployee
ORDERBYLOCATIONDESCNULLSFIRST
ID

NAME

DEPT

10
2
10
3
10
0
10
1
10
4

Harsha

Aeronautic
s
Electronics

AG
E

SALARY

LOCATION

28

35000

Soumy
a
Ramesh Electrical

22

20000

24

25000

Bangalore

Hrithik

Electronics

28

35000

Bangalore

Priya

InfoTech

25

30000

Mangalore

In this output , rows havng NuLL value in LOCATION column will be placed first ,then remaing rows
will shorted alphabeticaly.
http://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqlj40506.html
http://docs.oracle.com/javadb/10.8.3.0/ref/rrefclauses.html
http://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqlj13658.html
http://beginner-sql-tutorial.com/sql-order-by-clause.htm

Vous aimerez peut-être aussi