SQL DISTINCT Function
Quick summary: The SQL DISTINCT keyword removes duplicate rows from a result set.
SQL DISTINCT Syntax
SELECT DISTINCT column1, column2 FROM table_name
SQL
SQL DISTINCT Basic examples
SELECT DISTINCT country FROM users;
SQL
Output:
Unique country values
Returns each country only once.
SQL DISTINCT Real-world usage
SELECT DISTINCT status FROM orders;
SQL
Output:
paid, pending, canceled
Lists unique order statuses.
SQL DISTINCT Edge cases
SELECT DISTINCT first_name, last_name FROM users;
SQL
Output:
Unique name combinations
DISTINCT applies to all selected columns.
SQL DISTINCT Common mistakes
Using DISTINCT unnecessarily
DISTINCT can be expensive on large datasets.
Incorrect
SELECT DISTINCT * FROM users;
Correct
SELECT id, email FROM users;
Avoid DISTINCT when uniqueness is guaranteed.
SQL DISTINCT Frequently Asked Questions
What does DISTINCT do in SQL?
Removes duplicate rows from the result set.
Use case of DISTINCT?
Getting unique values.
Works with multiple columns?
Yes.
Common mistake?
Expecting it to remove partial duplicates.
Performance impact?
Can be expensive on large datasets.
Alternative?
GROUP BY.
Used with SELECT?
Yes.
Can use with ORDER BY?
Yes.
Handles NULL values?
Treats NULL as a distinct value.
Returns sorted data?
No.
Best practice?
Use only when needed.
Used in analytics?
Yes.