SQL Server ORDER BY Clause (2024)

Summary: in this tutorial, you will learn how to use the SQL Server ORDER BY clause to sort the result set of a query by one or more columns.

Introduction to the SQL Server ORDER BY clause

When using the SELECT statement to query data from a table, the order of rows in the result set is not specified. This means that SQL Server can return a result set with rows in an unspecified order.

The only way to guarantee that the rows in the result set are sorted is to use the ORDER BY clause.

Here’s the syntax of the ORDER BY clause:

SELECT select_listFROM table_nameORDER BY column_name | expression [ASC | DESC ];Code language: SQL (Structured Query Language) (sql)

In this syntax:

column_name | expression

First, you specify a column name or an expression by which to sort the result set of the query. If you specify multiple columns, the result set is sorted by the first column and then that sorted result set is sorted further by the second column, and so on.

The columns that appear in the ORDER BY clause must correspond to either column in the select list or columns defined in the table specified in the FROM clause.

ASC | DESC

Second, use ASC or DESC to specify whether the values in the specified column should be sorted in ascending or descending order.

The ASC keyword sorts the result from the lowest value to the highest value, while theDESC keyword sortsthe result set from the highest value to the lowest one.

If you don’t explicitly specify ASC or DESC, SQL Server uses ASC as the default sort order. Additionally, SQL Server treats NULL as the lowest value.

When processing the SELECT statement that has an ORDER BY clause, the SQL Server processes the ORDER BY clause last.

SQL Server ORDER BY clause example

We will use the customers table in the sample database from the demonstration.

SQL Server ORDER BY Clause (1)

1) Sort a result set by one column in ascending order

The following statement sorts the customer list by the first name in ascending order:

SELECT first_name, last_nameFROM sales.customersORDER BY first_name;Code language: SQL (Structured Query Language) (sql)
SQL Server ORDER BY Clause (2)

In this example, because we did not specify ASC or DESC, the ORDER BY clause used ASC by default.

2) Sort a result set by one column in descending order

The following statement sorts the customer list by the first name in descending order.

SELECTfirstname,lastnameFROMsales.customersORDER BYfirst_name DESC;Code language: SQL (Structured Query Language) (sql)
SQL Server ORDER BY Clause (3)

In this example, because we specified the DESC explicitly, the ORDER BY clause sorted the result set by values in the first_name column in descending order.

3) Sort a result set by multiple columns

The following statement retrieves the first name, last name, and city of the customers. It sorts the customer list by the city first and then by the first name.

SELECT city, first_name, last_nameFROM sales.customersORDER BY city, first_name;Code language: SQL (Structured Query Language) (sql)
SQL Server ORDER BY Clause (4)

4) Sort a result set by multiple columns and different orders

The following statement sorts the customers by the city in descending order and then sorts the sorted result set by the first name in ascending order.

SELECT city, first_name, last_nameFROM sales.customersORDER BY city DESC, first_name ASC;Code language: SQL (Structured Query Language) (sql)
SQL Server ORDER BY Clause (5)

5) Sort a result set by a column that is not in the select list

It is possible to sort the result set by a column that does not appear on the select list. For example, the following statement sorts the customer by the state even though the state column does not appear on the select list.

SELECT city, first_name, last_nameFROM sales.customersORDER BY state;Code language: SQL (Structured Query Language) (sql)
SQL Server ORDER BY Clause (6)

Note that the state column is defined in the customers table. If it was not, then you would have an invalid query.

6) Sort a result set by anexpression

The LEN() function returns the number of characters in a string. The following statement uses the LEN() function in the ORDER BY clause to retrieve a customer list sorted by the length of the first name:

SELECT first_name, last_nameFROM sales.customersORDER BY LEN(first_name) DESC;Code language: SQL (Structured Query Language) (sql)
SQL Server ORDER BY Clause (7)

7) Sort by ordinal positions of columns

SQL Server allows you to sort the result set based on the ordinal positions of columns that appear in the select list.

The following statement sorts the customers by first name and last name. But instead of specifying the column names explicitly, it uses the ordinal positions of the columns:

SELECT first_name, last_nameFROM sales.customersORDER BY 1, 2;Code language: SQL (Structured Query Language) (sql)

In this example, 1 means the first_name column, and 2 means the last_name column.

Using the ordinal positions of columns in the ORDER BY clause is considered a bad programming practice for a couple of reasons.

  • First, the columns in a table don’t have ordinal positions and need to be referenced by name.
  • Second, when you modify the select list, you may forget to make the corresponding changes in the ORDER BY clause.

Therefore, it is a good practice to always specify the column names explicitly in the ORDER BY clause.

Summary

  • Use the SQL Server ORDER BY clause to sort a result set by columns in ascending or descending order.
  • Use the ASC keyword to sort rows by a column in ascending order.
  • Use the DESC keyword to sort rows by a column in descending order.

Was this tutorial helpful?

SQL Server ORDER BY Clause (2024)

FAQs

How to use ORDER BY clause in SQL Server? ›

The ORDER BY command is used to sort the result set in ascending or descending order. The ORDER BY command sorts the result set in ascending order by default. To sort the records in descending order, use the DESC keyword.

What is the alternative of ORDER BY in SQL Server? ›

