Thursday, February 12, 2009

SQL: Finding Duplicate Values

It turns out there's another use for the HAVING clause that I hadn't considered before. This came to me when taking a written quiz for a job interview.

"Write a query to find duplicate 'name' values in a 'user' table"

I had to think about this for a few minutes. It's really easy to suppress duplicates. But returning only duplicates is not so obvious. Here's the answer I gave.
select
name,
count(name) as name_count
from
users
group by
name
having
name_count > 1;
After getting home a quick test with my local copy of MySQL revealed my answer was indeed correct. As an added bonus you also get the number of times each value appears.

No comments: