views:

5148

answers:

6

What's the simplest SQL statement that will return the duplicate values for a given column and the count of their occurrences in an Oracle database table?

For example: I have a JOBS table with the column JOB_NUMBER - how can I find out if I have any duplicate JOB_NUMBERs, and how many times they're duplicated?

+15  A: 
select column_name, count(column_name)
from table
group by column_name
having count (column_name) > 1;
Bill the Lizard
Thanks - that's the answer I just found and you beat me to posting it back here! :o)
Andrew
You're welcome. Now I'm about to post my own question on the differences between count(column) and count(*). :)
Bill the Lizard
+5  A: 

Simplest I can think of:

select job_number, count(*)
from jobs
group by job_number
having count(*) > 1;
JosephStyons
+1  A: 

How about:

SELECT <column>, count(*)
FROM <table>
GROUP BY <column> HAVING COUNT(*) > 1;

To answer the example above, it would look like:

SELECT job_number, count(*)
FROM jobs
GROUP BY job_number HAVING COUNT(*) > 1;
Andrew
A: 

Doing

select count(j1.job_number), j1.job_number, j1.id, j2.id
from   jobs j1 join jobs j2 on (j1.job_numer = j2.job_number)
where  j1.id != j2.id
group by j1.job_number

will give you the duplicated rows' ids.

agnul
A: 

another way:

 select *
   from table a
  where exists (select 1 from table
                 where column_name=a.column_name
                   and rowid<a.rowid)

Works fine (quick enough) when there is index on column_name. And it's better way to delete or update dublicate rows.

Grrey
A: 

You don't need to even have the count in the returned columns if you don't need to know the actual number of duplicates. e.g.

SELECT column_name
FROM table
GROUP BY column_name
HAVING COUNT(*) > 1
Evan