Deleting duplicate rows from a table - mysql

I have a table in my database which has duplicate records that I want to delete. I don't want to create a new table with distinct entries for this. What I want is to delete duplicate entries from the existing table without the creation of any new table. Is there any way to do this?
id action
L1_name L1_data
L2_name L2_data
L3_name L3_data
L4_name L4_data
L5_name L5_data
L6_name L6_data
L7_name L7_data
L8_name L8_data
L9_name L9_data
L10_name L10_data
L11_name L11_data
L12_name L12_data
L13_name L13_data
L14_name L14_data
L15_name L15_data
see these all are my fields :
id is unique for every row.
L11_data is unique for respective action field.
L11_data is having company names while action is having name of the industries.
So in my data I'm having duplicate name of the companies in L11_data for their respective industries.
What I want is to have is unique name and other data of the companies in the particular industry stored in action. I hope I have stated my problem in a way that you people can understand it.

Yes, assuming you have a unique ID field, you can delete all records that are the same except for the ID, but don't have "the minimum ID" for their group of values.
Example query:
DELETE FROM Table
WHERE ID NOT IN
(
SELECT MIN(ID)
FROM Table
GROUP BY Field1, Field2, Field3, ...
)
Notes:
I freely chose "Table" and "ID" as representative names
The list of fields ("Field1, Field2, ...") should include all fields except for the ID
This may be a slow query depending on the number of fields and rows, however I expect it would be okay compared to alternatives
EDIT: In case you don't have a unique index, my recommendation is to simply add an auto-incremental unique index. Mainly because it's good design, but also because it will allow you to run the query above.

ALTER IGNORE TABLE 'table' ADD UNIQUE INDEX(your cols);
Duplicates get NULL, then you can delete them

DELETE
FROM table_x a
WHERE rowid < ANY (
SELECT rowid
FROM table_x b
WHERE a.someField = b.someField
AND a.someOtherField = b.someOtherField
)
WHERE (
a.someField,
a.someOtherField
) IN (
SELECT c.someField,
c.someOtherField
FROM table_x c
GROUP BY c.someField,
c.someOtherField
HAVING count(*) > 1
)
In above query the combination of someField and someOtherField must identify the duplicates distinctively.

Related

delete row/entry based on duplicate column value

