1

How can I delete rows based on just two column conditions.

Example

Table 1 id name phone 1 aa 123 1 aa 345 1 bb 123 2 aa 456 1 NULL 123 1 123 

My Expected output

id name phone 1 bb 123 2 aa 456 

My condition to delete: if id and name is same, delete the rows If one of the value in a condition is null or blank it should also delete the row as given in the input.

3
  • 1
    Which row would you want to keep, the one with phone 123 or 345? Commented May 3, 2019 at 16:54
  • I want to delete both the rows if id and name are the same Commented May 3, 2019 at 16:55
  • Please post your table layouts, and what you have tried here stackoverflow.com/help/mcve Please revise your question to provide a bit more clarity as your comment "if id and name are the same" - they will never be the same in your example data since one is a number and the other a string value for example. Commented May 3, 2019 at 16:59

3 Answers 3

1
Delete from table1 t where exists ( Select * from (Select id, name from table1 group by id, name having count(*) > 1) t2 where t.id = t2.id and t.name = t2.name) 
Sign up to request clarification or add additional context in comments.

Comments

0

This should do what you want. You can do the select first for testing purposes, then remove the Select and uncomment out the delete.

-- This joins on the table the set of data that has more then 1 row with duplicate IDs, and names. Then you can delete from here. --DELETE t1 SELECT * FROM Table1 T1 INNER JOIN ( -- this gets all the records that have more then 1 ID and Name that are the same. SELECT ID, name FROM Table1 GROUP BY ID, name HAVING COUNT(*) > 1 ) ToDelete ON T1.ID = ToDelete.ID AND T1.name = ToDelete.name 

3 Comments

Sure, Let me try. Thanks
If the NAME is either blank or null with same ID. Will the query still capture it? @Brad
NULL is handled weird. Maybe change the spots where NAME is to ISNULL(name, '')
0
create table #tablea ( id int, name varchar(3), phone int ) insert into #tablea (id, name, phone) values (1,'aa','123'), (1,'aa','345'), (1,'bb','123'), (2,'aa','456') select * from #tablea delete a from #tablea a inner join ( select id, name from #tablea group by id, name having COUNT(*) > 1 ) b on a.id = b.id and a.name = b.name select * from #tablea drop table #tablea 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.