Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle merge constants into single table

Tags:

In Oracle, given a simple data table:

create table data (
    id       VARCHAR2(255),
    key      VARCHAR2(255),
    value    VARCHAR2(511));

suppose I want to "insert or update" a value. I have something like:

merge into data using dual on 
    (id='someid' and key='testKey')
when matched then 
    update set value = 'someValue' 
when not matched then 
    insert (id, key, value) values ('someid', 'testKey', 'someValue');

Is there a better way than this? This command seems to have the following drawbacks:

  • Every literal needs to be typed twice (or added twice via parameter setting)
  • The "using dual" syntax seems hacky

If this is the best way, is there any way around having to set each parameter twice in JDBC?

like image 400
David Citron Avatar asked Oct 03 '08 15:10

David Citron


People also ask

How do I MERGE data from one table to another in Oracle?

First, specify the target table ( target_table ) which you want to update or insert into in the INTO clause. Second, specify the source of data ( source_table ) to be updated or inserted in the USING clause. Third, specify the search condition upon which the merge operation either updates or inserts in the ON clause.

Can we use MERGE on same table?

This command checks if USER_ID and USER_NAME are matched, if not matched then it will insert. This is a good simple example because, if you're only using one table, you have to use the select 1 from dual and in the ON, enter the criteria, based on the primary key for the table.

Is MERGE faster than update in Oracle?

merge is faster for merging. update is faster for updating.

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.


1 Answers

I don't consider using dual to be a hack. To get rid of binding/typing twice, I would do something like:

merge into data
using (
    select
        'someid' id,
        'testKey' key,
        'someValue' value
    from
        dual
) val on (
    data.id=val.id
    and data.key=val.key
)
when matched then 
    update set data.value = val.value 
when not matched then 
    insert (id, key, value) values (val.id, val.key, val.value);
like image 144
Craig Avatar answered Jan 03 '23 03:01

Craig