Oracle Merge vs Select then Insert or Update
Asked Answered
M

2

12

What is faster?

the Merge statement

    MERGE INTO table_name 
     USING dual
     ON (row_id = 'some_id')
    WHEN MATCHED THEN
     UPDATE SET col_name = 'some_val'
    WHEN NOT MATCHED THEN
     INSERT (row_id, col_name)
     VALUES ('some_id', 'some_val')

or

querying a select statement then using an update or insert statement.

    SELECT * FROM table_name where row_id = 'some_id'

if rowCount == 0

    INSERT INTO table_name (row_id,col_name) VALUES ('some_id','some_val')

else

    UPDATE table_name SET col_name='some_val' WHERE row_id='some_id'
Myriapod answered 5/9, 2012 at 3:35 Comment(0)
S
24

The rule of thumb is, if you can do it in one SQL, it'll generally perform better than doing it in multiple SQL statements.

I'd go with the MERGE if it does the job.

Also - another suggestion: you can avoid repeating data in your statement, e.g.:

MERGE INTO table
 USING (SELECT 'some_id' AS newid,
               'some_val' AS newval
        FROM dual)
 ON (rowid = newid)
WHEN MATCHED THEN
 UPDATE SET colname = newval
WHEN NOT MATCHED THEN
 INSERT (rowid, colname)
 VALUES (newid, newval)
Syndetic answered 5/9, 2012 at 3:36 Comment(8)
I was thinking the same but how about the process on the oracle server?Myriapod
yes, I gathered that - but I was talking about the choice of column name, which conflicts with oracle's ROWID pseudocolumn.Syndetic
Don't know why my answer survived so long with inaccurate information. Live and learn, I guess.Syndetic
If I use host arrays in PRO*C code for doing bulk merge with similar query, will bulk merge better that doing a query first and then do insert/update in bulk using host arrays? Please comment.Will it degrade performance as the volume increases?Silt
@Dr.DebasishJana, you're more likely to get a useful answer by asking a new question. Plus, it's free!Syndetic
@JeffreyKemp yes I did, it's #42167741Silt
The question is which one is faster? It is not which one is easy to writeLansing
@MayurB, that's precisely the question I answered. That's what "perform better" means.Syndetic
S
-2

Take care of the merge. It can consume a lot of your area TEMP using HASH JOIN. Test him using hint FIRST_ROWS or use UPDATE view join plus INSERT with NOT EXISTS.

Salleysalli answered 3/5, 2016 at 11:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.