Data manipulation language (DML) statements in standard SQL | BigQuery | Google Cloud

元からあるテーブル(Target) を 新しいテーブル(Source) で置き換える、というのが基本。

新しいレコードや重なってるレコードの値をどうするかを指定できたり、”重なってる”の条件を細かく指定できたりする。

構文

merge <target_table> as T
using <soure_table> as S
on <condition>
when matched then
  update set 
     col1 = T.col1 + S.col2
     col2 = ...
when not matched then
  insert (col1, col2) values (S.col1, S.col2)

MERGE `project.dataset.product` AS target
USING (SELECT *
     FROM UNNEST([
         STRUCT('TBL535522' AS sku, 5 AS quantity, 240.5 AS price),
         ('POT76456', 2, 32),
         ('FPL29921', 10, 780),
         ('ABC123456', 5, 250)
     ])) AS source
ON target.sku = source.sku
WHEN MATCHED THEN # AND target.description = 'Furniture' THEN みたいなこともできる
  UPDATE SET
       quantity = target.quantity + source.quantity,
       price = target.price + source.price
WHEN NOT MATCHED THEN
  INSERT (sku, quantity, price)
  VALUES(source.sku, source.quantity, source.price);

ドキュメント