Home > database >  Insert if not exist and update certain values if it does
Insert if not exist and update certain values if it does

Time:11-24

I'm using JDBI3 (and would like to use @SQLUpdate) and an Oracle DB.

I want to insert an item with 4 columns into the table if it does not exist, if it does exist I want to instead update 3 of the 4 values of the item. If it wasn't Oracle I would've used some ON DUPLICATE_KEY logic but that does not exist in Oracle. I read some things about using Merge but the Queries seemed really wonky for what I was trying to do. Any tips on what to look for?

Additional question: If it is Merge I should use (with some form of sub queries I assume), how does the query affect performance? I think this database is quite write heavy.

MERGE INTO device db USING (SELECT 'abc' AS col1, 'bcd' as col2, 'cde' as col3, 'def' as col4 FROM DUAL) input
on (db.col1 = input.col1 AND db.col2= input.col2)
WHEN MATCHED THEN UPDATE
SET db.col4 = input.col4
WHEN NOT MATCHED THEN INSERT
(db.col1, db.col2, db.col3, db.col4)
VALUES (input.col1, input.col2, input.col3, input.col4)

CodePudding user response:

Merge it is. Performs well.

Dummy example based on your description:

merge into target_table a
  using source_table b
  on (a.id = b.id)
when matched then update set
  a.name = b.name,
  a.job  = b.job,
  a.sal  = b.sal
when not matched then 
  insert (id, name, job, sal) 
  values (b.id, b.name, b.job, b.sal);
  • Related