ORDER BY
ORDER BY
Section titled βORDER BYβWhat it means
Section titled βWhat it meansβORDER BY sorts a queryβs result rows by one or more columns, ascending (ASC, the default) or descending (DESC). Without an ORDER BY clause, SQL Server does not guarantee any particular row order β the order you happen to see without one is an implementation detail, not a promise.
Examples
Section titled βExamplesβSELECT * FROM Products ORDER BY Price; -- ascending by defaultSELECT * FROM Products ORDER BY Price DESC; -- highest first
-- Sort by multiple columns -- ties on the first are broken by the secondSELECT * FROM Employees ORDER BY DepartmentId, LastName;
-- Mixed directionsSELECT * FROM Products ORDER BY Category ASC, Price DESC;
-- Combine with paging (OFFSET/FETCH requires ORDER BY)SELECT * FROM ProductsORDER BY PriceOFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY; -- rows 21-30, e.g. "page 3" of 10Common mistake
Section titled βCommon mistakeβAssuming a query without ORDER BY returns rows in insertion order, or in primary-key order β SQL Server makes no such guarantee. It may return rows in whatever order the query optimizer finds convenient (often related to index usage), and that order can change between runs, especially after schema or index changes.
-- No guaranteed order -- may "happen to" look sorted today, and change tomorrowSELECT * FROM Orders;
-- Explicit, guaranteed orderSELECT * FROM Orders ORDER BY Id;Quick practice
Section titled βQuick practiceβ-
Does SQL Server guarantee row order for a query with no
ORDER BYclause?Answer
No β withoutORDER BY, the returned row order is unspecified and can change between executions, even if it happens to look consistent in practice. -
What does
ORDER BY DepartmentId, LastNamedo when two rows have the sameDepartmentId?Answer
Ties onDepartmentIdare broken by sorting onLastNameas the secondary sort key. -
What clause is required alongside
OFFSET ... FETCH NEXT ...for paging results?Answer
ORDER BYβ SQL Server requires an explicit order before you can meaningfully skip/take a specific "page" of rows.