Skip to Main Content
  • Questions
  • Insert trigger that do an update if record exists

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, Kåre.

Asked: April 12, 2019 - 7:43 am UTC

Last updated: April 15, 2019 - 5:05 am UTC

Version: 11G

Viewed 10K+ times! This question is

You Asked

I have a table:

create table test_tbl (id number, text varchar2(50));


with this data in it:

insert into test_tbl values (1,'Text 1');
insert into test_tbl values (2,'Text 2');


Now I want to insert a record, but if the ID is allready in the table, I want an update instead.

So if I do this insert

insert into test_tbl values (2,'Text 2 edited');


I want a trigger to do an UPDATE instead of an INSERT.

A trigger could be something like:


create trigger test_trg
before insert on test_tbl for each row
begin
  if exists (select * from test_tbl where id = :new.id) then
    -- update record
  else
    -- insert into table
  end if;
end;


But I can't figure out how to create this trigger.

and Connor said...

Don't use a trigger for that. It's way more trouble than it's worth. Search this site for "read consistency" and "mutating table" for examples how incredibly complex that can get.

Best resolution:

1) Add a constraint,

alter table test_tbl add primary key ( id )


2) Use MERGE to handle both the insert and update

merge into test_tbl t
using ( select [new values] from dual ) n
on ( t.id = n.id)
when matched then 
  update set t.col = n.col, etc
when not matched than
  insert (t.id,t.col, ... ) values (n.id,n.col, ... )





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

More to Explore

Design

New to good database design? Check out Chris Saxon's full fundamentals class.