← All Exercises

First Purchase per Customer with DISTINCT ON

basicsql~20min

Background

Retention and lifecycle emails depend on the first purchase date. A single pass with DISTINCT ON is simpler than a correlated subquery and easy to index.

Problem

Given customers and orders tables, return one row per customer who has ordered, showing the customer, the first order id, its timestamp, and its total.

Input

PostgreSQL customers(id integer PRIMARY KEY, name text) and orders(id integer PRIMARY KEY, customer_id integer REFERENCES customers, ordered_at timestamptz, total numeric(10,2)).

Output

One row per customer with at least one order containing customer_id, name, first_order_id, ordered_at, and total, ordered by customer_id ascending.

Sample tests

Sample 1

Input: Alice orders 101 at 2026-01-05 and 102 at 2026-02-01; Bob order 103 at 2026-01-20; Carol has no orders
Expected: 1 | Alice | 101 | 2026-01-05 | 120.00
2 | Bob | 103 | 2026-01-20 | 45.50

Sample 2

Input: a separate dataset with only customer Bob (id 2), whose orders 201 and 202 share the timestamp 2026-03-01 10:00
Expected: 2 | Bob | 202 | 2026-03-01 10:00 | 30.00

Your solution

Learning objective

Use DISTINCT ON, understand its ORDER BY contract, and translate a per-group first-row problem into one pass.