SQL ORDER BY Examples to Sort and Order Data (2024)

By: Joe Gavin |Updated: 2023-04-10 |Comments (2) | Related: > TSQL


Problem

The SQL language can be very powerful in helping you manipulate data and one part of SQLthat can be super helpful is ordering results in a specific order. In this SQLtutorial, we will look at different ways you can use SQL to order data along withseveral examples in a Microsoft SQL Server database.

Solution

Sorting result sets is done using the SQL ORDER BY clause in a SELECT statement.ORDER BY, as the name implies, orders a result set in ascending or descending order.We'll step through some examples that show how ORDER BYworks.

AdventureWorks2019 Database

For these examples, we will use the free sample databaseAdventureWorks. All the examples are queryingthe Person.Person table.

We will use the AdventureWorksLT2019 database for the examples as follows.

USE [AdventureWorks2019];GO

ORDER BY Syntax

Here is the full syntax for ORDER BY:

ORDER BY order_by_expression [ COLLATE collation_name ] [ ASC | DESC ] [ ,...n ] [ <offset_fetch> ] <offset_fetch> ::= { OFFSET { integer_constant | offset_row_count_expression } { ROW | ROWS } [ FETCH { FIRST | NEXT } {integer_constant | fetch_row_count_expression } { ROW | ROWS } ONLY ] }

SQL ORDER BY in Ascending Order

First, in the following query we'll get a list of full names of employees(WHERE clause) and order the list byLastName in ascending sort order.

SELECT [LastName], [FirstName], [MiddleName]FROM [Person].[Person]WHERE [PersonType] = 'EM'ORDER BY [LastName];GO

The ORDER BY default is ascending order, and specifying it is optional.

Here we specify ascending order, but it willwork the same way with or without using ASC.

SELECT [LastName], [FirstName], [MiddleName]FROM [Person].[Person]WHERE [PersonType] = 'EM'ORDER BY [LastName] ASC;GO

SQL ORDER BY Examples to Sort and Order Data (1)

SQL ORDER BY Using Column Number

I want to preface this example by saying that just because you can do somethingdoes not mean you should.

It's valid to sort a result set on a column by usingthe column number based on its position in the SELECT statement. LastName is thefirst column, so it is number 1. ORDER BY 1 still orders the results by LastName.However, this is messy, tougher to read, and requires changing if the SELECT changes.It's definitely not a good practice.

SELECT [LastName], [FirstName], [MiddleName]FROM [Person].[Person]WHERE [PersonType] = 'EM'ORDER BY 1;GO

This will yield the same results as the previous two queries.

By not specifying the ascending or descending, the results will use thedefault of ascending order.

SQL ORDER BY in Descending Order

What if we want the result set sorted in descending order? As we saw, the firstthree examples are all ordering by the LastName column in ascending order. To returnthe results by LastName in descending order, simply specify DESCkeyword after ORDER BYLastName as shown with this SQL statement.

SELECT [LastName], [FirstName], [MiddleName]FROM [Person].[Person]WHERE [PersonType] = 'EM'ORDER BY [LastName] DESC;GO

SQL ORDER BY Examples to Sort and Order Data (2)

SQL ORDER BY on Multiple Columns

So far, our result sets have been sorted by only one column. We're notlimited to that.

Here, we sort by LastName first, then FirstName second. There arethree employees with the last name 'Brown'. Their first names, 'Eric, 'Jo',and 'Kevin', are sorted in ascending order.

SELECT [LastName], [FirstName], [MiddleName]FROM [Person].[Person]WHERE [PersonType] = 'EM'ORDER BY [LastName], [FirstName];GO

SQL ORDER BY Examples to Sort and Order Data (3)

SQL ORDER BY on Multiple Columns in Ascending and Descending Order

We can also sort by multiple columns and mix ascending and descending orders.To sort by LastName in ascending order and FirstName in descending order, we simplyput a 'DESC' after FirstName. Now we have the first names in the order: 'Kevin,'Jo',and 'Eric'.

SELECT [LastName], [FirstName], [MiddleName]FROM [Person].[Person]WHERE [PersonType] = 'EM'ORDER BY [LastName] ASC, [FirstName] DESC;GO

SQL ORDER BY Examples to Sort and Order Data (4)

Specify Number of Records to Return with ORDER BY

To specify the number of sorted records to return, we can use the TOP clausein a SELECT statement along with ORDER BY to give us the first x number of recordsin the result set.

This query will sort by LastName and return the first 25 records.

