10 / 10

ORDER BY & TOP

Sorting, TOP, WITH TIES, NULLS LAST workaround.

What you’ll learn

  • Sort results; take first N rows with TOP and WITH TIES.
  • Handle NULL ordering.
-- Latest 10 orders, including ties by date
SELECT TOP (10) WITH TIES *
FROM dbo.Orders
ORDER BY OrderDate DESC;

-- NULLS LAST (workaround)
SELECT *
FROM dbo.Products
ORDER BY CASE WHEN Color IS NULL THEN 1 ELSE 0 END, Color;

Notes

  • WITH TIES returns extra rows that tie on the ORDER BY keys.
  • Use deterministic ORDER BY with secondary columns to break ties.