Sorting with ORDER BY
ORDER BY sorts a query's results by one or more columns, in ascending or descending order.
Basic and Multi-Column Sorting
By default, ORDER BY sorts ascending (ASC). Adding DESC reverses that. Sorting by multiple columns applies each as a tiebreaker for the ones before it, in the order listed.
SELECT FirstName, LastName, Department, Salary
FROM Employees
ORDER BY Department ASC, Salary DESC;
Sorting by Column Position or Alias
You can sort by a column's position number in the SELECT list, or by an alias defined in that same statement — though sorting by explicit column name is usually clearer and safer against future changes.
Common Mistakes
- Forgetting that ASC is the default, and mistakenly assuming results are unsorted without an explicit direction.
- Sorting by a computed alias that was mistyped, which SQL Server will reject since it cannot resolve the alias.
- Assuming ORDER BY runs before WHERE — WHERE filters first, and ORDER BY only sorts what remains.
- Relying on a table's "natural" row order without ORDER BY — SQL Server makes no guarantee about order unless you specify one.
Professional Tip
Never assume query results come back in a particular order unless you've added an explicit ORDER BY. SQL Server's internal storage and query optimisation can return rows in different orders even for the exact same query run twice.
Your Turn
Write a query listing all products sorted by category alphabetically, and within each category, by price from highest to lowest.
Mini Quiz
What is the default sort direction in T-SQL if you don't specify ASC or DESC?