SELECT TOP 25 [LastName], [FirstName], [MiddleName]FROM [Person].[Person]WHERE [PersonType] = 'EM'ORDER BY [LastName] ASC;GO

SQL ORDER BY Examples to Sort and Order Data (5)

Limit Number of Rows Returned with ORDER BY

The OFFSET and SET clauses can also be used in an ORDER BY to limit the numberof rows returned by a query. OFFSET specifies how many rows to skip over beforestarting to return rows. For example, an OFFSET of 0 means skip 0 rows and startat the first row. FETCH optionally specifies how many rows to return.

This query says return the first 25 records of the employees' LastName,FirstName, and MiddleName starting at the first record:

DECLARE @PageNumber INT = 0DECLARE @RowsOfPage INT = 25 SELECT [LastName], [FirstName], [MiddleName]FROM [Person].[Person]WHERE [PersonType] = 'EM'ORDER BY [LastName] ASC, [FirstName] ASC OFFSET @PageNumber ROWSFETCH NEXT @RowsOfPage ROWS ONLY;GO

SQL ORDER BY Examples to Sort and Order Data (6)

Changing the OFFSET to 25 will give us the next 25 results.

DECLARE @PageNumber INT = 25DECLARE @RowsOfPage INT = 25 SELECT [LastName], [FirstName], [MiddleName]FROM [Person].[Person]WHERE [PersonType] = 'EM'ORDER BY [LastName] ASC, [FirstName] ASC OFFSET @PageNumber ROWSFETCH NEXT @RowsOfPage ROWS ONLY;GO

SQL ORDER BY Examples to Sort and Order Data (7)

The advantage of using OFFSET and FETCH is that it makes it possible to pagethrough a result set, just as we would see in a Google search. Here, we'llreturn all the records, 25 at a time in one query:

DECLARE @PageNumber INTDECLARE @RowsOfPage INTDECLARE @MaxTablePage FLOAT SET @PageNumber = 1SET @RowsOfPage = 25SELECT @MaxTablePage = COUNT(*)FROM [Person].[Person]WHERE [PersonType] = 'EM'SET @MaxTablePage = CEILING(@MaxTablePage / @RowsOfPage) WHILE @MaxTablePage >= @PageNumberBEGIN SELECT [LastName], [FirstName], [MiddleName] FROM [Person].[Person] WHERE [PersonType] = 'EM' ORDER BY [LastName] ASC, [FirstName] ASC OFFSET (@PageNumber - 1) * @RowsOfPage ROWS FETCH NEXT @RowsOfPage ROWS ONLY SET @PageNumber = @PageNumber + 1END;GO

SQL ORDER BY Examples to Sort and Order Data (8)

Next Steps

Here are some MSSQLTips with more examples of using the ORDER BY clause:

  • SELECT with ORDER BY
  • SQL ORDER BY Clause
  • SQL ORDER BY Clause Examples
  • SQL WHERE IS NOT NULL for SELECT, INSERT, UPDATE and DELETE
  • Advanced Use of the SQL Server ORDER BY Clause
  • SQL Server SELECT Examples
  • SQL Queries Tutorial
  • Avoid ORDER BY in SQL Server views
  • Building SQL Server Indexes in Ascending vs Descending Order
  • Execute Dynamic SQL commands in SQL Server
  • SQL Server Cursor Example




About the author

Joe Gavin is from the Greater Boston area. He started working with SQL Server and Sybase in 1998 in the financial services industry and has been a SQL Server Database Administrator for a dairy cooperative since 2011. He graduated from Northeastern University in Boston with a Bachelor of Science in Engineering Technology (BSET) degree in Computer Technology. Joe has spoken at the Boston and Providence SQL Saturday events.

This author pledges the content of this article is based on professional experience and not AI generated.

View all my tips

Article Last Updated: 2023-04-10

SQL ORDER BY Examples to Sort and Order Data (2024)

FAQs

How to sort data in SQL without using ORDER BY? ›

That could be possible if you would create a index on your table where first(or only) key is DEPARTMENT_ID and you would force your query engine to use this index. This should be a plain SELECT statement as well. But even then, it won't guarantee correct sort order. You cannot, at least not reliably.

How to ORDER BY a specific order in SQL? ›

SQL ORDER BY Keyword
  1. ORDER BY. The ORDER BY command is used to sort the result set in ascending or descending order. ...
  2. ASC. The ASC command is used to sort the data returned in ascending order. ...
  3. DESC. The DESC command is used to sort the data returned in descending order.

