🐘 PostgreSQL
Beginner
How do you use DISTINCT in PostgreSQL?
Answer
SELECT DISTINCT returns only unique rows, eliminating duplicates. SELECT DISTINCT country FROM users; returns each country once. SELECT DISTINCT col1, col2 deduplicates based on the combination of both columns. DISTINCT ON is a PostgreSQL-specific extension: SELECT DISTINCT ON (user_id) * FROM orders ORDER BY user_id, created_at DESC; — returns one row per user_id, specifically the most recent order. The ORDER BY must start with the DISTINCT ON column(s). DISTINCT requires sorting or hashing all rows, which can be expensive — a GROUP BY or a subquery with ROW_NUMBER() is sometimes faster. Use COUNT(DISTINCT col) to count unique values.