Selecting Rows with Non-Distinct Column Values
When working with data, it may be necessary to retrieve rows where specific column values are not distinct. For instance, in a table containing email addresses, it might be useful to identify duplicate email addresses across different customer records.
The provided query employs the GROUP BY and HAVING clauses to group rows by email address and identify those occurring more than once. However, it has been reported to have performance issues.
An alternative approach is to utilize an IN clause combined with a subquery. This method selects email addresses from the Customers table that appear more than once:
SELECT [EmailAddress], [CustomerName] FROM [Customers] WHERE [EmailAddress] IN (SELECT [EmailAddress] FROM [Customers] GROUP BY [EmailAddress] HAVING COUNT(*) > 1)
This query performance is generally faster than using the GROUP BY and HAVING clauses and should effectively return rows with duplicate email addresses.
The above is the detailed content of How Can I Efficiently Select Rows with Non-Unique Column Values in a Database?. For more information, please follow other related articles on the PHP Chinese website!