Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: SQL Server
Expertise: Beginner
Jun 12, 2000

Ordering Query Output By Two Fields

Question:
I want to order the output of my query by two fields. Is this possible? That is, if two values are the same, I want the output ordered by a second field.

Answer:
The standard ORDER BY clause allows you to sort query output by one or more columns. For example, if you have a query to retrieve orders from the Northwind Orders table you can sort it by CustomerID and EmployeeID like this:

SELECT OrderID, CustomerID, EmployeeID, OrderDate 
FROM Orders
ORDER BY CustomerID, EmployeeID
With this result:
OrderID     CustomerID EmployeeID  OrderDate                   
----------- ---------- ----------- --------------------------- 
10835       ALFKI      1           1998-01-15 00:00:00.000
10952       ALFKI      1           1998-03-16 00:00:00.000
11011       ALFKI      3           1998-04-09 00:00:00.000
10692       ALFKI      4           1997-10-03 00:00:00.000
10702       ALFKI      4           1997-10-13 00:00:00.000
10643       ALFKI      6           1997-08-25 00:00:00.000
10625       ANATR      3           1997-08-08 00:00:00.000
10759       ANATR      3           1997-11-28 00:00:00.000
By default each ORDER BY expression sorts the results in ascending order. But you can specify the direction of the sort for each expression separately like this:
SELECT OrderID, CustomerID, EmployeeID, OrderDate 
FROM Orders
ORDER BY CustomerID ASC, EmployeeID DESC
With this result:
 
OrderID     CustomerID EmployeeID  OrderDate                   
----------- ---------- ----------- --------------------------- 
10643       ALFKI      6           1997-08-25 00:00:00.000
10692       ALFKI      4           1997-10-03 00:00:00.000
10702       ALFKI      4           1997-10-13 00:00:00.000
11011       ALFKI      3           1998-04-09 00:00:00.000
10835       ALFKI      1           1998-01-15 00:00:00.000
10952       ALFKI      1           1998-03-16 00:00:00.000
10308       ANATR      7           1996-09-18 00:00:00.000
10926       ANATR      4           1998-03-04 00:00:00.000
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date