Introduction
To get one unique row per group from a table, picking the first row based on a specific order.
To get one unique row per group from a table, picking the first row based on a specific order.
SELECT DISTINCT ON (group_column) group_column, other_columns FROM table_name ORDER BY group_column, order_column [ASC|DESC];
SELECT DISTINCT ON (customer_id) customer_id, order_id, order_date FROM orders ORDER BY customer_id, order_date DESC;
SELECT DISTINCT ON (category) category, product_name, price FROM products ORDER BY category, price ASC;
This creates a table of orders, inserts some sample data, then selects the latest order per customer.
CREATE TABLE orders ( order_id SERIAL PRIMARY KEY, customer_id INT, order_date DATE ); INSERT INTO orders (customer_id, order_date) VALUES (1, '2024-01-01'), (1, '2024-02-01'), (2, '2024-01-15'), (2, '2024-01-10'), (3, '2024-03-01'); SELECT DISTINCT ON (customer_id) customer_id, order_id, order_date FROM orders ORDER BY customer_id, order_date DESC;
Always include ORDER BY with DISTINCT ON to control which row you get per group.
DISTINCT ON returns the first row it finds per group based on ORDER BY.
DISTINCT ON helps pick one unique row per group in PostgreSQL.
Use ORDER BY to decide which row to keep.
Great for getting latest, earliest, or specific rows per group.
DISTINCT ON clause do in PostgreSQL?DISTINCT ON returns only one row per group defined by the columns inside the parentheses.ORDER BY clause.DISTINCT ON?DISTINCT ON (customer_id).customer_id, then order by order_date DESC to get latest order.sales with columns region, sale_date, and amount, what will this query return?SELECT DISTINCT ON (region) region, sale_date, amount FROM sales ORDER BY region, sale_date DESC;
SELECT DISTINCT ON (user_id) user_id, login_time FROM logins ORDER BY login_time ASC;
user_id as the first column.login_time ASC, missing user_id first, causing error.messages with columns chat_id, message_id, and sent_at. You want to get the most recent message per chat. Which query correctly achieves this?chat_id with the latest sent_at.Pass the test and this pattern moves unknown