Request a demo

BigQuery · DML statement

BigQuery MERGE

MERGE updates, inserts and deletes rows of a BigQuery table in one atomic statement, by matching it against a source table or query. It is BigQuery's upsert: WHEN MATCHED THEN UPDATE, WHEN NOT MATCHED THEN INSERT, and WHEN NOT MATCHED BY SOURCE THEN DELETE for rows that disappeared.

GoogleSQL for BigQuery · Checked against the official reference in November 2026

MERGE joins a target table with a source (a table or a subquery) on the ON condition and then applies WHEN clauses to each row. WHEN MATCHED updates or deletes target rows that have a source match. WHEN NOT MATCHED (also written WHEN NOT MATCHED BY TARGET) inserts source rows that have no target match; INSERT ROW inserts all source columns in order. WHEN NOT MATCHED BY SOURCE updates or deletes target rows that have no source match. Each clause can add AND condition, and for every row only the first clause whose condition is true runs, so put specific clauses before general ones. The whole statement succeeds or fails as one transaction, and matching uses the tables as they were when the statement started: rows inserted by the MERGE never match.

One rule causes most MERGE failures. If a target row matches more than one source row and a WHEN MATCHED clause would update or delete it, the statement fails with UPDATE/MERGE must match at most one source row for each target row. Change feeds and append-only staging tables often hold several versions of a key, so reduce the source to one row per key first, for example with QUALIFY ROW_NUMBER() OVER (PARTITION BY id ORDER BY updated_at DESC) = 1. The opposite trap is NULL keys: NULL = NULL is not true, so rows with a NULL key never match and are inserted again on every run. The docs suggest ON t.k = s.k OR (t.k IS NULL AND s.k IS NULL) when keys can be NULL.

MERGE is billed like other DML. On-demand, a MERGE whose only action is INSERT bills the bytes it reads. As soon as it has an UPDATE or DELETE clause, it also bills the full size of the target table (for a partitioned table, of the partitions being updated), because BigQuery rewrites the storage it touches. For a partitioned target, put a constant filter on the partitioning column in the source subquery, the WHEN conditions or the ON clause. A WHEN NOT MATCHED BY SOURCE clause without such a filter has to read the whole target. To replace one partition atomically, use ON FALSE with a filtered WHEN NOT MATCHED BY SOURCE ... DELETE plus WHEN NOT MATCHED ... INSERT ROW; the constant false condition lets BigQuery prune both tables.

MERGE with UPDATE or DELETE is a mutating DML statement: BigQuery runs at most two of them at a time per table and queues up to 20 more. Concurrent statements that change the same partitions conflict, are retried, and can fail with Could not serialize access to table due to concurrent update. A MERGE that only inserts does not conflict. Rows streamed in the last 30 minutes through the legacy tabledata.insertAll API cannot be updated or deleted yet (DML over the streaming buffer).

Syntax

MERGE [INTO] target_table [[AS] alias]
USING source_table_or_subquery [[AS] alias]
ON merge_condition
when_clause [...]

when_clause:
    WHEN MATCHED [AND condition] THEN { UPDATE SET column = expression[, ...] | DELETE }
  | WHEN NOT MATCHED [BY TARGET] [AND condition] THEN INSERT [(column[, ...])] { VALUES (expression[, ...]) | ROW }
  | WHEN NOT MATCHED BY SOURCE [AND condition] THEN { UPDATE SET column = expression[, ...] | DELETE }

Arguments and return value

ArgumentDescription
target_tableThe table to change. It cannot be a view or a wildcard table.
source_table_or_subqueryA table or a subquery. Filter and deduplicate here: each target row may match at most one source row when it is updated or deleted.
merge_conditionThe join condition, usually key equality. ON FALSE makes every row unmatched, which turns MERGE into an atomic delete-and-insert.
WHEN MATCHEDRuns UPDATE SET or DELETE on target rows that have a source match.
WHEN NOT MATCHED [BY TARGET]Runs INSERT for source rows with no target match. INSERT ROW inserts every source column in order.
WHEN NOT MATCHED BY SOURCERuns UPDATE SET or DELETE on target rows with no source match, for example to remove records that disappeared upstream.

Returns: No result set. The job statistics report inserted, updated and deleted row counts (dml_statistics in INFORMATION_SCHEMA.JOBS).

Examples

Upsert customers from a staging table

Updates customers that exist and changed, inserts new ones. The extra AND s.updated_at > t.updated_at keeps an older staging row from overwriting newer data.

MERGE `project.dataset.customers` AS t
USING `project.dataset.customers_staging` AS s
ON t.customer_id = s.customer_id
WHEN MATCHED AND s.updated_at > t.updated_at THEN
  UPDATE SET email = s.email, plan = s.plan, updated_at = s.updated_at
WHEN NOT MATCHED THEN
  INSERT (customer_id, email, plan, updated_at)
  VALUES (s.customer_id, s.email, s.plan, s.updated_at);

Deduplicate a change feed before merging

The change table can hold several versions of the same customer from one day. Keeping only the latest version per key avoids the at-most-one-source-row error. INSERT ROW works because the subquery returns the target's columns in the target's order.

MERGE `project.dataset.customers` AS t
USING (
  SELECT customer_id, email, plan, updated_at
  FROM `project.dataset.customer_changes`
  WHERE change_date = '2026-11-22'
  QUALIFY ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY updated_at DESC) = 1
) AS s
ON t.customer_id = s.customer_id
WHEN MATCHED THEN
  UPDATE SET email = s.email, plan = s.plan, updated_at = s.updated_at
