How would you find the latest record per group, such as each customer latest order?

SQL joins · Experienced

Model answer

Use ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC) and keep row 1, or join to a subquery of MAX(created_at) per customer (careful with ties). PostgreSQL also has DISTINCT ON for this.

Learn this topic

SQL JOINs: INNER JOIN and LEFT JOIN Explained in the course SQL for Beginners: Learn Databases Step by Step.

Sign in to add your own answer.

More questions