Concept · Modifying data

MERGE

MERGE compares source data with a target table to decide which rows to update, insert or delete, according to the rules in the statement.

MERGE example

Suppose inventory holds the current products and stock_updates brings in a new snapshot:

Example in PostgreSQL syntax
MERGE INTO inventory AS destination
USING stock_updates AS source
ON destination.product_id = source.product_id
WHEN MATCHED THEN
  UPDATE SET stock = source.stock
WHEN NOT MATCHED THEN
  INSERT (product_id, stock)
  VALUES (source.product_id, source.stock);

Product 2 matches and is updated. Product 3 does not exist in the target and is inserted. Product 1 is not in the source and stays as it is, because the statement has no action for “not matched by source”.

What changes from case to case

How it makes the decision

  1. It builds the candidate rows by relating source and target with ON.
  2. It classifies each candidate as matched or not matched.
  3. It evaluates the WHEN clauses in the order written.
  4. It runs the first applicable action for that row.

The ON condition defines what “the same row” means for the sync. It must compare a key that unambiguously identifies the target row. Do not use it as a general update filter.

Checks before running it

  • First run a SELECT with the same join to review the matches.
  • Check that the source does not have two rows for the same target key.
  • Test with a small amount of data, inside a transaction where the engine allows it.
  • Review triggers, constraints and delete actions that could widen the effect.
  • Decide how you will check the result: rows affected, final values and target rows that do not appear in the source.

Common mix-ups with MERGE

Allowing several source rows for the same target row

If two source rows match a single target product, the update is no longer an unambiguous decision and the engine may reject the operation. Deduplicate or aggregate the source before the MERGE and use a unique key for the condition.

Check beforehand
SELECT product_id, COUNT(*) AS occurrences
FROM stock_updates
GROUP BY product_id
HAVING COUNT(*) > 1;
Key differences between engines

PostgreSQL, SQL Server and Oracle all have MERGE, but their syntax, available actions, and restrictions are not identical. MySQL uses mechanisms such as INSERT ... ON DUPLICATE KEY UPDATE for certain insert-or-update cases. SQLite offers INSERT ... ON CONFLICT as an UPSERT. These alternatives depend on a unique key and do not cover everything a full MERGE can do.

This example was checked against the official PostgreSQL documentation, but it was not run in the site's local lab, because that lab uses SQLite, which does not implement the MERGE.