WHEN NOT MATCHED THEN
  INSERT ROW;

Replace one day of a partitioned table atomically

daily_inventory is partitioned by snapshot_date. With ON FALSE nothing matches: every target row of 2026-11-22 is deleted and every source row is inserted, in one transaction. Because the conditions are constant filters on the partitioning column, only that day's partition is read and rewritten, not the whole table.

MERGE `project.dataset.daily_inventory` AS t
USING (
  SELECT snapshot_date, sku, warehouse, quantity
  FROM `project.dataset.inventory_snapshot`
  WHERE snapshot_date = '2026-11-22'
) AS s
ON FALSE
WHEN NOT MATCHED BY SOURCE AND t.snapshot_date = '2026-11-22' THEN
  DELETE
WHEN NOT MATCHED THEN
  INSERT ROW;

Soft-delete rows that disappeared from the source

Marks active subscriptions as cancelled when they are missing from today's full export. The extra condition on t.status stops the statement from touching rows that are already cancelled. Use this only when the source is a complete snapshot: with a partial source, BY SOURCE would cancel everything not in it.

MERGE `project.dataset.subscriptions` AS t
USING `project.dataset.subscriptions_export` AS s
ON t.subscription_id = s.subscription_id
WHEN MATCHED THEN
  UPDATE SET status = s.status, renewed_at = s.renewed_at
WHEN NOT MATCHED BY TARGET THEN
  INSERT (subscription_id, customer_id, status, renewed_at)
  VALUES (s.subscription_id, s.customer_id, s.status, s.renewed_at)
WHEN NOT MATCHED BY SOURCE AND t.status = 'active' THEN
  UPDATE SET status = 'cancelled';

Common mistakes

  • Merging a source with duplicate keys. Several source rows for one target row fail the whole statement with UPDATE/MERGE must match at most one source row for each target row. Deduplicate with QUALIFY ROW_NUMBER() OVER (PARTITION BY key ORDER BY updated_at DESC) = 1, or aggregate the source.
  • Joining on keys that can be NULL. NULL never equals NULL, so those rows are treated as new on every run and the target fills with duplicates. Use ON t.k = s.k OR (t.k IS NULL AND s.k IS NULL) or make the key NOT NULL upstream.
  • Using WHEN NOT MATCHED BY SOURCE THEN DELETE with an incremental source. Every target row that is not in the current batch counts as missing and gets deleted. Either merge from a full snapshot or add a condition that limits the clause to the slice the source covers.
  • Looking for INSERT ... ON CONFLICT (PostgreSQL) or ON DUPLICATE KEY UPDATE (MySQL). BigQuery has neither, and its primary keys are not enforced, so a plain INSERT happily creates duplicates. MERGE is the upsert.
  • Putting a general WHEN clause before a specific one. Clauses are evaluated in order and the first true one wins, so WHEN MATCHED THEN UPDATE placed before WHEN MATCHED AND s.is_deleted THEN DELETE means the DELETE never runs.

Cost and performance

  • On-demand, a MERGE with an UPDATE or DELETE clause bills the bytes it reads plus the full size of the target table (for a partitioned table, of the partitions being updated). Upserting 1,000 rows into an unpartitioned 2 TiB table therefore bills at least 2 TiB, $12.50 or more at $6.25 per TiB, on every run. Partition the target and filter on the partitioning column so only the affected partitions count.
  • WHEN NOT MATCHED BY SOURCE without a constant partition filter forces a scan of the whole target, and combined with WHEN NOT MATCHED it usually needs a full outer join that cannot be pruned. The ON FALSE pattern in the third example is the documented way to keep pruning.
  • Batch changes into one MERGE per load instead of row-by-row statements. Mutating DML is limited to two running and 20 queued statements per table, and to 25 DML statements per table every 10 seconds; beyond that you get Too many DML statements outstanding.

FAQ

How do I upsert in BigQuery?

Use MERGE with WHEN MATCHED THEN UPDATE SET ... and WHEN NOT MATCHED THEN INSERT ..., as in the first example. There is no INSERT ... ON CONFLICT or UPSERT keyword.

Why does my MERGE fail with "must match at most one source row for each target row"?

The source has more than one row for at least one key that matches a target row, and a WHEN MATCHED clause updates or deletes it. Find the keys with GROUP BY key HAVING COUNT(*) > 1 and deduplicate the source, usually keeping the latest row per key.

How much does a MERGE cost in BigQuery?

On-demand, an insert-only MERGE bills the bytes it reads; with any UPDATE or DELETE clause it also bills the size of the target table, or of the partitions being updated if the table is partitioned. On capacity pricing it uses slots for the read and the rewrite. A dry run shows the estimate.

What does WHEN NOT MATCHED BY SOURCE do?

It acts on target rows that have no matching source row: you can DELETE them or UPDATE them, for example to set a deleted flag. Add AND conditions to limit it to the rows the source is supposed to cover.

Errors you may hit

All BigQuery DML statements · All statements and clauses · BigQuery error messages

Observability for every BigQuery table, in about 15 minutes

Masthead detects freshness, volume and schema anomalies, monitors pipeline errors and maps column-level lineage across all your projects, from logs and metadata only.