BigQuery MERGE Statement – Explained
BigQuery MERGE Statement – Explained
๐ What is BigQuery MERGE?
The MERGE statement in BigQuery allows you to conditionally INSERT, UPDATE, or DELETE rows in a target table based on matching rows from a source table. It’s ideal for data synchronization, staging table merges, and incremental updates.
๐ผ️ Thumbnail Preview
๐งช Syntax Overview
MERGE target_table AS T
USING source_table AS S
ON T.id = S.id
WHEN MATCHED THEN
UPDATE SET T.name = S.name
WHEN NOT MATCHED THEN
INSERT (id, name) VALUES (S.id, S.name);
๐ฏ Example Use Case
MERGE dataset.inventory AS I
USING dataset.new_arrivals AS N
ON I.product_id = N.product_id
WHEN MATCHED THEN
UPDATE SET I.quantity = I.quantity + N.quantity
WHEN NOT MATCHED THEN
INSERT (product_id, quantity) VALUES (N.product_id, N.quantity);
✅ Benefits of MERGE in BigQuery
- Atomic operations for INSERT, UPDATE, DELETE
- Efficient for large-scale ETL and staging workflows
- Reduces query complexity and improves maintainability
Possible share more with examples
ReplyDelete