Oracle Database Merge with sample data


Example

drop table table01;
drop table table02;

create table table01 (
       code int,
       name varchar(50),
       old int
);

create table table02 (
       code int,
       name varchar(50),
       old int
);

truncate table table01;
insert into table01 values (1, 'A', 10);
insert into table01 values (9, 'B', 12);
insert into table01 values (3, 'C', 14);
insert into table01 values (4, 'D', 16);
insert into table01 values (5, 'E', 18);

truncate table table02;
insert into table02 values (1, 'AA', null);
insert into table02 values (2, 'BB', 123);
insert into table02 values (3, 'CC', null);
insert into table02 values (4, 'DD', null);
insert into table02 values (5, 'EE', null);

select * from table01 a order by 2;
select * from table02 a order by 2;

--

merge into table02 a using (
      select b.code, b.old from table01 b
) c on (
  a.code = c.code
)
when matched then update set a.old = c.old
;

--

select a.*, b.* from table01 a 
inner join table02 b on a.code = b.codetable01;

select * from table01 a
where 
       exists 
       (
         select 'x' from table02 b where a.code = b.codetable01
       );
       
select * from table01 a where a.code in (select b.codetable01 from table02 b);

--

select * from table01 a
where 
       not exists 
       (
         select 'x' from table02 b where a.code = b.codetable01
       );
       
select * from table01 a where a.code not in (select b.codetable01 from table02 b);