How to remove partial duplicates from a mysql table? - mysql

I have a mysql table. How do I remove partial duplicates based on three columns? Is it posibble to apply the changes to the current table? If not what is the solution?
Example:
The current table
Surname.........First Name.......Company Name........Responsibilities.......Column5
McKain...............Christine.........XYZ...............................A................................A
McKain.......... ....Christine .........XYZ .............................B............................... B
Morrell............... Sally ..............ABC ..............................A ...............................A
Motu ..................Timothy........... EFG .............................I ................................I
The resulting Table:
Surname.........First Name.......Company Name........Responsibilities.......Column5
McKain...............Christine.........XYZ...............................A................................A
Morrell............... Sally ..............ABC ..............................A ...............................A
Motu ..................Timothy........... EFG .............................I ................................I
and if possible someone please tell me an easy way to add a table here in stack overflow..

Replace tableName with your table's name and the GROUP BY/UNIQUE INDEX fields with the fields you want to be unique.
Warning: The GROUP BY used will only select the first entry when removing duplicates.
If something goes wrong, you still have a copy of your original data in tableName_old.
-- Create a new table that's filtered
CREATE TABLE newTable
(SELECT *
FROM tableName
GROUP BY LastName, FirstName, Company);
-- Add a unique index of the fields you want
ALTER TABLE newTable ADD UNIQUE INDEX ix_unique (LastName, FirstName, Company);
-- Rename the tables around
RENAME TABLE tableName TO tableName_old;
RENAME TABLE newTable TO tableName;

Related

how to combine three columns and remove duplicates in sql

I have table with 7 columns where I want to combine three column and want to remove duplicates. Your help will be appreciated.
I'm guessing you want to update the table SERIAL_NUMBERS with just a single row of combined warranty_indicator, account, date_sold data. If that's true then I will suggest the following.
Duplicate SERIAL_NUMBERS table:
CREATE TABLE SERIAL_NUMBERS_NEW LIKE SERIAL_NUMBERS;
Add unique constraint - combination of warranty_indicator, account, date_sold:
ALTER TABLE SERIAL_NUMBERS_NEW
ADD CONSTRAINT Index1 UNIQUE (warranty_indicator,account,date_sold);
Insert data from SERIAL_NUMBERS table to SERIAL_NUMBERS_NEW using INSERT IGNORE ; to ignore duplicates:
INSERT IGNORE INTO SERIAL_NUMBERS_NEW
SELECT * FROM SERIAL_NUMBERS;
Rename old and new table:
RENAME TABLE SERIAL_NUMBERS TO SERIAL_NUMBERS_OLD;
RENAME TABLE SERIAL_NUMBERS_NEW TO SERIAL_NUMBERS;
Check data:
SELECT * FROM SERIAL_NUMBERS_OLD;
SELECT * FROM SERIAL_NUMBERS;
Keep in mind that any future data inserted will treat duplicates according to the unique constraint. Therefore, if you have program running the INSERT syntax, make sure you update it to INSERT IGNORE.
Demo fiddle

Create another table TRANS_TEMP from TRANSACTION table by change the column name acc_no to account_no

table name = TRANSACTION, i want to create another table trans_temp from transaction table but rename column acc_no to account_no. this all operation made in one query, Thank you...
You could use the CREATE ... AS SELECT syntax:
CREATE TABLE trans_temp AS
SELECT
acc_no AS account_no,
tr_date,
amt,
type_of_tr,
mode_of_pay
FROM transaction
The name of the columns returned by the query will become column names in the new table.
Note that the CTAS syntax does not take care of transferring constraints or indexes on the target table. You would need to recreate them manually aferwards.
There is another method if you don't want to list out all the columns:
create table trans_temp as
select *
from transaction;
alter table trans_temp modify acc_no account_no <type goes here>;
Perhaps you don't need a temporary table at all, and a view would suffice.

Delet just one record of duplicate

i am trying to delete e-mail duplicates from table nlt_user
this query is showing correctly records having duplicates:
select [e-mail], count([e-mail])
from nlt_user
group by [e-mail]
having count([e-mail]) > 1
now how can i delete all records having duplicate but one?
Thank you
If MySQL version is prior 5.7.4 you can add a UNIQUE index on the column e-mail with the IGNORE keyword.
This will remove all the duplicate e-mail rows:
ALTER IGNORE TABLE nlt_user
ADD UNIQUE INDEX idx_e-mail (e-mail);
If > 5.7.4 you can use a temporary table (IGNORE not possible on ALTER anymore):
CREATE TABLE nlt_user_new LIKE nlt_user;
ALTER TABLE nlt_user_new ADD UNIQUE INDEX (emailaddress);
INSERT IGNORE INTO nlt_user_new SELECT * FROM nlt_user;
DROP TABLE nlt_user;
RENAME TABLE nlt_user_new TO nlt_user;
Try this :
delete n1 from nlt_user n1
inner join nlt_user n2 on n1.e-mail=n2.e-mail and n1.id>n2.id;
This will keep record with minimum ID value of duplicates and deletes remaining duplicate records
The rank function can be employed to retain only the unique values
1:Create a new table which contains only unique values
Example: nlt_user_unique
CREATE TABLE nlt_user_unique AS
(SELECT * FROM
(SELECT A.*,RANK() OVER (PARTITION BY email ORDER BY email) RNK
FROM nlt_user A)
where RNK=1)
2:Truncate the orignal table containing duplicates
truncate table nlt_user
3:Insert the unique rows from the table created in step 1 to your table nlt_user
INSERT INTO nlt_user()
SELECT email from nlt_user_unique;

