Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete from where exists (select...) deleting all rows

Tags:

sql

I want to delete the rows of a table that are returned from a select statement.

Here is an simplified example of it not working.

declare @t1 table(a int, b int, c int)

insert into @t1(a,b,c) select 1, 10, 1
insert into @t1(a,b,c) select 1, 5, 2

select ta.a, ta.b, ta.c
        from @t1 ta
        join @t1 tb on ta.a = tb.a
        where ta.c < tb.c

delete from @t1
where exists (select ta.a, ta.b, ta.c
        from @t1 ta
        join @t1 tb on ta.a = tb.a
        where ta.c < tb.c)

select * from @t1

Here are the outputs, you can see the select only selects a single row but the delete deletes everything

results

like image 977
TagJones Avatar asked Oct 19 '25 04:10

TagJones


1 Answers

The problem is the fact that you're using EXISTS.

EXISTS only evaluates whether or not there is a result at all, and since your statement is returning records, you're essentially saying: DELETE @T1 WHERE (TRUE)

Try using this instead:

Delete  ta
From    @t1 ta
Join    @t1 tb  On  ta.a = tb.a
Where   ta.c < tb.c
like image 195
Siyual Avatar answered Oct 21 '25 17:10

Siyual



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!