SQL ORDER BY
Sort Results with SQL ORDER BY
Once you get results you want to sort them using the SQL ORDER BY clause. Use it to specify columns or expressions to sort your results.
The general form of the command is:
SELECT column1, column2, column3
ORDER BY column1, column4
You can sort by more than one column, and the column don’t have to be displayed; however, they have to be known to the table.
In this example we’re sorting People by their LastName then FirstName.
-- Answer SELECT LastName, FirstName FROM Person.Person ORDER BY LastName
Results are usually sorted in Ascending order (A to Z); however, you can sort in descending order (Z to A) using the DESC keyword. To do so just add the DESC keyword to the end of the column.
SELECT LastName, FirstName
ORDER BY LastName DESC
You can add the key word to the end of any column in the SQL ORDER BY clause.
How about you try it.
Can you write a query to sort people by LastName in ascending order, and FirstName in descending order?
-- Answer SELECT LastName, FirstName FROM Person.Person ORDER BY LastName, FirstName DESC
ORDER BY Expressions (Calculated Values)
Consider the following query, how can we sort by the calculated amount TotalPrice?
UnitPrice * OrderQty AS TotalPrice
To do so we could add the same expression, UnitPrice * OrderQty, to our ORDER BY clause.
Or better yet, we can order by the column Alias TotalPrice. How about you try that? Can you rewrite the following query, so it orders the result by TotalPrice?
-- Answer SELECT PurchaseOrderID, UnitPrice, OrderQty, UnitPrice * OrderQty AS TotalPrice FROM Purchasing.PurchaseOrderDetail ORDER BY TotalPrice
Additional SELECT Statement Resources
If you’re looking to learn more about the SQL ORDER BY clause, then I would recommend you read our article Sort Your Query Results.
To learn more about functions, such as UPPER, check out our article Introduction to Common String Functions.
Looking for a super SQL book? Check out SQL Queries for Mere Mortals.