Skip to content

ORDER BY

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.

SELECT * FROM Products ORDER BY Price; -- ascending by default
SELECT * FROM Products ORDER BY Price DESC; -- highest first
-- Sort by multiple columns -- ties on the first are broken by the second
SELECT * FROM Employees ORDER BY DepartmentId, LastName;
-- Mixed directions
SELECT * FROM Products ORDER BY Category ASC, Price DESC;
-- Combine with paging (OFFSET/FETCH requires ORDER BY)
SELECT * FROM Products
ORDER BY Price
OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY; -- rows 21-30, e.g. "page 3" of 10

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 tomorrow
SELECT * FROM Orders;
-- Explicit, guaranteed order
SELECT * FROM Orders ORDER BY Id;
  1. Does SQL Server guarantee row order for a query with no ORDER BY clause?

    AnswerNo β€” without ORDER BY, the returned row order is unspecified and can change between executions, even if it happens to look consistent in practice.
  2. What does ORDER BY DepartmentId, LastName do when two rows have the same DepartmentId?

    AnswerTies on DepartmentId are broken by sorting on LastName as the secondary sort key.
  3. What clause is required alongside OFFSET ... FETCH NEXT ... for paging results?

    AnswerORDER BY β€” SQL Server requires an explicit order before you can meaningfully skip/take a specific "page" of rows.