Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does DB2 have an "insert or update" statement?

From my code (Java) I want to ensure that a row exists in the database (DB2) after my code is executed.

My code now does a select and if no result is returned it does an insert. I really don't like this code since it exposes me to concurrency issues when running in a multi-threaded environment.

What I would like to do is to put this logic in DB2 instead of in my Java code. Does DB2 have an insert-or-update statement? Or anything like it that I can use?

For example:

insertupdate into mytable values ('myid') 

Another way of doing it would probably be to always do the insert and catch "SQL-code -803 primary key already exists", but I would like to avoid that if possible.

like image 828
Mikael Eriksson Avatar asked Dec 01 '08 07:12

Mikael Eriksson


People also ask

What is the difference between an insert statement and an update statement?

The main difference between INSERT and UPDATE in SQL is that INSERT is used to add new records to the table while UPDATE is used to modify the existing records in the table.

Can we use insert instead of update?

No. Insert will only create a new row.

Why we use select update delete and insert statements?

INSERT , UPDATE , and DELETE are all functions in SQL that help you ensure your data is up-to-date and kept clear of unnecessary or outdated information. INSERT , UPDATE , and DELETE , as well as SELECT and MERGE, are known as Data Manipulation Language (DML) statements, which let SQL users view and manage data.


1 Answers

Yes, DB2 has the MERGE statement, which will do an UPSERT (update or insert).

MERGE INTO target_table USING source_table ON match-condition {WHEN [NOT] MATCHED            THEN [UPDATE SET ...|DELETE|INSERT VALUES ....|SIGNAL ...]} [ELSE IGNORE] 

See:

http://publib.boulder.ibm.com/infocenter/db2luw/v9/index.jsp?topic=/com.ibm.db2.udb.admin.doc/doc/r0010873.htm

https://www.ibm.com/support/knowledgecenter/en/SS6NHC/com.ibm.swg.im.dashdb.sql.ref.doc/doc/r0010873.html

https://www.ibm.com/developerworks/community/blogs/SQLTips4DB2LUW/entry/merge?lang=en

like image 162
Winston Smith Avatar answered Sep 28 '22 09:09

Winston Smith