Skip to content

Instantly share code, notes, and snippets.

@zkarj735
Created May 29, 2024 08:28
Show Gist options
  • Save zkarj735/c76961a0a7cd45e52f620731d8bcbe20 to your computer and use it in GitHub Desktop.
Save zkarj735/c76961a0a7cd45e52f620731d8bcbe20 to your computer and use it in GitHub Desktop.
A technique to "update or insert" a single row in a DB2 table.
-- DB2 has a MERGE statement which is designed to merge the rows from one table into another.
-- This technique adapts that to the case of a single row of literal values (such as might be provided in an application program).
-- This is informally known as an 'upsert' - a portmanteau of "update" and "insert".
-- The key parts of this statement are:
-- 1. The USING clause provides the values for the entire row, and also provides column names for these.
-- 2. The ON clause is the means for detecting an existing record (like a join's ON clause).
-- 3. The WHEN MATCHED clause specifies which columns to update in an existing record. Obviously this won't contain the keys, but needn't contain all the other columns either.
-- 4. The INSERT VALUES clause uses the column names provided in the USING clause.
-- Technically, the INSERT needn't specify every column (e.g. allowing defaults to be used, or ID columns to generate)
MERGE INTO Products AS Target
USING (VALUES (101, 'New Product', 19.99) ) AS Source (ProductID, ProductName, ProductPrice)
ON Target.ProductID = Source.ProductID
WHEN MATCHED THEN
UPDATE SET Target.ProductName = Source.ProductName,
Target.ProductPrice = Source.ProductPrice
WHEN NOT MATCHED BY TARGET THEN
INSERT VALUES (Source.ProductID, Source.ProductName, Source.ProductPrice);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment