Home >Database >Mysql Tutorial >How to Find and Retrieve Rows with Non-Unique Column Values in SQL?
Querying Rows with Non-Distinct Column Values
In SQL, a common task is to retrieve rows where the value of a specific column is not distinct. This can be useful in identifying duplicate data or detecting anomalies.
Example Scenario
Consider a table named Customers containing the following data:
CustomerName | EmailAddress |
---|---|
Aaron | [email protected] |
Christy | [email protected] |
Jason | [email protected] |
Eric | [email protected] |
John | [email protected] |
To retrieve all rows where the EmailAddress column is not distinct, we can use the following query:
SELECT EmailAddress, CustomerName FROM Customers WHERE EmailAddress IN (SELECT EmailAddress FROM Customers GROUP BY EmailAddress HAVING COUNT(*) > 1)
Explanation
The IN clause filters for EmailAddress values that are found in the subquery. The subquery groups all EmailAddress values and counts the occurrences of each value. The HAVING clause then selects only the groups with more than one occurrence (i.e., non-distinct values).
By using this approach, we efficiently identify and return rows where the EmailAddress column is not distinct. This method is significantly faster than using the EXISTS operator in most cases.
The above is the detailed content of How to Find and Retrieve Rows with Non-Unique Column Values in SQL?. For more information, please follow other related articles on the PHP Chinese website!