Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle: how to UPSERT (update or insert into a table?)

The UPSERT operation either updates or inserts a row in a table, depending if the table already has a row that matches the data:

if table t has a row exists that has key X:     update t set mystuff... where mykey=X else     insert into t mystuff... 

Since Oracle doesn't have a specific UPSERT statement, what's the best way to do this?

like image 277
Mark Harrison Avatar asked Oct 26 '08 01:10

Mark Harrison


People also ask

How do you upsert in Oracle?

You use the INSERT statement to insert or update a single row in an existing table. The word UPSERT combines UPDATE and INSERT , describing it statement's function. Use an UPSERT statement to insert a row where it does not exist, or to update the row with new values when it does.

What is the difference between INSERT and upsert?

upsert stands for both update and insert. insert is a dml statement used to insert the records in to the object. upsert can be used when you are not aware of the records that are coming in to the insatance .. i.e whether the records are there to update or insert... then u can use the upsert dml statement.

Which command helps to INSERT or update the table based on condition?

The UPSERT operation either updates or inserts a row in a table, depending if the table already has a row that matches the data: if table t has a row exists that has key X: update t set mystuff...


1 Answers

The MERGE statement merges data between two tables. Using DUAL allows us to use this command. Note that this is not protected against concurrent access.

create or replace procedure ups(xa number) as begin     merge into mergetest m using dual on (a = xa)          when not matched then insert (a,b) values (xa,1)              when matched then update set b = b+1; end ups; / drop table mergetest; create table mergetest(a number, b number); call ups(10); call ups(10); call ups(20); select * from mergetest;  A                      B ---------------------- ---------------------- 10                     2 20                     1 
like image 121
Mark Harrison Avatar answered Sep 21 '22 00:09

Mark Harrison