Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete with "Join" in Oracle sql Query

I am not deeply acquainted with Oracle Sql Queries, therefore I face a problem on deleting some rows from a table which must fulfill a constraint which includes fields of another (joining) table. In other words I want to write a query to delete rows including JOIN.

In my case I have a table ProductFilters and another table Products joined on fields ProductFilters.productID = Products.ID. I want to delete the rows from ProductFilters having an ID higher or equal to 200 and the product they refer has the name 'Mark' (name is a field in Product).

I would like to be informed initially if JOIN is acceptable in a Delete Query in Oracle. If not how should I modify this Query in order to make it work, since on that form I receive an error:

DELETE From PRODUCTFILTERS pf  where pf.id>=200  And pf.rowid in  (      Select rowid from PRODUCTFILTERS       inner join PRODUCTS on PRODUCTFILTERS.PRODUCTID = PRODUCTS.ID       And PRODUCTS.NAME= 'Mark' );        
like image 943
arjacsoh Avatar asked Oct 01 '12 11:10

arjacsoh


People also ask

Can we use join IN DELETE query?

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

How do you DELETE data from two tables using join in Oracle?

You can specify multiple tables in a DELETE statement to delete rows from one or more tables depending on the condition in the WHERE clause. You cannot use ORDER BY or LIMIT in a multiple-table DELETE . The table_references clause lists the tables involved in the join, as described in Section 13.2. 9.2, “JOIN Clause”.

How do you DELETE using LEFT join?

Delete left join table is used to delete rows from the left table that do not have matching records in the right table. Below is the syntax to of deleting rows with a left join that does not have matching rows in another table: Delete table1 from table1 LEFT JOIN table2 ON table1. col_name=table2.


2 Answers

Recently I learned of the following syntax:

DELETE (SELECT *         FROM productfilters pf         INNER JOIN product pr             ON pf.productid = pr.id         WHERE pf.id >= 200             AND pr.NAME = 'MARK') 

I think it looks much cleaner then other proposed code.

like image 133
xlogic Avatar answered Sep 17 '22 18:09

xlogic


Based on the answer I linked to in my comment above, this should work:

delete from ( select pf.* From PRODUCTFILTERS pf  where pf.id>=200  And pf.rowid in    (      Select rowid from PRODUCTFILTERS       inner join PRODUCTS on PRODUCTFILTERS.PRODUCTID = PRODUCTS.ID       And PRODUCTS.NAME= 'Mark'   ) );  

or

delete from PRODUCTFILTERS where rowid in ( select pf.rowid From PRODUCTFILTERS pf  where pf.id>=200  And pf.rowid in    (      Select PRODUCTFILTERS.rowid from PRODUCTFILTERS       inner join PRODUCTS on PRODUCTFILTERS.PRODUCTID = PRODUCTS.ID       And PRODUCTS.NAME= 'Mark'   ) );  
like image 32
davek Avatar answered Sep 21 '22 18:09

davek