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


 

Data in descending order

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


 

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


 


Last Update: 3/25/2009




More SQL Server Solutions











Post a comment or let the author know this tip helped.

All comments are reviewed, so stay on subject or we may delete your comment. Note: your email address is not published. Required fields are marked with an asterisk (*).

*Name
*Email
Email me updates

Signup for our newsletter

I agree by submitting my data to receive communications, account updates and/or special offers about SQL Server from MSSQLTips and/or its Sponsors. I have read the privacy statement and understand I may unsubscribe at any time.






download





get free sql tips

I agree by submitting my data to receive communications, account updates and/or special offers about SQL Server from MSSQLTips and/or its Sponsors. I have read the privacy statement and understand I may unsubscribe at any time.



Learn more about SQL Server tools