Browse topics

MERGE

Version
19
Since
15
Review
Draft

Summary#

MERGE joins a source to a target table and runs the first WHEN clause that applies to each candidate row. One statement can insert, update and delete.

Syntax#

sql
MERGE INTO target AS t
USING source AS s ON t.key_column = s.key_column
WHEN MATCHED AND condition THEN
    DELETE
WHEN MATCHED THEN
    UPDATE SET value_column = s.value_column
WHEN NOT MATCHED [BY TARGET] THEN
    INSERT (column_list) VALUES (value_list)
WHEN NOT MATCHED BY SOURCE THEN
    UPDATE SET value_column = value
RETURNING merge_action(), old.value_column, new.value_column;

Example#

The output below is from PostgreSQL 19.0, produced with psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch database. The script rolls back at the end, so it leaves nothing behind.

sql
BEGIN;

CREATE TEMPORARY TABLE inventory (
    sku      text PRIMARY KEY,
    quantity integer NOT NULL
);

CREATE TEMPORARY TABLE feed (
    sku      text PRIMARY KEY,
    quantity integer NOT NULL
);

INSERT INTO inventory VALUES ('apple', 5), ('banana', 8), ('cherry', 2);
INSERT INTO feed VALUES ('apple', 9), ('banana', 0), ('damson', 4);

WITH changes AS (
    MERGE INTO inventory AS i
    USING feed AS f ON i.sku = f.sku
    WHEN MATCHED AND f.quantity = 0 THEN
        DELETE
    WHEN MATCHED THEN
        UPDATE SET quantity = f.quantity
    WHEN NOT MATCHED THEN
        INSERT (sku, quantity) VALUES (f.sku, f.quantity)
    WHEN NOT MATCHED BY SOURCE THEN
        UPDATE SET quantity = 0
    RETURNING merge_action() AS action,
              coalesce(new.sku, old.sku) AS sku,
              old.quantity AS before,
              new.quantity AS after
)
SELECT action, sku, before, after FROM changes ORDER BY sku;

SELECT sku, quantity FROM inventory ORDER BY sku;

ROLLBACK;

Expected output#

Text
action|sku|before|after
UPDATE|apple|5|9
DELETE|banana|8|NULL
UPDATE|cherry|2|0
INSERT|damson|NULL|4
(4 rows)
sku|quantity
apple|9
cherry|0
damson|4
(3 rows)

Common mistakes#

WHEN NOT MATCHED BY SOURCE can delete unrelated target rows when the source is incomplete. Make the source unique on the join key to avoid trying to update or delete a target row twice. A concurrent insert of the same key can cause a unique violation. Use INSERT ... ON CONFLICT when you need an atomic insert-or-update.

Version applicability#

PostgreSQL 15 added MERGE. Both BY forms of WHEN NOT MATCHED, RETURNING and merge_action() require PostgreSQL 17. The old and new names require PostgreSQL 18. WHEN NOT MATCHED without BY means not matched by target.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0