Skip to Main Content
  • Questions
  • Updating a table when a match is found in another table

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, Rajendra.

Asked: March 11, 2019 - 6:04 am UTC

Last updated: March 11, 2019 - 2:28 pm UTC

Version: Oracle 11g

Viewed 1000+ times

You Asked

Hi Tom,

I have a table (T1) and a view is created upon T1 by masking few PI information say (V1)

T1

area_code integer (100 USA, 200 UK)
id integer
Name string
age integer
DOB date
type string (Individual/Company)

V1 (Masked version of T1)
area_code integer (100 USA, 200 UK)
id integer
Name string
age integer
DOB date
type string (Individual/Company)

Now i have a staging table (ST1) which has the id matching with that of T1 and type (Individual/Company). Based on the matching ids between ST1 and T1 i need to update the type in T1 table for all UK Employer/Employees

Below is the update statement i have written

update T1 set type = b.type 
from V1 a inner join ST1 b
on a.id = b.id
where a.area_code = 200 


When i ran the above query, the type is updated for the entire table T1 that too with a single value 'Individual'. Can you please explain what might have exactly happened.

Thanks
Raj




and Chris said...

An update-only merge is probably the way to go here:

create table t (
  c1 int primary key,
  c2 int 
);

create table t_stage (
  c1 int primary key,
  c2 int 
);

insert into t values ( 1, 0 );
insert into t_stage values ( 1, 9999 );

commit;

select * from t;

C1   C2   
   1    0 

merge into t
using t_stage ts
on    ( t.c1 = ts.c1 )
when matched then update
  set t.c2 = ts.c2;

select * from t;

C1   C2     
   1   9999 


Learn more about it in this video:


Rating

  (1 rating)

Is this answer out of date? If it is, please let us know via a Comment

Comments

A reader, March 11, 2019 - 10:54 am UTC

Hi Tom,

Thank you but just wanted to know what may have happened in my case where entire table got updated even though I have given a where condition.

Raj
Chris Saxon
March 11, 2019 - 2:28 pm UTC

It's Chris here, but hey!

Thank you but just wanted to know what may have happened in my case where entire table got updated even though I have given a where condition.

I dunno... the update you've posted is invalid SQL...

Please share a complete working example. This should include:

- create tables
- insert into
- update statement

More to Explore

SQL

The Oracle documentation contains a complete SQL reference.