patternMinor
How is ORDER BY logically Processed
Viewed 0 times
orderlogicallyprocessedhow
Problem
Take this example:
I understand ORDER BY when one column is specified but how does the ORDER BY clause order the table by two or three columns? Which one is ordered first? What if the highest value in the SalesOrderID column does not correlate with the highest value in the OrderDate column?
SELECT SalesOrderID,
CustomerID,
SalesPersonID,
OrderDate
FROM Sales.SalesOrderHeader
ORDER BY OrderDate,
SalesOrderID DESC
OFFSET 0 ROWS
FETCH NEXT 10 ROWS ONLY;I understand ORDER BY when one column is specified but how does the ORDER BY clause order the table by two or three columns? Which one is ordered first? What if the highest value in the SalesOrderID column does not correlate with the highest value in the OrderDate column?
Solution
Think of the way telephone directories are (typically) ordered.
If they were generated by an SQL query it would be
The names are ordered by
The secondary column is only used for ordering within groups of people sharing the same last name.
If they were generated by an SQL query it would be
ORDER BY LastName ASC,
FirstName ASCThe names are ordered by
LastName first. The secondary column is only used for ordering within groups of people sharing the same last name.
Code Snippets
ORDER BY LastName ASC,
FirstName ASCContext
StackExchange Database Administrators Q#48593, answer score: 3
Revisions (0)
No revisions yet.