What are the best practices of ORDER BY in SQL? ›

Best Practices of Using ORDER BY in SQL

To reduce processing overhead, include only the columns needed for sorting. Define an index with the same columns and in the same order as the ORDER BY clause to improve query performance.

What is the default sort order when using the ORDER BY keyword in SQL? ›

The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

What is the alternative to ORDER BY in SQL? ›

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.

Does order matter in ORDER BY SQL? ›

SQL Server is smart enough to understand that the order of columns in the GROUP BY doesn't matter.

What is ORDER BY clause with an example? ›

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. The result follows. Note: Null values are ordered as the highest value.

How do you sort data in a specific order? ›

On the Data tab, in the Sort & Filter group, click Sort. In the Sort dialog box, under Column, in the Sort by or Then by box, select the column that you want to sort by a custom list. Under Order, select Custom List. In the Custom Lists dialog box, select the list that you want.

How to write ORDER BY and WHERE in SQL? ›

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.

What is the advantage of ORDER BY in SQL? ›

Benefits and Use Cases

The Order by Clause is advantageous for data processing and analytics because it: Improves data readability by organizing query results in a logical order. Enables efficient identification of trends and patterns by sorting data based on specific criteria.

When to use ORDER BY in SQL? ›

SQL ORDER BY syntax and usage. The SQL ORDER BY clause is primarily used to sort the result of a SELECT query statement. When you need to display data in a specific order based on the values in one or more columns, the ORDER BY clause comes in handy.

What is the correct order of a SQL? ›

It also helps to predict the outcome of queries, troubleshoot issues, and optimize performance. What is the correct order of execution for a given query? The correct order of execution in SQL is FROM, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY and LIMIT.

What is the correct sequence when using ORDER BY and limit together? ›

How ORDER BY and LIMIT go together. Being able to order the result rows is particularly useful when using LIMIT , as it allows us to quickly return just the "top 3" or "bottom 10" of the results. The ORDER BY clause goes after the FROM clause but before the LIMIT .

How to ORDER BY ascending in SQL? ›

If you want to sort some of the data in ascending order and other data in descending order, then you would have to use the ASC and DESC keywords. SELECT * FROM table ORDER BY column1 ASC, column2 DESC; That is how to use the ORDER BY clause in SQL to sort data in ascending order.

What is an example of an ascending order? ›

Ascending order is a method of arranging numbers from smallest value to largest value. The order goes from left to right. Ascending order is also sometimes named as increasing order. For example, a set of natural numbers are in ascending order, such as 1 < 2 < 3 < 4 < 5 < 6 < 7 < 8… and so on.

How to avoid ORDER BY in SQL Server? ›

Avoid ORDER BY in SQL Server views
  1. Problem. ...
  2. Solution. ...
  3. USE WideWorldImporters; GO CREATE VIEW dbo.CustomersByName AS SELECT CustomerID, CustomerName, DeliveryCityID FROM Sales.Customers ORDER BY CustomerName; GO. ...
  4. Msg 1033, Level 15, State 1, Procedure CustomersByName.

How do I sort randomly in SQL? ›

Basic Random Ordering

To select rows from a table in a random order, use the ORDER BY RAND() clause. For example: SELECT * FROM your_table ORDER BY RAND(); This query selects all rows from your_table and orders them randomly.

Can we use limit without ORDER BY in SQL? ›

If you are not using the ORDER BY then you are not sorting your records, so it will definitely make your data retrieval faster. So if you simply use LIMIT then it would be faster as compared to the data retrieved through ORDER BY. But do note that, in that case the data will not be in any order.

Is ORDER BY mandatory in SQL? ›

To sum up, the SQL ORDER BY clause is not mandatory. Rather, it is a helpful tool. Whenever you need to sort your data in ascending or descending order, you can use it.

References

Top Articles
Latest Posts
Article information

Author: Lidia Grady

Last Updated:

Views: 5420

Rating: 4.4 / 5 (65 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Lidia Grady

Birthday: 1992-01-22

Address: Suite 493 356 Dale Fall, New Wanda, RI 52485

Phone: +29914464387516

Job: Customer Engineer

Hobby: Cryptography, Writing, Dowsing, Stand-up comedy, Calligraphy, Web surfing, Ghost hunting

Introduction: My name is Lidia Grady, I am a thankful, fine, glamorous, lucky, lively, pleasant, shiny person who loves writing and wants to share my knowledge and understanding with you.