Data changes

SQL MERGE / UPSERT

Insert or update rows according to a match condition; syntax differs by database.

Availability: Common SQL with references for SQL standard, MySQL/MariaDB, PostgreSQL, SQL Server, SQLite and Oracle Database; syntax and feature support vary by engine and version.中文

Syntax

MERGE INTO target USING source ON match_condition WHEN MATCHED THEN UPDATE SET ... WHEN NOT MATCHED THEN INSERT ...;

Examples

Example (standard-style syntax). Verify supported keywords in your database.

MERGE INTO inventory AS t USING incoming AS s ON (t.sku = s.sku) WHEN MATCHED THEN UPDATE SET quantity = s.quantity WHEN NOT MATCHED THEN INSERT (sku, quantity) VALUES (s.sku, s.quantity);

SQLite-oriented variant; dialect behaviour may differ.

INSERT INTO inventory (sku, quantity) VALUES ('A-1', 12) ON CONFLICT (sku) DO UPDATE SET quantity = excluded.quantity;

Parameters, options and clauses

Option / clauseDescription
Target table / columnsName the table and columns affected by the statement.
VALUES / SET / source querySupply inserted values or assign new values.
WHERERestrict affected rows. Omitting it may change every row.
RETURNING / OUTPUTReturn changed rows where the dialect supports it.
TransactionUse a transaction when several changes must succeed or fail together.

Dialect references

Safety note

Review a command and its target before running it. Commands that alter files, services, accounts, disks, permissions or databases may be difficult to reverse. Test in a safe environment and keep backups.

Official reference ↗Back to directory