Use ROW_NUMBER in a subquery or CTE.
Section: Top N per group
Get the latest row per group
sql
sql
WITH ranked AS (
SELECT o.*,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY created_at DESC
) AS rn
FROM orders o
)
SELECT *
FROM ranked
WHERE rn = 1;Explanation
This is one of the most useful window-function patterns for production SQL.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing Top N per group
Get top 3 rows per group
Keep the highest-value rows within each partition.
Return top values including ties
Use RANK when tied rows should all qualify.