Skip to Main Content
  • Questions
  • How to sync a column value across 2 tables.

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, Subhash.

Asked: August 12, 2019 - 6:58 am UTC

Last updated: August 12, 2019 - 10:24 am UTC

Version: 19c

Viewed 1000+ times

You Asked

Hi Tom,

I have 2 tables A and B. column "id" is common in both the tables.

create table A (id number primary key, type varchar2(20), desc1 varchar2(20));

create table B (id number primary key, type varchar2(20));

column "type" in both the tables can have values in (1,2,3).

Initially when table A is populated with all 3 columns values, only id from table A is inserted to table B(type column value is not updated in B).

Now when there is an update in type column of table A, we want updated value should be inserted to table B type column. Same way if there is an update in type column of table B, that value should be updated in table A for corresponding id.
Basically we want type column same in both the table for an id.

Could you please let me know the way to achieve this.

Thanks,
Subhash

and Chris said...

If the tables should have the same values... why not just have one table?

You can use merge to do update-if-exists, insert-if-not-exists logic. So after every insert or update on A, you could merge into B:

create table A (
  id number primary key, type varchar2(20), desc1 varchar2(20)
);

create table B (
  id number primary key, type varchar2(20)
);

insert into a values ( 1, 1, 'a' );

merge into b
using a
on    ( a.id = b.id )
when matched then
  update set b.type = a.type
when not matched then
  insert values ( a.id, a.type );
  
select * from b;

ID    TYPE   
    1 1  

update a
set    type = 2;

merge into b
using a
on    ( a.id = b.id )
when matched then
  update set b.type = a.type
when not matched then
  insert values ( a.id, a.type );

select * from b;

ID    TYPE   
    1 2   


You can then do the reverse to transfer changes on B back to A.

BUT!

This opens you up to all sorts of concurrency problems.

If in session one you run:

update a
set    type = 1;


And in session two:

update b 
set   type = 3;


Then run the appropriate merges after each, you'll hit deadlock!

So you need to think carefully about what to do when two people write conflicting changes at the same time.

Why do you need two tables again?

Rating

  (1 rating)

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

Comments

Subhash Kumar, August 12, 2019 - 10:45 am UTC

Thanks Chris for reply and suggestion.

I will look for having a single table to avoid issue you have mentioned.

More to Explore

SQL

The Oracle documentation contains a complete SQL reference.