Merge (SQL)

Merge (SQL)

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.

Contents

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. If multiple Source rows match a given Target row, error is mandated by SQL-2003.

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 MERGE INTO though fails at throwing error when multiple Source data. Additionally 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.)

IBM DB2 extends syntax with multiple WHEN MATCHED and WHEN NOT MATCHED clauses, distinguishing them with ... AND some-condition guards.

Microsoft SQL extends with supporting guards and also with supporting Left Join via WHEN NOT MATCHED BY SOURCE clauses.

References

  1. ^ MySQL :: MySQL 5.1 Reference Manual :: 12.2.4.3 INSERT ... ON DUPLICATE KEY UPDATE Syntax
  2. ^ MySQL 5.1 Reference Manual: 11.2.6 REPLACE Syntax

External links



Wikimedia Foundation. 2010.

Игры ⚽ Нужно решить контрольную?

Look at other dictionaries:

  • Merge (SQL) — Merge оператор языка SQL, который позволяет сливать данные одной таблицы с данными другой таблицы. При слиянии таблиц проверяется условие, и если оно истинно, то выполняется Update, а если нет Insert. Причем нельзя изменять поля таблицы в секции… …   Википедия

  • Merge — See Help:Merging for the usage of Merge in Wikipedia. Contents 1 Concepts 2 Computer science 3 Music …   Wikipedia

  • SQL — Класс языка: Мультипарадигмальный Появился в: 1974 Автор(ы): Дональд Чэмбэрлин Рэймонд Бойс Релиз: SQL:2008 (2008) Типизация данных …   Википедия

  • SQL Server Integration Services — (SSIS) is a component of Microsoft SQL Server 2005 and 2008. It replaces Data Transformation Services, which has been a feature of SQL Server since Version 7.0. Unlike DTS, which was included in all versions, SSIS is available in the Standard ,… …   Wikipedia

  • SQL Server Compact — Filename extension .sdf Developed by Microsoft Type of format Relational database Microsoft SQL Server Compact (SQL CE) is a compact relational database produced by Microsoft for applications that run on mobile devices and desktops. Prior to the… …   Wikipedia

  • SQL-92 — SQL 92  третья версия языка запросов к базам данных SQL. В отличие от стандарта SQL 89, третья версия стала весьма существенным обновлением языка. За исключением некоторых мелких противоречий стандарт SQL 89 практически полностью совместим… …   Википедия

  • SQL:2008 — SQL:2008  шестая версия (ревизия) языка запросов баз данных SQL. Содержание 1 Общие сведения 2 Новшества 3 …   Википедия

  • SQL:2003 — Saltar a navegación, búsqueda SQL: 2003 es la quinta revisión del lenguaje de consulta de base de datos SQL. La última revisión de el estándar es SQL:2008. Resumen El estándar SQL:2003 hace pequeñas modificaciones sobre la versión anterior,… …   Wikipedia Español

  • SQL — This article is about the database language. For the airport with IATA code SQL, see San Carlos Airport. SQL Paradigm(s) Multi paradigm Appeared in 1974 Designed by Donald D. Chamberlin Raymond F. Boyce Developer …   Wikipedia

  • SQL — Structured Query Language SQL Apparu en 1974 Auteur …   Wikipédia en Français

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”