Using DISTINCT ON to Get Unique Rows per Group in PostgreSQL
📖 Scenario: You work for a company that stores sales data in a PostgreSQL database. Each sale record includes the customer, the product sold, and the sale date. You want to find the most recent sale for each customer.
🎯 Goal: Build a SQL query using DISTINCT ON to select the latest sale record for each customer.
📋 What You'll Learn
Create a table called
sales with columns customer (text), product (text), and sale_date (date).Insert at least 5 rows with multiple sales per customer.
Write a query using
DISTINCT ON (customer) to get the latest sale per customer.Order the results by
customer and sale_date DESC.💡 Why This Matters
🌍 Real World
Finding the latest record per group is common in reporting, such as showing the most recent purchase per customer.
💼 Career
Database developers and analysts often use DISTINCT ON in PostgreSQL to simplify queries that require unique rows per group.
Progress0 / 4 steps