I have two tables with the same number of columns with no primary keys (I know, this is not my fault). Now I need to delete all rows from table A that exists in table B (they are equal, each one with 30 columns).
The most immediate way I thought is to do a INNER JOIN
and solve my problem. But, write conditions for all columns (worrying about NULL
) is not elegant (maybe cause my tables are not elegant either).
I want to use INTERSECT
. I am not knowing how to do it? This is my first question:
I tried (SQL Fiddle):
declare @A table (value int, username varchar(20))
declare @B table (value int, username varchar(20))
insert into @A values (1, 'User 1'), (2, 'User 2'), (3, 'User 3'), (4, 'User 4')
insert into @B values (2, 'User 2'), (4, 'User 4'), (5, 'User 5')
DELETE @A
FROM (SELECT * FROM @A INTERSECT SELECT * from @B) A
But all rows were deleted from table @A
.
This drived me to second question: why the command DELETE @A FROM @B
deletes all rows from table @A
?
A DELETE statement can include JOIN operations. It can contain zero, one, or multiple JOIN operations. The DELETE removes records that satisfy the JOIN conditions.
You can use the WHERE clause with a DELETE query to delete the selected rows, otherwise all the records would be deleted.
With INTERSECT, you can create a 3D solid from the common volume of two or more existing 3D solids, surfaces, or regions. If you select a mesh, you can convert it to a solid or surface before completing the operation. You can extrude 2D profiles and then intersect them to create a complex model efficiently.
SQL INTERSECT operator combines two select statements and returns only the dataset that is common in both the statements. To put it simply, it acts as a mathematical intersection. In mathematics, the intersection of A and B is the common data present in both A and B.
Try this:
DELETE a
FROM @A a
WHERE EXISTS (SELECT a.* INTERSECT SELECT * FROM @B)
Delete from @A where, for each record in @A, there is a match where the record in @A intersects with a record in @B.
This is based on Paul White's blog post using INTERSECT for inequality checking.
SQL Fiddle
To answer your first question you can delete based on join
:
delete a
from @a a
join @b b on a.value = b.value and a.username = b.username
The second case is really strange. I remember similar case here and many complaints about this behaviour. I will try to fing that question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With