I have a table called prospective_shop and one of the column name is 'username'. Username is not set as a primary key, but I wanted to remove all rows that have duplicate username. How can I do this the fastest way?
I tried doing the following:
ALTER IGNORE TABLE `prospective_shop` ADD UNIQUE INDEX idx_name (username);
but then it gives me:
Duplicate entry 'calista_shopp' for key 'idx_name'
delete from prospective_shop
where id not in
(
select * from
(
select min(id)
from prospective_shop
group by username
) x
)
You can just delete all records that are not the first ones for every unique username. By selecting min(id)` for every username group you make sure not to delete those but all the rest.
In MySQL you can't delete from a table you are selecting from at the same time. You can trick the engine by using another subselect as I did. The x is just an alias name for the temp table.

MySQL: delete duplicates rows where possible

I entered a query that introduced some duplicates into my database. The table is straight forward.
It has an id (int) column and a phrase column which is varchar(255). In order to find duplicates, my query looks like the following:
SELECT phrase from foo GROUP BY phrase HAVING (count(phrase) > 1)
My question is, how do I delete the duplicate entries without manually having to do it? I want to use the query above to generate the list of entries that need to be deleted at least once. This way only one version of 'phrase' exists in table foo.
This would keep one row (the one with the lowest ID) per phrase.
DELETE FROM foo
WHERE id NOT IN (
SELECT id FROM (
SELECT MIN(id) id
FROM foo
GROUP BY phrase
) _
);
As dan pointed out in comments, with MySQL you need that weird inner query.
You should use:
SELECT max(id) from foo GROUP BY phrase HAVING (count(phrase) > 1)
To establish what the ids that need to be deleted.
To delete the entries you can do something like:
delete from foo where id in (select id from (SELECT max(id) from foo GROUP BY phrase HAVING (count(phrase) > 1)) foo);
You will be able to execute the delete statement multiple times, to delete duplicates that are more then one.
You need to create a temporary table, add unique values, add just one of the duplicated values, and then rename your temporary table to your original one.
create table tmp like foo;
alter table tmp add unique (phrase);
insert into tmp select * from foo
on duplicate key update phrase=ifnull(phrase, values(phrase));
rename table foo to deleteme, tmp to foo;
drop table deleteme;
You can do a JOIN and decide if you want to delete the first (min) or last (max) duplicate.
DELETE phrase FROM phrase JOIN
(SELECT max(id),COUNT(id) cnt from foo GROUP BY phrase
HAVING cnt>1) AS dups
ON phrase.id=dups.id
You need to run it multiple times if you have more that more than 1 duplicate of each record.

Duplicate Entries in DB

I have a huge table of products but there are lot of duplicate entries. The table has more than10 Thousand entries and I want to remove the duplicate entries in it without manually finding and deleting it. Please let me know if you can provide me a solution for this
You could use SELECT DISTINCT INTO TempTable, drop the original table, and then rename the temp one.
You should also add primary and unique keys to avoid this sort of thing in the future.
for full row duplicates try this.
select distinct * into mytable_tmp from mytable
drop table mytable
alter table mytable_tmp rename mytable
Seems the below statements will help you in resolving your requirements.
if the table(foo) has primary key field
First step
store key values in temporary table, give your unique conditions in group by clause
if you want to delete the duplicate email id, give email id in group by clause and give the primary key name in
select clause like either min(primarykey) or max(primarykey)
CREATE TEMPORARY TABLE temptable AS SELECT min( primarykey ) FROM foo GROUP BY uniquefields;
Second step
call the below delete statement and give the table name and primarykey columns
DELETE FROM foo WHERE primarykey NOT IN (SELECT * FROM temptable );
execute both the query combined in your query analyser or db tool.
If the table(foo) doesn't have a primary key filed
step 1
CREATE TABLE temp_table AS SELECT * FROM foo GROUP BY field or fileds;
step 2
DELETE FROM foo;
step 3
INSERT INTO foo select * from temp_table;
There are different solutions to remove duplicate rows and it fully depends upon your scenario to make use of one from them. The simplest method is to alter the table making the Unique Index on Product Name field:
alter ignore table products add unique index `unique_index` (product_name);
You can remove the index after getting all the duplicate rows deleted:
alter table products drop index `unique_index`;
Please let me know if this resolves the issue. If not I can give you alternate solutions for that.
You can add more than one column to a group by. I.E.
SELECT * from tableName GROUP BY prod_name HAVING count(prod_name) > 1
That will show the unique products. You can write it dump it to new table and drop the existing one.

Removing duplicate rows from a MySql table

Similar questions were indeed asked, but I didn't find an answer.
I have a MySql table with 3 non-unique fields. I don't want duplicate rows. Meaning ("a", "b", "c") and ("a", "dasd", "dfsd") are okay (I don't mind having "a" twice in the first fields), but having ("a", "b", "c") twice is wrong.
I need a query which will remove duplicates, leaving only one row for each row group.
Edit This has already been covered on SO before.
One approach would be to create a new table based on the existing table. You could do this through something like:
create table myNewTable SELECT distinct * FROM myOldTable;
Then you could clear the old table's data, and create a unique constraint on the fields you don't want duplicated:
TRUNCATE TABLE myOldTable;
ALTER TABLE myOldTable
ADD UNIQUE (field1, field2);
Then insert your data back into the original table. Because you created myNewTable using DISTINCT, you should not have any duplicates.
INSERT INTO myOldTable SELECT * FROM myNewTable;
Note: It assumes we have primary key apart from column1 and column2 and column3. Also it assumes that last row should be preserved. Helpful when we have some other information also apart from column1,column2 and column3.
It saves the last primary key and delete the rest for unique values of Column1,Column2,Column3
Insert result of below query into a temp table
SELECT MAX(PrimaryKey)
FROM TABLENAME
GROUP BY Column1,Column2,Column3
Delete from TABLENAME where PrimaryKey NOT IN (SELECT PrimaryKey FROM TEMPTABLE)
If we have only these 3 columns, then
Save distinct in temp table
truncate original table
insert back into original from temp table.
You can retrieve a list of the duplicates like this:
SELECT field1, field2, field3, count(*) AS cnt
FROM yourtable
GROUP by field1, field2, field3
HAVING (cnt > 1)
You'll then have to delete the duplicate rows in subsequent seperate queries.
I will solve the problem by using a temporary table and subqueries to find the elements to erase. That will only work if your table 'yourTable' with the fields f1,f2,f3 has also an ID field that is unique.
Create the temporary table to store the IDs of the elements to erase.
CREATE TEMPORARY TABLE ids (ID int);
Find the IDs of the elements to erase:
INSERT INTO ids(ID) SELECT ID FROM yourTable AS t
WHERE 1 != (SELECT COUNT(*) FROM yourTable
WHERE yourTable.ID <= t.ID
AND yourTable.f1 = t.f1
AND yourTable.f2 = t.f2
AND yourTable.f3 = t.f3);
Delete the elements of the table with the previously selected indexes
DELETE yourTable FROM yourTable,ids WHERE yourTable.ID = ids.ID;
Remove the temporary table
DROP TABLE ids;
If SQL supported to to subqueries using the same table for a SELECT and a DELETE we could do all that in the same query, but this is not the case, so we need to go through a temporary table.
To avoir duplicates to happen I will set the three fields as primary keys of the table, in this way:
ALTER TABLE yourTable ADD PRIMARY KEY (f1, f2, f3);
You will be able to alter your table this way, only when you removed all the duplicates and once the table altered subsequent inserts with duplicated values will fail.

How to delete multiple entries in mysql

I have db with multiple entries.
I Google out something like this
SELECT COUNT(*), item_id, text, number FROM ads
GROUP BY item_id, text, number
HAVING COUNT(*)>1;
this select (I think) all my multiple entries, I use SQLyog, ... and there is no option to press button and delete all results of this query.
but even if I select all one by one and delete, I would also delete original one, right?
I basically want to keep all unique entries and keep one of multiple items.
simple example
('1' 'Novi Sad' '123');
('1' 'Novi Sad' '123');
('3' 'Beograd' '124');
I want to keep
('1' 'Novi Sad' '123');
('3' 'Beograd' '124');
I know only basic mysql.
When you do delete entries make sure to reset your ID increment
ALTER TABLE 'table_name' AUTO_INCREMENT = 1
Can you just copy, drop and delete?
CREATE TABLE Copy_Temp as
SELECT item_id, text, number
FROM ads
GROUP BY item_id, text, number;
DROP Table ads;
RENAME TABLE Copy_Temp TO ads;
Select all unique records into a temp table.
Delete all records from original table.
Insert all records from your temp table into original table.
DELETE emp FROM employee emp, employee emp2
WHERE emp.id > emp2.id
AND emp.name = emp2.name
For example, you having the table employee in which there are duplicate records (having the same name multiple times) then this query will delete all the duplicate records.