The ORDER BY clause in a query forces the database to return rows in the specified order. The only alternative is to just not use ORDER BY which means that the database is free to return the rows in any order it likes. This often results is faster performance and never in slower performance.

What is the DESC ASC order? ›

Answer: In general terms, Ascending means smallest to largest, 0 to 9, and/or A to Z and Descending means largest to smallest, 9 to 0, and/or Z to A. Ascending order means the smallest or first or earliest in the order will appear at the top of the list: For numbers or amounts, the sort is smallest to largest.

How to SELECT ORDER BY desc in SQL Server? ›

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 = 'Sarah' ORDER BY last_name DESC; This SQL Server ORDER BY example would return all records sorted by the last_name field in descending order.

How to use ORDER BY in SQL with condition? ›

SQL ORDER BY clause is used after the WHERE clause (i.e. after filtering the data) to sort the result in either Ascending or Descending order. DESC: Keyword is used to arrange the result in Descending Order. Note: Ascending is a default sort order.

Can we use two columns in ORDER BY clause? ›

You can also ORDER BY two or more columns, which creates a nested sort . The default is still ascending, and the column that is listed first in the ORDER BY clause takes precedence.

How to ORDER BY dynamically in SQL Server? ›

To do that, follow these steps:
  1. Add a query Parameter to the SQL query define the Name as SORT , the Data Type as Text and the Expand Inline Property to Yes . ...
  2. Add the SQL snippet ORDER BY @SORT to your SQL query.
  3. Define the SORT Parameter of your SQL query as List_SortColumn_GetOrderBy(<TableRecordsName>.
May 9, 2024

What is the difference between ORDER BY and sort by SQL? ›

The difference between "order by" and "sort by" is that the former guarantees total order in the output while the latter only guarantees ordering of the rows within a reducer. If there are more than one reducer, "sort by" may give partially ordered final results.

Is SQL ORDER BY stable? ›

The ORDER BY clause contains a column or combination of columns that are guaranteed to be unique. The simplest way to understand that a sort is not stable is to go back to the definition of a table. Tables are inherently unordered in SQL. So, there is no ordering to fall back on for "stability".

What is the difference between ORDER BY and ASC? ›

By default, ORDER BY is sorted in ascending order, so I guess there are no differences between your requests. From this documentation: ASC Optional -- It sorts the result set in ascending order by expression (default, if no modifier is provider).

Is ORDER BY ASC default? ›

If the order is not specified, ASC is the default. Specifies that the results should be returned in descending order.

How to ORDER BY two columns in SQL ASC and DESC? ›

To combine ascending and descending sorting for different columns:
  1. Specify the column names after the ORDER BY keyword, separated by commas.
  2. Add the ASC keyword for ascending order or the DESC keyword for descending order after each column name, depending on the desired sorting order for that column.

Is ORDER BY DESC or ASC in SQL? ›

ASC sorts from the lowest value to highest value. DESC sorts from highest value to lowest value. ASC is the default sort order. Null values are treated as the lowest possible values.

What is the ORDER BY clause in SQL? ›

The ORDER BY clause specifies the particular order in which you want selected rows returned. The order is sorted by ascending or descending collating sequence of a column's or an expression's value.

What is DESC command for SQL Server? ›

A desc command is also called a describe command in SQL. The command is case-insensitive and can be used in any of the below forms. Desc Table_Name; The above two commands perform the same function and will produce the same result.

How to use case in ORDER BY in SQL Server? ›

CASE Syntax:

CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 WHEN condition3 THEN result3 ELSE result END; ORDER BY: This keyword is used to sort the result-set in ascending or descending order. It sorts the records in ascending order by default.

How do you ORDER BY 2 DESC in SQL? ›

You can specify the sorting order by adding ASC for ascending or DESC for descending order after each column. For example: SELECT * FROM table_name ORDER BY column1 ASC, column2 DESC; This query sorts the results by column1 in ascending order and column2 in descending order.

How to use ORDER BY clause in view in SQL? ›

The ORDER BY clause is not valid in views, inline functions, derived tables, and subqueries, unless either the TOP or OFFSET and FETCH clauses are also specified. When ORDER BY is used in these objects, the clause is used only to determine the rows returned by the TOP clause or OFFSET and FETCH clauses.

How to use ORDER BY after WHERE clause in SQL? ›

The ORDER BY clause must come after the WHERE, GROUP BY, and HAVING clause if present in the query. Use ASC or DESC to specify the sorting order after the column name. Use ASC to sort the records in ascending order or use DESC for descending order.

References

Top Articles
Latest Posts
Article information

Author: Stevie Stamm

Last Updated:

Views: 5410

Rating: 5 / 5 (60 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Stevie Stamm

Birthday: 1996-06-22

Address: Apt. 419 4200 Sipes Estate, East Delmerview, WY 05617

Phone: +342332224300

Job: Future Advertising Analyst

Hobby: Leather crafting, Puzzles, Leather crafting, scrapbook, Urban exploration, Cabaret, Skateboarding

Introduction: My name is Stevie Stamm, I am a colorful, sparkling, splendid, vast, open, hilarious, tender person who loves writing and wants to share my knowledge and understanding with you.