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 -

IDNAMEAGEADDRESSSALARY
01William32Karachi72000
02Avery24London34000
03Jackson34Paris12000
04Harper20United state15000
05Ella22Islamabad33000
06Monty23Turkey42000
07Mason26Saudi50500

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.

IDNAMEAGEADDRESSSALARY
02Avery24London72000
05Ella22Islamabad34000
04Harper20New York12000
03Jackson34Paris15000
07Mason26Saudi Arabia33000
06Monty23Turkey42000
01William32Karachi50500

Example 2:

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

The above command will produce the following effect ?

IDNAMEAGEADDRESSSALARY
03Jackson34Paris50500
07William32Karachi42000
01Mason26Saudi Arabia33000
02Avery24London15000
06Monty23Turkey12000
05Ella22Islamabad34000
04Harper20New York72000

Example 3:

This command sorts the result in ascending order by ADDRESS.

The command gives the below output.

IDNAMEAGEADDRESSSALARY
05Ella22Islamabad33000
01William32Karachi72000
02Avery24London34000
03Jackson34Paris12000
07Mason26Saudi50500
06Monty23Turkey42000
04Harper20United state15000

Next TopicT-SQL GROUP BY