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 
|
Find duplicate rows in a table (no primary key)
21 comments. Current rating: (8 votes). Leave comments and/ or rate it.
Question:
I have a table of city names and need to find duplicate entries. The table does not have a primary key, so the duplicate rows are entirely identical.
Answer:
You can use the GROUP clause in your SELECT statement. Below are 3 different attempts. Try the first one first. It may not work with your DBMS but if it works, it's most convenient. The second one is an ok choice as it returns all rows but the duplicate rows in the 'See Also' box.
The last version returns all city names with a count value and you manually have to look for those with a value > 1. If you need to do this more often, you should consider creating a VIEW or a temporary table with this query and then do a SELECT on this VIEW/ temp table.
In Microsoft SQL-Server, you can use the HAVING clause, as shown at the bottom.
And: If you do have a primary key defined, see the other tip mentioned at the top. This would work in that situation, but using the unique ID is better.
 | |  | |
select city_name, count(city_name) as cnt
from areas
group by city_name
where cnt>1
select city_name, count(city_name) as cnt
from areas
group by city_name
order by cnt desc
select city_name, count(city_name) as cnt
from areas
group by city_name
select city_name
from areas
group by city_name
having count(*) > 1
| |  | |  |
Comments:
| You are on page 2 of 2, other pages: 1 [2] | |
|
|
|
Thanks guys, really helpful.
|
|
|
|
|
This would also work:
SELECT
city_name,
COUNT(city_name) AS NumOccurrences
FROM
areas
GROUP BY
city_name
HAVING ( COUNT(city_name) > 1 )
// By =IceBurn= //
|
|
|
|
|
Vary Good Support and Help
|
|
|
|
|
Add a sequential primary key by using the ALTER TABLE statement
To add a column to an existing table, the ALTER TABLE syntax is:
ALTER TABLE table_name
ADD column_name column-definition;
For example:
ALTER TABLE supplier
ADD supplier_name varchar2(50);
This will add a column called supplier_name to the supplier table.
|
|
|
|
|
|
|
|
|
|
Very Useful.
Thanks.
|
| You are on page 2 of 2, other pages: 1 [2] |
|