Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update with inner join in Oracle

Tags:

sql

oracle

Could someone please verify whether inner join is valid with UPDATE statment in PL SQL? e.g.

Update table t
set t.value='value'
from tableb b inner join
on t.id=b.id
inner join tablec c on
c.id=b.id
inner join tabled d on
d.id=c.id
where d.key=1
like image 281
Nil Pun Avatar asked Feb 23 '12 10:02

Nil Pun


People also ask

Can we use inner join in UPDATE statement in Oracle?

The answer is pretty straightforward: in Oracle this syntax of UPDATE statement with a JOIN is not supported.

Can we UPDATE with inner join?

SQL UPDATE JOIN could be used to update one table using another table and join condition. UPDATE tablename INNER JOIN tablename ON tablename. columnname = tablename.

Can you UPDATE a joined table?

To UPDATE a table by joining multiple tables in SQL, let's create the two tables 'order' and 'order_detail. ' We can update the data of a table using conditions of other joined tables. It is possible to join two or more tables in an UPDATE query.

How inner join works internally in Oracle?

It compares each row of table T1 with rows of table T2 to find all pairs of rows that satisfy the join predicate. Whenever the join predicate is satisfied by matching non-NULL values, column values for each matching pair of rows of T1 and T2 tables are combined into a row in the result set.


2 Answers

This synthax won't work in Oracle SQL.

In Oracle you can update a join if the tables are "key-preserved", ie:

UPDATE (SELECT a.val_a, b.val_b
          FROM table a
          JOIN table b ON a.b_pk = b.b_pk)
   SET val_a = val_b

Assuming that b_pk is the primary key of b, here the join is updateable because for each row of A there is at most one row from B, therefore the update is deterministic.

In your case since the updated value doesn't depend upon another table you could use a simple update with an EXIST condition, something like this:

UPDATE mytable t
   SET t.VALUE = 'value'
 WHERE EXISTS 
       (SELECT NULL
          FROM tableb b
         INNER JOIN tablec c ON c.id = b.id
         INNER JOIN tabled d ON d.id = c.id
         WHERE t.id = b.id
           AND d.key = 1)
like image 86
Vincent Malgrat Avatar answered Sep 22 '22 07:09

Vincent Malgrat


update t T  
set T.value = 'value'
where T.id in (select id from t T2, b B, c C, d D
               where T2.id=B.id and B.id=C.id and C.id=D.id and D.key=1)

-- t is the table name, T is the variable used to reffer to this table
like image 24
L Petre Avatar answered Sep 23 '22 07:09

L Petre