AI Hints
Home›PostgreSQL Tutorial›DISTINCT ON, generate_series, Report
PostgreSQL · Lesson 34 of 120

DISTINCT ON

One row per group.

⏱ 2 min read▶ Video at 29:33🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

For each customer, show their most recent order. Postgres has a neat shortcut for one row per group, called distinct on.

  • Each customer
  • Latest order
  • DISTINCT ON

Latest order per customer

Distinct on customer ID keeps the first row for each customer. Order by decides which row is first, so the newest date comes first. Run it. Each customer's latest order.

query.sqlsql
SELECT DISTINCT ON (customer_id)
       customer_id, order_id, order_date, status
FROM orders
ORDER BY customer_id, order_date DESC
LIMIT 4;
Output
 customer_id | order_id | order_date |  status
-------------+----------+------------+-----------
           1 |     1001 | 2025-03-06 | delivered
           2 |     1004 | 2025-02-19 | shipped
           3 |     1006 | 2025-02-05 | delivered
           6 |     1007 | 2025-12-17 | delivered
(4 rows)

DISTINCT ON rules

The distinct on columns must come first in order by. The rest of order by picks the winner in each group. It's Postgres only, and often simpler than row number.

keyvalue
ORDER BYstarts with the same cols
Thenpick the winner
Postgresonly
vs row_numbershorter

Summary

Distinct on keeps one row per group, chosen by order by. Next, generating rows with generate series.

Key takeaways
  • DISTINCT ON
  • ORDER BY
  • One per group
Next up: generate_series — make rows from nothing