DISTINCT Keyword
DISTINCT removes duplicate rows from query results. Use it when you want unique values from a column or combination of columns. It's applied after all other clauses run — only in the final SELECT output.
DISTINCT Basics
- SELECT DISTINCT col — returns only unique values of that column
- SELECT DISTINCT col1, col2 — unique combinations of both columns
- DISTINCT applies to the whole row, not a single column in multi-column SELECT
- Can be slower on large tables — requires sorting/hashing
- COUNT(DISTINCT col) — count unique values
DISTINCT Examples
-- All unique statuses in orders table
SELECT DISTINCT status FROM orders;
-- Result: 'delivered', 'pending', 'shipped'
-- Unique user_ids who placed orders
SELECT DISTINCT user_id FROM orders;
-- Result: 1, 2
-- Distinct combination (both columns together)
SELECT DISTINCT user_id, status FROM orders;
-- Returns unique (user_id, status) pairs
-- Count distinct users who ordered
SELECT COUNT(DISTINCT user_id) AS active_customers
FROM orders;
-- Result: 2
-- Unique payment methods used
SELECT DISTINCT payment_method FROM payments;
-- Result: 'credit_card', 'paypal'
-- Without DISTINCT (shows duplicates):
SELECT user_id FROM orders;
-- 1, 2, 1 ← user 1 appears twice (2 orders)
-- With DISTINCT:
SELECT DISTINCT user_id FROM orders;
-- 1, 2 ← each user onceQuick Quiz
Tip
Tip
Practice DISTINCT Keyword in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Common Mistake
Warning
A common mistake with DISTINCT Keyword is skipping edge case testing — empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready sql code.
Practice Task
Note
Practice Task — (1) Write a working example of DISTINCT Keyword from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Key Takeaways
- DISTINCT removes duplicate rows from query results.
- SELECT DISTINCT col — returns only unique values of that column
- SELECT DISTINCT col1, col2 — unique combinations of both columns
- DISTINCT applies to the whole row, not a single column in multi-column SELECT