This SQL tutorial focuses on the SQL Server ORDER BY clause, and provides explanations, examples and exercises. For this lesson exercises use this link.

The order of records retrieved by a query is undefined, to specify the order in which rows are displayed, you can use the SQL Server ORDER BY clause. This tutorial explains how to sort the query result set in an ascending and descending order, and also how to sort by multiple columns.


The ORDER BY clause

ORDER BY

Sort the results in ascending and descending order

The SQL Server ORDER BY clause is used to sort the query result set, based on a certain column:

ORDER BY column_name

For example, the following SQL Server example sorts the result set by salary (in ascending order, from the lowest to the highest):

SELECT employee_id, last_name, salary
FROM employees
ORDER BY salary

To reverse the order in which rows are displayed, use the keyword DESC after the column name in the SQL Server ORDER BY clause:

SELECT employee_id, last_name, salary
FROM employees
ORDER BY salary DESC

Sort by multiple columns

You can sort the query result set by more than one column. In the ORDER BY clause, specify the columns and separate them using commas.

This SQL Server example sorts the result set by department number and then by salary:

SELECT last_name, salary 
FROM employees
ORDER BY department_id, salary

This SQL Server example sorts the result set by department number in descending order and then by salary:

SELECT last_name , salary
FROM employees
ORDER BY department_id DESC, salary