Home » T-SQL ORDER BY

T-SQL ORDER BY

by Online Tutorials Library

T-SQL ORDER BY

ORDER BY Clause sorts the database in increasing or decreasing order. To sort multiple columns at once, separate the column names by the operator (,) operator.

  • ORDER BY sorts the data in ascending order by default.
  • The DESC keyword is used to sort the data in descending order and ASC keyword is used to sort the database in ascending order.

Syntax of ORDER BY Clause:

Here: table_name: Name of the table.
column_name: Column of the database.
|: Use ASC or DESC to sort in ascending or descending order

Example:

Consider the CUSTOMERS table which has the below records –

ID NAME AGE ADDRESS SALARY
01 William 32 Karachi 72000
02 Avery 24 London 34000
03 Jackson 34 Paris 12000
04 Harper 20 United state 15000
05 Ella 22 Islamabad 33000
06 Monty 23 Turkey 42000
07 Mason 26 Saudi 50500

Example 1:

Below command is the example, which sorts the result in ascending order by NAME and the SALARY.

The command gives the below output.

ID NAME AGE ADDRESS SALARY
02 Avery 24 London 72000
05 Ella 22 Islamabad 34000
04 Harper 20 New York 12000
03 Jackson 34 Paris 15000
07 Mason 26 Saudi Arabia 33000
06 Monty 23 Turkey 42000
01 William 32 Karachi 50500

Example 2:

The command is the example, which sort the result in descending order by AGE.

The above command will produce the following effect ?

ID NAME AGE ADDRESS SALARY
03 Jackson 34 Paris 50500
07 William 32 Karachi 42000
01 Mason 26 Saudi Arabia 33000
02 Avery 24 London 15000
06 Monty 23 Turkey 12000
05 Ella 22 Islamabad 34000
04 Harper 20 New York 72000

Example 3:

This command sorts the result in ascending order by ADDRESS.

The command gives the below output.

ID NAME AGE ADDRESS SALARY
05 Ella 22 Islamabad 33000
01 William 32 Karachi 72000
02 Avery 24 London 34000
03 Jackson 34 Paris 12000
07 Mason 26 Saudi 50500
06 Monty 23 Turkey 42000
04 Harper 20 United state 15000

Next TopicT-SQL GROUP BY

You may also like