Delphi .NET (2) Database (71) Delphi IDE (89) Network (39) Printing (3) Strings (12) VCL (83) Windows with Delphi (280)
Exchange Links About this site Links to us 
New related comments Number of comments in the last 48 hoursAccess a password-saved paradox database without knowing the password 1 new comments
|
SQL: Find duplicate rows in a table (with a primary key)
25 comments. Current rating: (12 votes). Leave comments and/ or rate it.
Question:
I have a table of city names and need to find duplicate entries. The table does have a primary key called CITY_ID, so the duplicates will have different CITY_ID values but identical CITY_NAME values.
Answer:
If you indeed have a primary key then you need two cursor instances (c1, c2) as the following example shows. The query requires that ID #1 is smaller than ID #2 otherwise all pairs would be returned twice (2,3) and (3,2) or, if you don't even require that c1 <> c2, .. well, try that out for yourself. 
If you do not have a primary key defined, see the other tip mentioned in the 'See Also' box.
Note:
In Microsoft SQL-Server, you can use the HAVING clause, as shown at the bottom.
 | |  | |
select c1.city_id, c2.city_id, c1.city_name
from cities c1, cities c2
where c1.city_id < c2.city_id and c1.city_name = c2.city_name
select city_name
from areas
group by city_name
having count(*) > 1
| |  | |  |
Comments:
| You are on page 1 of 2, other pages: [1] 2 | |
Dog_Cheez from United States
|
 |
|
|
I forgot to say before that the above example also works great with MySQL.
|
|
anonymous from Australia
|
 |
|
|
Fantastic, made my job much easier
no if only Books online had these type of helpful hints...
|
|
[hidden] from Tallahassee, United States
|
 |
|
|
Excellent! I just now needed to know this for my project and the answer was clear and quick. God bless you all!
|
|
anonymous from Hong Kong
|
|
|
|
Thank you, I love this site, fast n easy steps XD
|
|
anonymous from United Kingdom
|
 |
|
|
As we say in Great Britain - 'Does what it says on the tin'. Thanks !!
|
|
JRyan from Oxford, United Kingdom
|
 |
|
|
There's a 100 ways to solve a problem. Here's another alternative:-
select q1.CITY_NAME
from CITIES q1
where 1 < (select count(*)
from CITIES q2
where q1.CITY_NAME = q2.CITY_NAME)
|
|
anonymous from Zimbabwe
|
|
|
|
IT IS WORKING BUT HOW DO DO IF WE ARE LINKING 3 TABLES
|
|
anonymous from Bombay, India
|
 |
|
|
Fantastic, made my job much easier ;God bless you all!
|
2008-04-29, 03:36:08 (updated: 2008-04-29, 03:41:31) |
anonymous from India
|
|
|
|
how to retrieve the primary key id if there is more than one columns in a duplicate result query.actually i retrieve the other columns that are duplicate but now i want to retrieve the ids for that rows.pls help me
|
|
anonymous from Canada
|
|
|
|
Godlike! Thank you.
|
| You are on page 1 of 2, other pages: [1] 2 |
|