Click here to Skip to main content
15,883,896 members
Articles / Database Development / SQL Server / SQL Server 2012

Getting Started With SQL Server: 2. Sort Your Query Results

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
24 Oct 2014MIT3 min read 7K   8   1
How to sort your query results in SQL Server

Introduction

In this lesson, you are going to explore how to sort your query results by using SQL’s ORDER BY statement. Using this phrase allows us to sort our result in ascending or descending order. In addition, you can limit your query to a specified number of results.

The lesson’s objectives are to:

  1. learn how to sort on one column in ascending or descending order
  2. sort on two or more columns
  3. sort on a calculated field
  4. limit our query to a specified number of results

ORDER BY

In order to sort a query’s results, use the ORDER BY clause. This clause comes after the FROM clause and is where you specify columns or expression to use to order your data.

When using the ORDER BY clause, the select statement takes the form.

SELECT columns FROM table ORDER BY columns;

So if you wanted to sort people by last name, you could state:

SQL
SELECT   FirstName,
         LastName
FROM     Person.Person
ORDER BY LastName

In addition, you can specify the direction to sort. Unless specified, all sorts are in ascending order (smallest to largest) and can be explicitly specified using the ASC keyword.

SQL
SELECT   FirstName,
         LastName
FROM     Person.Person
ORDER BY LastName ASC

To sort by LastName in descending order, you would issue the statement:

SQL
SELECT   FirstName,
         LastName
FROM     Person.Person
ORDER BY LastName DESC

DESC stand for Descending.

ORDER BY More than One Column

You can also order by more than one column. Just separate the columns you wish to sort with a comma. If you wanted to sort PurchaseOrderDetail by OrderQty and UnitPrice, enter:

SQL
SELECT   PurchaseOrderID,
         OrderQty,
         UnitPrice
FROM     Purchasing.PurchaseOrderDetail
ORDER BY OrderQty, UnitPrice

You can also specify the sort order, that is whether the columns are sorted in ascending or descending order. In this sample, the PurchaseOrderDetails are sorted in descending order by price within quantity.

SQL
SELECT   PurchaseOrderID,
         OrderQty,
         UnitPrice
FROM     Purchasing.PurchaseOrderDetail
ORDER BY OrderQty ASC, UnitPrice DESC

ORDER BY A Calculated Value

So far, you have learned to sort on one or more columns, but did you know you can sort on an expression? For instance, consider PurchaseOrderDetail, perhaps you would like to know who has largest orders. Of course, you can sort by Quantity or UnitPrice, but what about TotalPrice? That column doesn’t exist in the table, be we learned how to create it as an expression in our last lesson. Can we sort on this?

Sure!

Check out the following, and look closely at the ORDER BY clause, there you’ll see where it’s ordered by TotalPrice (UnitPrice * Quantity).

SQL
SELECT   PurchaseOrderID,
         UnitPrice,
         OrderQty
FROM     Purchasing.PurchaseOrderDetail
ORDER BY UnitPrice * OrderQty

To make it more clear, let's also display the TotalPrice.

SQL
SELECT   PurchaseOrderID,
         UnitPrice,
         OrderQty,
         UnitPrice * OrderQty AS TotalPrice
FROM     Purchasing.PurchaseOrderDetail
ORDER BY UnitPrice * OrderQty

And here is where aliasing, or renaming fields, can help. Here UnitPrice * OrderQty is aliased as TotalPrice in the SELECT clause. Now that’s done, we can simply refer to TotalPrice when specifying the sort order.

SQL
SELECT   PurchaseOrderID,
         UnitPrice,
         OrderQty,
         UnitPrice * OrderQty AS TotalPrice
FROM     Purchasing.PurchaseOrderDetail
ORDER BY TotalPrice

Get TOP Results

The last item I would like to go over with you is being able to limit the number of sorted results returned from a list. This makes it really easy to return the “first ten” or “top ten” items in a search. For instance, if you want to know the top five PurchaseOrderDetail items, you could enter the following query into SSMS:

SQL
SELECT   TOP 5 PurchaseOrderID,
               UnitPrice,
               OrderQty,
               UnitPrice * OrderQty AS TotalPrice
FROM     Purchasing.PurchaseOrderDetail
ORDER BY TotalPrice

The TOP keyword limits our search to the first five rows. You can limit by other numbers of course, in fact you can also limit by any number resulting from an expression.

Tip! To get the last five rows of a result, such as the smallest five orders, just order your result in descending order.

Exercises

It’s important to practice! Use the sample database to answer these questions.

  1. Write a statement to select Employee NationalIDNumbrer, MaritalStatus, BirthDate and JobTitle, sorted by BirthDate.
  2. Write a statement to select Person first and last names ordered by the upper case equivalent of their last name. Remember: We discussed UPPER in the previous lesson.
  3. Select the first two names to appear in a sort of Person LastNames.
  4. Select the last two names to appear in a sort of Person LastNames.

Answers to the Exercises

Congratulations! You just learned how to use the select command to query a database. More tutorials are to follow!

Remember! I want to remind you all that if you have other questions you want answered, then post a comment or tweet me. I’m here to help you.

What other topics would you like to know more about?

This article was originally posted at http://www.essentialsql.com?p=698

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Easy Computer Academy, LLC
United States United States
Hello my name is Kris. I’m here because I am passionate about helping non-techie people to overcome their fear of learning SQL.

I know what it is like to not know where to start or whether the time spent learning is worth the effort. That is why I am here to help you to:
- Get started in an easy to follow step-by-step manner.
- Use your time wisely so you focus on what is important to learn to get the most value from your time.
- Answer your questions. Really! Just post a comment and I’ll respond. I’m here to help.

It wasn’t long ago that I was helping a colleague with some reporting. She didn’t know where to start and soon got overwhelmed and lost as she didn’t know SQL.

I felt really bad, as she was under pressure to get some summary information to her boss, the built-in reports were falling short, and to make them better would require her to know SQL. At that time that seemed impossible! It in dawned on me, it doesn’t have to be that way.

Then I discovered a way for anyone with the desire to easily learn SQL. I worked with my co-worker, started to teach her what I learned and soon she was able to write reports and answer her boss’ questions without getting stressed or ploughing hours into manipulating data in Excel.

It hasn’t always been easy. Sometimes the information seems abstract or too conceptual. In this case I’ve found out that a visual explanation is best. I really like to use diagrams or videos to explain hard-to-grasp ideas.

Having video, pictures, and text really help to reinforce the point and enable learning.

And now I want to help you get the same results.

The first step is simple, click here http://www.essentialsql.com/get-started-with-sql-server/

Comments and Discussions

 
AnswerNot an article Pin
Akhil Mittal5-Nov-14 1:54
professionalAkhil Mittal5-Nov-14 1:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.