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.
OpenIn sheetsqlsame section
Return top values including ties
Use RANK when tied rows should all qualify.
OpenIn sheetsqlsame section
ROW_NUMBER
Unique sequence with no ties.
RANK
Tied rows share rank and leave gaps.
DENSE_RANK
Tied rows share rank without gaps.
Split rows into quartiles with NTILE
Bucket ordered rows into four groups.