SELECT with ORDER BY


By:

Overview
In this tutorial we will issue a variety of SELECT statements with ORDER BY clauses to show how data can be sorted in both ascending and descending.  We are going to offer examples with character, numeric and date based columns.  We will also provide some examples on combinations of these columns and ORDER BY logic.  Let's take a look at an example. 

Explanation
In the examples below we are selecting a variety of columns from the HumanResources.Employee table and ordering the data in a variety of ways to show the various options available in SQL Server.  In the first example, we are ordering the data by the HireDate column in ascending order.  In the second example, we are ordering the data by the LoginID column in descending order.  In the third example, we are first ordering the data by the LoginID column in ascending order and then by the HireDate column in descending order.

Data in ascending order

USE AdventureWorks;
GO 
SELECT LoginID, EmployeeID, HireDate
FROM HumanResources.Employee
ORDER BY HireDate ASC;
GO

ELECTStatementwithOrderByClause 1
 

Data in descending order

USE AdventureWorks;
GO 
SELECT LoginID, EmployeeID, HireDate
FROM HumanResources.Employee
ORDER BY LoginID DESC;
GO

ELECTStatementwithOrderByClause 2
 

A column in ascending order and a separate column in descending order

USE AdventureWorks;
GO 
SELECT LoginID, EmployeeID, HireDate
FROM HumanResources.Employee
ORDER BY LoginID ASC, HireDate DESC;
GO

ELECTStatementwithOrderByClause 3
 






Comments For This Article

















get free sql tips
agree to terms