How do I delete all the duplicate records in a MySQL table without temp tables

I've seen a number of variations on this but nothing quite matches what I'm trying to accomplish.
I have a table, TableA, which contain the answers given by users to configurable questionnaires. The columns are member_id, quiz_num, question_num, answer_num.
Somehow a few members got their answers submitted twice. So I need to remove the duplicated records, but make sure that one row is left behind.
There is no primary column so there could be two or three rows all with the exact same data.
Is there a query to remove all the duplicates?
Add Unique Index on your table:
ALTER IGNORE TABLE `TableA`
ADD UNIQUE INDEX (`member_id`, `quiz_num`, `question_num`, `answer_num`);
Another way to do this would be:
Add primary key in your table then you can easily remove duplicates from your table using the following query:
DELETE FROM member
WHERE id IN (SELECT *
FROM (SELECT id FROM member
GROUP BY member_id, quiz_num, question_num, answer_num HAVING (COUNT(*) > 1)
) AS A
);
Instead of drop table TableA, you could delete all registers (delete from TableA;) and then populate original table with registers coming from TableA_Verify (insert into TAbleA select * from TAbleA_Verify). In this way you won't lost all references to original table (indexes,... )
CREATE TABLE TableA_Verify AS SELECT DISTINCT * FROM TableA;
DELETE FROM TableA;
INSERT INTO TableA SELECT * FROM TAbleA_Verify;
DROP TABLE TableA_Verify;
This doesn't use TEMP Tables, but real tables instead. If the problem is just about temp tables and not about table creation or dropping tables, this will work:
SELECT DISTINCT * INTO TableA_Verify FROM TableA;
DROP TABLE TableA;
RENAME TABLE TableA_Verify TO TableA;
Thanks to jveirasv for the answer above.
If you need to remove duplicates of a specific sets of column, you can use this (if you have a timestamp in the table that vary for example)
CREATE TABLE TableA_Verify AS SELECT * FROM TableA WHERE 1 GROUP BY [COLUMN TO remove duplicates BY];
DELETE FROM TableA;
INSERT INTO TableA SELECT * FROM TAbleA_Verify;
DROP TABLE TableA_Verify;
Add Unique Index on your table:
ALTER IGNORE TABLE TableA
ADD UNIQUE INDEX (member_id, quiz_num, question_num, answer_num);
is work very well
If you are not using any primary key, then execute following queries at one single stroke. By replacing values:
# table_name - Your Table Name
# column_name_of_duplicates - Name of column where duplicate entries are found
create table table_name_temp like table_name;
insert into table_name_temp select distinct(column_name_of_duplicates),value,type from table_name group by column_name_of_duplicates;
delete from table_name;
insert into table_name select * from table_name_temp;
drop table table_name_temp
create temporary table and store distinct(non duplicate) values
make empty original table
insert values to original table from temp table
delete temp table
It is always advisable to take backup of database before you play with it.
As noted in the comments, the query in Saharsh Shah's answer must be run multiple times if items are duplicated more than once.
Here's a solution that doesn't delete any data, and keeps the data in the original table the entire time, allowing for duplicates to be deleted while keeping the table 'live':
alter table tableA add column duplicate tinyint(1) not null default '0';
update tableA set
duplicate=if(#member_id=member_id
and #quiz_num=quiz_num
and #question_num=question_num
and #answer_num=answer_num,1,0),
member_id=(#member_id:=member_id),
quiz_num=(#quiz_num:=quiz_num),
question_num=(#question_num:=question_num),
answer_num=(#answer_num:=answer_num)
order by member_id, quiz_num, question_num, answer_num;
delete from tableA where duplicate=1;
alter table tableA drop column duplicate;
This basically checks to see if the current row is the same as the last row, and if it is, marks it as duplicate (the order statement ensures that duplicates will show up next to each other). Then you delete the duplicate records. I remove the duplicate column at the end to bring it back to its original state.
It looks like alter table ignore also might go away soon: http://dev.mysql.com/worklog/task/?id=7395
An alternative way would be to create a new temporary table with same structure.
CREATE TABLE temp_table AS SELECT * FROM original_table LIMIT 0
Then create the primary key in the table.
ALTER TABLE temp_table ADD PRIMARY KEY (primary-key-field)
Finally copy all records from the original table while ignoring the duplicate records.
INSERT IGNORE INTO temp_table AS SELECT * FROM original_table
Now you can delete the original table and rename the new table.
DROP TABLE original_table
RENAME TABLE temp_table TO original_table
Tested in mysql 5.Dont know about other versions.
If you want to keep the row with the lowest id value:
DELETE n1 FROM 'yourTableName' n1, 'yourTableName' n2 WHERE n1.id > n2.id AND n1.member_id = n2.member_id and n1.answer_num =n2.answer_num
If you want to keep the row with the highest id value:
DELETE n1 FROM 'yourTableName' n1, 'yourTableName' n2 WHERE n1.id < n2.id AND n1.member_id = n2.member_id and n1.answer_num =n2.answer_num

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.