3

I have a table in MySQL named ZipCode and its fields are: id, zipcode, city, state. It has some duplicate records; some zipcode are showing two times I want to remove all that zipcodes that are coming twice; each zipcode must be stored just once. How can I make it correct?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Sharma Mudeet
  • 41
  • 1
  • 4
  • possible duplicate of [Delete Duplicate SQL Records](http://stackoverflow.com/questions/841447/delete-duplicate-sql-records) – Bohemian Aug 21 '11 at 23:18

3 Answers3

7
-- remove duplicates

DELETE z1
FROM ZipCode z1, ZipCode z2
WHERE z1.zipcode = z2.zipcode AND z2.id < z1.id;

-- add a primary key

ALTER TABLE ZipCode ADD PRIMARY KEY (zipcode);

-- or a unique key

ALTER TABLE ZipCode ADD UNIQUE INDEX zipcode_unique (zipcode);
Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
4

This set of three queries will remove all duplicates:

CREATE TABLE new_table AS SELECT * FROM old_table WHERE 1 GROUP BY zip;
DROP TABLE old_table;
RENAME TABLE new_table TO old_table;
EdoDodo
  • 8,220
  • 3
  • 24
  • 30
0

Try this its working fine

DELETE
FROM
insurance_policy_customers ipc
WHERE
ipc.id NOT IN (SELECT
min(ipc.id)
FROM
insurance_policy_customers ipc
GROUP BY
ipc.resident_insurance_policy_id )
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195