HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

How is ORDER BY logically Processed

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
orderlogicallyprocessedhow

Problem

Take this example:

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

ORDER BY LastName ASC,
         FirstName ASC


The 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 ASC

Context

StackExchange Database Administrators Q#48593, answer score: 3

Revisions (0)

No revisions yet.