Jump to content

Merge (SQL)

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by 79.111.218.128 (talk) at 11:31, 24 October 2011 (Usage). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

A relational database management system uses SQL MERGE (upsert) statements to INSERT new records or UPDATE existing records depending on whether or not a condition matches. It was officially introduced in the SQL:2008 standard.

Usage

MERGE INTO table_name USING table_reference ON (condition)
  WHEN MATCHED THEN
  UPDATE SET column1 = value1 [, column2 = value2 ...]
  WHEN NOT MATCHED THEN
  INSERT (column1 [, column2 ...]) VALUES (value1 [, value2 ...


Right join is employed over Target and Source tables. That is, rows present in Source and missed from Target do run the action, the rows missed from Source and present in Target are ignored.

Implementations

Database management systems Oracle Database, DB2, and MS SQL support the standard syntax. Some also add non-standard SQL extensions.

Other non-standard implementations

Some other database management systems support this, or very similar behavior, through their own, non-standard SQL extensions.

MySQL, for example, supports the use of INSERT ... ON DUPLICATE KEY UPDATE syntax[1] which can be used to achieve the same effect. It also supports REPLACE INTO syntax[2], which first deletes the row, if exists, and then inserts the new one.

SQLite's INSERT OR REPLACE INTO works similarly.

Firebird supports both MERGE INTO and a single-row version, UPDATE OR INSERT INTO tablename (columns) VALUES (values) [MATCHING (columns)], but the latter does not give you the option to take different actions on insert vs. update (e.g. setting a new sequence value only for new rows, not for existing ones.)

References