1

I have table containing following entries

Id  |   Accno  |    Name   |    Hash
----+----------+-----------+---------
 1  |    11    |     ABC   |    01110
 2  |    11    |     ABC   |        
 3  |    22    |     PQT   |        
 4  |    33    |     XYZ   |    03330
 5  |    44    |     LMN   |    04440
 6  |    33    |     XYZ   |        

I need SQL query to remove duplicate entry from table and keep atleast single entry in table whose hash value is present. and for those entries which are not duplicate should also remain in table.

5
  • Please be more specific in what you want, provide us with example Commented Jun 28, 2014 at 5:33
  • 1
    Which columns should it be checking for duplicates? Accno, Name, or both together? Commented Jun 28, 2014 at 5:36
  • 1
    Write a SELECT query that returns all the rows you want to keep. Then use DELETE FROM YourTable WHERE id NOT IN (SELECT id FROM (<subquery>)), where <subquery> is the query you wrote. Commented Jun 28, 2014 at 5:38
  • Can you give expected output of given data so we can clarify what you want? Commented Jun 28, 2014 at 5:47
  • I want output as Id | Accno | Name | Hash ----+----------+-----------+--------- 1 | 11 | ABC | 01110 3 | 22 | PQT | 4 | 33 | XYZ | 03330 5 | 44 | LMN | 04440 Commented Jun 28, 2014 at 6:23

3 Answers 3

1

I think you guys overcomplicate things a lot. This should work just dandy:

DELETE FROM 
    YourTable
WHERE Hash IS NULL
AND Accno IN 
    (
    SELECT Accno
    FROM YourTable
    GROUP BY Accno
    HAVING COUNT(Name) > 1
    )
;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Dagg Nabbit for the suggested corrections.
0

Probably the easiest way to do it is to create a new table and copy non duplicate entries.

create table table_name2 as select distinct * from table_name1;
drop table table_name1;
rename table_name2 to table_name1;

Something like this.

2 Comments

This will copy all the rows, because the id column makes them all distinct. He also said he wants to keep the row with a non-empty Hash column.
I want to remove duplicate entries of accno and keep those entries for which hash is present and in case hash is not present for any unique entry keep that too in database
0
Create table temp2 as SELECT *
FROM temp where id in (select id from temp group by accno having count(accno)>=1 and hash<>'');    
drop table old_table;
rename table temp2 to old_table;

Check SQL Fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.