PostgreSQL: latest price per product with DISTINCT ON (greatest-n-per-group)

Backend Live Coding November 13, 2026 sql

How do you get the latest price per product (greatest-n-per-group) in PostgreSQL?

sql
1
2
3
4
5
6
7
8
9
-- ======================================================================
-- Q: How do you get the latest price per product (greatest-n-per-group) in
-- PostgreSQL?
-- ======================================================================

SELECT DISTINCT ON (product_id) product_id, amount, created_at
FROM price_history
ORDER BY product_id, created_at DESC;
-- index: (product_id, created_at DESC)