Learn SQL/Advanced/Window Functions/SQL Latest Record per Customer

SQL Latest Record per Customer

Return the newest complete row for every customer or other business key.

What & Why

The latest-record pattern ranks each entity's rows from newest to oldest and keeps row one. It produces current-state snapshots without losing columns that belong to the chosen record.

See How It Works

BUSINESS QUESTION

Return the latest invoice record for every SaaS account.

idaccount_idamountstatusdue_datepaid_at
101240.00paid2024-02-012024-01-29 13:00:00+00
111260.00paid2024-03-012024-02-28 16:30:00+00
12290.00overdue2024-03-15NULL
133480.00open2024-04-01NULL
EXAMPLE QUERY
WITH ranked AS (
  SELECT
    id AS invoice_id,
    account_id,
    amount,
    status,
    due_date,
    ROW_NUMBER() OVER (
      PARTITION BY account_id
      ORDER BY due_date DESC, id DESC
    ) AS recency_number
  FROM saas.invoices
)
SELECT invoice_id, account_id, amount, status, due_date
FROM ranked
WHERE recency_number = 1
ORDER BY account_id;
RESULT — latest invoice per SaaS account
invoice_idaccount_idamountstatusdue_date
111260.00paid2024-03-01
12290.00overdue2024-03-15
133480.00open2024-04-01

Account 1 keeps invoice 11 because it has the later due date; accounts 2 and 3 keep their only invoices.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario