QA
Beginner LevelPostgreSQL

How does DISTINCT ON (column) select the first row for each logical group?

❓ Interview Prompt: Explain `DISTINCT ON (column_list)`, selecting top record per group, pairing with `ORDER BY`, and eliminating window function overhead.

'DISTINCT ON (expression)' is a PostgreSQL-specific extension that keeps ONLY the first row for each group of matching expressions:

How It Works:

Pair 'DISTINCT ON (group_key)' with 'ORDER BY group_key, sort_key' to retrieve the top record per group in a single pass without subqueries or window functions!

Code Implementation Example

sql
-- Find the most recent order for every customer
SELECT DISTINCT ON (customer_id) customer_id, order_date, total_amount
FROM orders
ORDER BY customer_id, order_date DESC;
💡Selecting the latest order per customer using DISTINCT ON.
🎯 Interview Key Takeaway

Use DISTINCT ON (group_key) combined with ORDER BY to retrieve the top record per group efficiently.

#DISTINCT ON#ORDER BY#Grouping#Beginner
Back to all PostgreSQL Questions→

More PostgreSQL Interview Questions

Beginner LevelPostgreSQL

How to use pgvector in PostgreSQL for vector similarity search with HNSW indexes?

Beginner LevelPostgreSQL

What is PostgreSQL architecture and how do client backends connect via process fork model?

Beginner LevelPostgreSQL

What special built-in data types exist in PostgreSQL (JSONB, UUID, ARRAY, INET, TEXT)?