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_ID | PRICE | NAME |
---|---|---|
1 | 200 | A |
2 | 500 | B |
3 | 900 | C |
4 | 500 | D |
Return the store rows ordered by price and name.
SELECT * FROM store
ORDER BY price, name;
OBJECT_ID | PRICE | NAME |
---|---|---|
1 | 200 | A |
2 | 500 | B |
4 | 500 | D |
3 | 900 | C |
Return the store rows ordered by name DESC.
SELECT * FROM store
ORDER BY name DESC;
OBJECT_ID | PRICE | NAME |
---|---|---|
4 | 500 | D |
3 | 900 | C |
2 | 500 | B |
1 | 200 | A |
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.