Filtering and sorting
ORDER BY
Sort a result explicitly and resolve ties with additional columns.
Lesson 17 of 84
Reading: about 2 min
Lesson + practice: about 10 min
Difficulty: Beginner
On this page4 sections
This lesson uses DDI_SQL_Training dataset version 1.0.0 on SQL Server 2019 or later. A query result has no promised display order until you request one. ORDER BY turns a set of matching rows into a predictable presentation.
Run the example
SELECT CustomerID, FirstName, City
FROM dbo.Customers
ORDER BY City ASC, CustomerID ASC;Read it step by step
- ORDER BY City ASC sorts city names alphabetically. ASC is optional because ascending is the default.
- Several customers share a city. CustomerID ASC sorts those ties, giving each row a fixed position within its city.
- DESC reverses a sort. For example, ORDER BY ListPrice DESC, ProductID ASC ranks expensive products first and resolves equal prices by ID.
Check the result
| CustomerID | FirstName | City |
|---|---|---|
| 3 | Leo | Birmingham |
| 9 | Eli | Birmingham |
| 19 | Ben | Birmingham |
| 6 | Zara | Bristol |
| 13 | Sam | Bristol |
Birmingham comes before Bristol alphabetically. Within Birmingham, IDs 3, 9, and 19 rise in order. The sort changes display order only; it does not rearrange the stored table.
Practice
List the three most expensive products. Include ProductID as a tie breaker. Which products appear?
Check your answer and expected result
Reveal answer
SELECT TOP (3) ProductID, ProductName, ListPrice FROM dbo.Products ORDER BY ListPrice DESC, ProductID ASC;| ProductID | ProductName | ListPrice |
|---|---|---|
| 13 | Desk Chair | 189.00 |
| 15 | Shelf Unit | 149.00 |
| 2 | USB-C Dock | 129.00 |
IDs 13 (Desk Chair), 15 (Shelf Unit), and 2 (USB-C Dock) appear.
Your progress
Reveal the check answer or reach the end to complete this lesson.