T-SQL Tutorial

SQL ORDER BY


In SQL Server, the ORDER BY clause is used to sort the results of a query in a specific order.
The columns specified in the ORDER BY clause determine the sort order of the query results. By default, the sort order is ascending (ASC), but you can also specify descending order (DESC) by including the keyword after the column name.


ORDER BY syntax

The syntax for the ORDER BY clause is as follows:

SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC;



ORDER BY examples

You can also order multiple columns by specifying multiple column names separated by commas. For example, the following query will sort the results of the "customers" table by last name in ascending order and first name in descending order:

SELECT first_name, last_name
FROM customers
ORDER BY last_name ASC, first_name DESC;


It's also possible to sort by an expression or a column alias by including the expression or alias in the ORDER BY clause.

SELECT first_name, last_name,
(first_name + last_name) AS full_name
FROM customers
ORDER BY full_name DESC;


You can also use the TOP clause to only return a certain number of rows from the result set, which is useful when working with large tables.

SELECT TOP 10 *
FROM customers
ORDER BY last_name;


Store table example

OBJECT_IDPRICENAME
1200A
2500B
3900C
4500D

Return the store rows ordered by price and name.

SELECT * FROM store
ORDER BY price, name;

OBJECT_IDPRICENAME
1200A
2500B
4500D
3900C

Return the store rows ordered by name DESC.

SELECT * FROM store
ORDER BY name DESC;

OBJECT_IDPRICENAME
4500D
3900C
2500B
1200A

Keep in mind that the ORDER BY clause should be the last clause in a SELECT statement, after the WHERE and GROUP BY clauses if they are used.