Home > Database > Mysql Tutorial > How Can I Efficiently Select Rows with Non-Unique Column Values in a Database?

How Can I Efficiently Select Rows with Non-Unique Column Values in a Database?

Barbara Streisand
Release: 2024-12-22 14:53:11
Original
447 people have browsed it

How Can I Efficiently Select Rows with Non-Unique Column Values in a Database?

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template