w3resource logo


Sql Tutorial

SQL ORDER BY clause

Secondary Nav

Description

The ORDER BY clause orders or sorts the result of a query according to the values in one or more specific columns. More than one columns can be ordered one within another. It depends on the user that, whether to order them in ascending or descending order. The default order is ascending.

The SQL ORDER BY clause is used with the SQL SELECT statement.

Note : SQL ORDER BY clause always come at the end of a SELECT statement.

Syntax

SELECT <column_list> FROM < table name >.
WHERE <condition>
ORDER BY <columns> [ASC | DESC];

Parameters

Name Description
table_name Name of the table.
column_list Name of the columns of the table.
columns Name of the columns which will participate in ordering.

Example

Sample table : agents

To get 'agent_name', 'agent_name','working_area' and 'commission' from the 'agents' table with following condition -

1. 'agent_code' should come in ascending order,

then, the following SQL statement can be used :

SELECT agent_code,agent_name,working_area,commission
FROM agents ORDER BY agent_code;

Output

order-by

SQL ORDER BY clause in descending order

To get 'agent_name', 'agent_name','working_area' and 'commission' from the 'agents' table with following condition -

1. 'agent_code' should come in descending order,

then, the following SQL statement can be used :

SELECT agent_code,agent_name,working_area,commission
FROM agents ORDER BY agent_code DESC; 

Output

order by descending

SQL ORDER BY in more columns

You can use the ORDER BY clause to sort the result of a query according to the values in more than one columns.

To get 'agent_name', 'agent_name','working_area' and 'commission' from the 'agents' table with following conditions -

1. 'working_area' should come in ascending order first,

2. within the same 'working_area', 'agent_code' should come in ascending order,

then, the following SQL statement can be used :

SELECT agent_code,agent_name,working_area,commission
FROM agents ORDER BY working_area,agent_code;

Output

order bY in more columns

SQL ORDER BY in more columns in ascending or descending order

You can use the ORDER BY clause to sort the result of a query on multiple columns in various order (ascending or descending). Here is an example :

To get 'agent_name', 'agent_name','working_area' and 'commission' from the 'agents' table with following conditions -

1. 'working_area' comes in ascending order first,

2. 'commission' comes in descending order,

then, the following SQL statement can be used :

SELECT agent_code,agent_name,working_area,commission
FROM agents ORDER BY working_area ASC, commission DESC;

Output

SQL ORDER BY ACCENDING OR-DECENDING

See our Model Database



Join our Question Answer community to learn and share your programming knowledge.