ORDER BY & TOP
Sorting, TOP, WITH TIES, NULLS LAST workaround.
What you’ll learn
- Sort results; take first N rows with
TOP
andWITH 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 theORDER BY
keys.- Use deterministic
ORDER BY
with secondary columns to break ties.