In this post explains how to use the ORDER BY clause in SQL Server (Transact-SQL) with syntax and examples.
The SQL Server (Transact-SQL) ORDER BY clause is used to sort the records in your result set. The ORDER BY clause can only be used in SELECT statements.
The syntax for the ORDER BY clause in SQL Server (Transact-SQL) is:
SELECT expressions
FROM tables
[WHERE conditions]
ORDER BY expression [ ASC | DESC ];
The columns or calculations that you wish to retrieve.
The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
Optional. The conditions that must be met for the records to be selected.
Optional. It sorts the result set in ascending order by expression (default, if no modifier is provider).
Optional. It sorts the result set in descending order by expression.
The SQL Server ORDER BY clause can be used without specifying the ASC or DESC value. When this attribute is omitted from the ORDER BY clause, the sort order is defaulted to ASC or ascending order.
For example:
SELECT last_name
FROM employees
WHERE employee_id > 1000
ORDER BY last_name;
This SQL Server ORDER BY example would return all records sorted by the last_name field in ascending order and would be equivalent to the following ORDER BY clause:
SELECT last_name
FROM employees
WHERE employee_id > 1000
ORDER BY last_name ASC;
Most programmers omit the ASC attribute if sorting in ascending order.
When sorting your result set in descending order, you use the DESC attribute in your ORDER BY clause.
For example:
SELECT last_name
FROM employees
WHERE first_name = 'Julie'
ORDER BY last_name DESC;
This SQL Server ORDER BY example would return all records sorted by the last_name field in descending order.
You can also use the SQL Server ORDER BY clause to sort by relative position in the result set, where the first field in the result set is 1. The next field is 2, and so on.
For example:
SELECT last_name
FROM employees
WHERE last_name = 'Mark'
ORDER BY 1 DESC;
This SQL Server ORDER BY would return all records sorted by the last_name field in descending order, since the last_name field is in position #1 in the result set and would be equivalent to the following ORDER BY clause:
SELECT last_name
FROM employees
WHERE last_name = 'Mark'
ORDER BY last_name DESC;
When sorting your result set using the SQL Server ORDER BY clause, you can use the ASC and DESC attributes in a single SELECT statement.
For example:
SELECT last_name, first_name
FROM employees
WHERE last_name = 'Johnson'
ORDER BY last_name DESC, first_name ASC;
This SQL Server ORDER BY would return all records sorted by the last_name field in descending order, with a secondary sort by first_name in ascending order.