Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to select all duplicates efficiently

Tags:

sql

postgresql

I want to select all rows that have a value that already exists in the table. I did not find a better solution than

select * 
from provisioning_requests tt 
where code in (select code 
               from provisioning_requests tt2 
               where tt2.id <> tt.id)

This seems a bit naive. Does anybody have a better solution?

like image 389
nathanvda Avatar asked Jun 28 '11 09:06

nathanvda


4 Answers

select * 
from provisioning_requests t1
 join (select code from provisioning_requests group by code having count(*)>1) t2
 ON t1.code = t2.code

OR

select * 
from provisioning_requests
 WHERE code in (select code from provisioning_requests group by code having count(*)>1)
like image 60
niktrs Avatar answered Nov 07 '22 05:11

niktrs


An Auto join do the job

select tt.* 
from provisioning_requests tt 
    INNER JOIN provisioning_requests tt2 
        ON tt.code = tt2.code
        AND tt2.id <> tt.id
like image 25
Cyril Gandon Avatar answered Nov 07 '22 04:11

Cyril Gandon


select t.*
from(
    select *, count(1) over(partition by code) as cnt
    from test
) as t
where t.cnt > 1
like image 44
Petar Ivanov Avatar answered Nov 07 '22 06:11

Petar Ivanov


You can use operator exists, it produces better performance:

select * 
from provisioning_requests tt 
where exists
(
    select 1
    from provisioning_requests tt2
    where tt2.id <> tt.id and tt2.code = tt.code
)
like image 2
Kirill Polishchuk Avatar answered Nov 07 '22 06:11

Kirill Polishchuk