← Back to SQL, page 20

sql-0381 · Medium mid

Use PostgreSQL's DISTINCT ON to return each customer's most recent order.

DISTINCT ON (customer_id) keeps the first row for each customer according to ORDER BY, so ordering by customer_id and then order_date DESC keeps the latest order. It is concise and fast with a matching index, but it is PostgreSQL-only; portable code uses ROW_NUMBER.

Full answer
sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);
sql
SELECT DISTINCT ON (customer_id) customer_id, id, order_date FROM orders ORDER BY customer_id, order_date DESC;
customer_ididorder_date
11022026-02-11
21052026-03-09
31042026-03-01
NULL1062026-03-12

The ORDER BY must start with the DISTINCT ON expressions; the columns after them decide which row is first in each group. Order 106 has no customer, and NULL forms its own group, so it appears too. Add WHERE customer_id IS NOT NULL to drop it.

The portable version on SQLite uses a window function:

sql
SELECT customer_id, id, order_date FROM (
  SELECT o.*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC, id DESC) AS rn FROM orders o
) WHERE rn = 1 ORDER BY customer_id;
customer_ididorder_date
NULL1062026-03-12
11022026-02-11
21052026-03-09
31042026-03-01

Both return one row per customer, but the NULL group sorts last in PostgreSQL and first in SQLite, which is each engine's default NULL ordering; add NULLS LAST or NULLS FIRST when the position matters. With ties on the date, DISTINCT ON picks an arbitrary row among them unless another ORDER BY column breaks the tie, so add id DESC for a stable result. An index on (customer_id, order_date DESC) lets PostgreSQL read groups in order.

sql
CREATE TABLE customers (
  id      INTEGER PRIMARY KEY,
  name    TEXT NOT NULL,
  country TEXT
);
CREATE TABLE orders (
  id          INTEGER PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id),
  order_date  TEXT NOT NULL,
  status      TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id   INTEGER REFERENCES orders(id),
  product    TEXT NOT NULL,
  qty        INTEGER NOT NULL,
  unit_price INTEGER NOT NULL
);
INSERT INTO customers VALUES (1,'Ana','Spain'),(2,'Bilal','UAE'),(3,'Chloe','France'),(4,'Dev','India');
INSERT INTO orders VALUES
  (101,1,'2026-01-05','shipped'),(102,1,'2026-02-11','shipped'),
  (103,2,'2026-02-14','cancelled'),(104,3,'2026-03-01','shipped'),
  (105,2,'2026-03-09','pending'),(106,NULL,'2026-03-12','shipped');
INSERT INTO order_items VALUES
  (101,'Notebook',2,4),(101,'Pen',5,1),(102,'Bag',1,30),(103,'Pen',10,1),
  (104,'Notebook',3,4),(104,'Bag',1,30),(105,'Lamp',1,25),(106,'Pen',2,1);

SELECT customer_id, id, order_date FROM (
  SELECT o.*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC, id DESC) AS rn FROM orders o
) WHERE rn = 1 ORDER BY customer_id;

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • DISTINCT ON keeps the first row per key by ORDER BY
  • ORDER BY must begin with the DISTINCT ON columns
  • Add a tiebreaker for stable results
  • ROW_NUMBER is the portable equivalent

Common mistakes

  • ORDER BY that does not start with the DISTINCT ON columns
  • Expecting DISTINCT ON to work in SQLite or MySQL

Follow-ups

  • How would you return the latest two orders per customer?
  • Which index helps DISTINCT ON?

Tips

  • Mention the ORDER BY rule