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 / clause
Description
Target table / columns
Name the table and columns affected by the statement.
VALUES / SET / source query
Supply inserted values or assign new values.
WHERE
Restrict affected rows. Omitting it may change every row.
RETURNING / OUTPUT
Return changed rows where the dialect supports it.
Transaction
Use a transaction when several changes must succeed or fail together.
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.