A DISTINCT subquery returns unique combinations of selected columns before the result is used in a JOIN.
Removing duplicate relationship keys can prevent unwanted row multiplication.
Join customers with a unique list of customers who have active accounts.
SELECT
c.CustomerName,
a.CustomerID
FROM Customers c
INNER JOIN (
SELECT DISTINCT
CustomerID
FROM Accounts
WHERE AccountStatus = 'Active'
) a
ON c.CustomerID = a.CustomerID;
Used in data-quality checks, master-data integration, customer analytics, and reporting.
- DISTINCT removes duplicate selected combinations.
- It can control JOIN cardinality.
- Only columns needed for uniqueness should be selected.
- DISTINCT should not be used blindly to hide duplicate-data problems.
- The underlying relationship should still be understood.
Why use DISTINCT before a JOIN?
It can ensure that the JOIN input contains unique keys and prevent unwanted row multiplication.
Can DISTINCT hide a data problem?
Yes. It can hide unexpected duplicates instead of addressing their underlying cause.