ORDER BY & TOP
What you’ll learn
- Sort results; take first N rows with
TOPandWITH 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 TIESreturns extra rows that tie on theORDER BYkeys.- Use deterministic
ORDER BYwith secondary columns to break ties.