Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

oracle sql: update if exists else insert [duplicate]

Tags:

sql

oracle

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

Hi,

I have a table in which a record has to be modified if it already exists else a new record has to be inserted. Oracle sql doesnt accept IF EXISTS, otherwise I would have done an if - update - else - insert query. I've looked at MERGE but it only works for multiple tables. What do i do?

like image 208
Aks Avatar asked Oct 25 '10 13:10

Aks


People also ask

Does Oracle have Upsert?

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.

Can we use if exists in Oracle?

The Oracle EXISTS condition is used in combination with a subquery and is considered "to be met" if the subquery returns at least one row. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.


1 Answers

MERGE doesn't need "multiple tables", but it does need a query as the source. Something like this should work:

MERGE INTO mytable d USING (SELECT 1 id, 'x' name from dual) s ON (d.id = s.id) WHEN MATCHED THEN UPDATE SET d.name = s.name WHEN NOT MATCHED THEN INSERT (id, name) VALUES (s.id, s.name); 

Alternatively you can do this in PL/SQL:

BEGIN   INSERT INTO mytable (id, name) VALUES (1, 'x'); EXCEPTION   WHEN DUP_VAL_ON_INDEX THEN     UPDATE mytable     SET    name = 'x'     WHERE id = 1; END; 
like image 189
Tony Andrews Avatar answered Sep 20 '22 02:09

Tony Andrews