SteelReed

Search

Search posts, questions…

SQL & Query TuningQuestion 17 / 37

Middle

How do you get the 3 latest orders of each customer (top-N per group)?

Short answer

Number rows within each group with ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC), then filter rn <= 3 in an outer query. When each customer has very many orders, use LATERAL with an index.

most customers, few ordersfew customers, manyordersTop 3 ordersper customerROW_NUMBERPARTITION BY customerFilter rn ≤ 3in outer queryLATERAL + indexcustomer, date descRead 3 entriesper customer, stop

3 points to say:

  1. ROW_NUMBER, filter in the outer query.
  2. Many rows per group: LATERAL + index.
  3. Add id to ORDER BY.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.