Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL: Selecting rows to delete via joins

Tags:

join

tsql

Scenario:

Let's say I have two tables, TableA and TableB. TableB's primary key is a single column (BId), and is a foreign key column in TableA.

In my situation, I want to remove all rows in TableA that are linked with specific rows in TableB: Can I do that through joins? Delete all rows that are pulled in from the joins?

DELETE FROM TableA  FROM    TableA a    INNER JOIN TableB b       ON b.BId = a.BId       AND [my filter condition] 

Or am I forced to do this:

DELETE FROM TableA WHERE    BId IN (SELECT BId FROM TableB WHERE [my filter condition]) 

The reason I ask is it seems to me that the first option would be much more effecient when dealing with larger tables.

Thanks!

like image 655
John Avatar asked Jan 13 '09 16:01

John


People also ask

Can we use joins in delete query?

It is totally possible to use JOIN and multiple tables in the DELETE statement.

Does join delete rows?

DELETE JOIN is an advanced structured query language(SQL) statement that is used to perform delete operations in multiple tables while using SQL JOIN such that all rows are deleted from the first table and the matching rows in another table or based on the kind of join operation used in the query.

How to delete a join table in SQL Server?

The basic syntax for Delete Join in SQL Server is as follows: The basic syntax for Delete Join in MySQL is as follows: DELETE t1.* The different parameters used in the syntax are: DELETE t1: It is used to delete the required table from the database. Here, you may choose from the first table’s instance t1 and the second table’s instance t2.

How to delete rows from one table based on another table?

Using the same concept of Inner join, we can delete rows from one table based on another table using Inner Join. DELETE T2 FROM Table2 as T2 INNER JOIN Table1 as T1 ON T1. Id = T1 .Id; To simplify syntax, T2 is an alias name for Table2, whose rows we want to delete based on matching rows with Table1.

What is delete in SQL Server?

It is basically a combination of DELETE and JOIN statements. In this article, we will be learning about four types of DELETE operations, namely, DELETE while using INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN.

What is delete T1 in SQL Server?

DELETE t1: It is used to delete the required table from the database. Here, you may choose from the first table’s instance t1 and the second table’s instance t2. FROM table_name1 as t1 JOIN table_name2 as t2: It is used to specify the source from which data has to be fetched and deleted.


1 Answers

DELETE TableA FROM   TableA a        INNER JOIN TableB b                ON b.Bid = a.Bid                   AND [my filter condition]  

should work

like image 71
TheTXI Avatar answered Oct 13 '22 16:10

TheTXI