Sql-server – How is ORDER BY logically Processed

order-bysql-server-2012t-sql

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?

Best Answer

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.