Rank a user's orders by recency.
Section: window functions
Assign row numbers within each user
sql
sql
SELECT
user_id,
id AS order_id,
created_at,
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at DESC) AS rn
FROM orders;Explanation
Helpful for picking latest rows per entity.
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 window functions