How to use SQL ORDER BY in Your Queries

In this article we will learn how to use SQL ORDER BY in your queries. SQL is a powerful tool for manipulating data and ordering results in a specific order. This tutorial will look at different ways to use SQL to order data in a Microsoft SQL Server database.

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 BY works.

ORDER BY Syntax

Below is the full syntax for ORDER BY

ORDER BY  Column_name  Asc
ORDER BY  Column_name  Desc 

SQL ORDER BY in Ascending Order on one column

SELECT [EmployeeID]
      ,[LastName]
      ,[FirstName]
      ,[Title]
      ,[Country]
  FROM [NorthWND].[dbo].[Employees] order by FirstName asc 
GO

SQL ORDER BY in Ascending Order on multiple columns

SELECT [EmployeeID]
      ,[LastName]
      ,[FirstName]
      ,[Title]
      ,[Country]
  FROM [NorthWND].[dbo].[Employees] order by FirstName,LastName asc 
GO

SQL ORDER BY Using Column Number

Let’s do it in some other way now instead of column name we can pass column position.

The most important details are that ORDER BY 1 still orders the results by LastName, but it is somewhat messy, tougher to read, and requires changing if the SELECT changes. You must know this but ideally this is not a good practice. 

SELECT 
      [LastName]
      ,[FirstName]
      ,[Title]
      ,[Country]
  FROM [NorthWND].[dbo].[Employees] order by 1  asc
GO
--	You can order by 2 if want to order by with second column i.e. FirstName 

Note: you can use ASC or DESC as per the requirement.

SQL ORDER BY on Multiple Columns in Ascending and Descending Order

We can also sort by multiple columns and mix ascending and descending orders.

SELECT 
      [LastName]
      ,[FirstName]
      ,[Title]
      ,[Country]
  FROM [NorthWND].[dbo].[Employees] order by LastName asc,FirstName desc

How to use SQL ORDER BY in Your Queries

You can see above record is ordered by “LastName” as Asc and “FirstName” as Desc. You can read more on this topic at Microsoft Learn 

I hope after reading above you will be able to use this in your development practices. For more such articles you can also check our SQL Section

You may also like:

Posted in SQL

Leave a Reply

Your email address will not be published. Required fields are marked *