Approach (high-level): minimize scanned bytes by (1) pre-filtering staging to true deltas, (2) deduplicating and batching the Merge, (3) limiting target scanned via clustering / micro-partition pruning (or partition key) and doing CTAS + atomic swap for large affected ranges.Operational steps:1. Load 50M into a staging table (stg_raw).2. Dedup and compute change-detection hash to produce stg_delta (only rows where data differs or new).3. Partition stg_delta into batches by hash-range or date-range to keep each MERGE small.4. For small batches: MERGE directly against target using equality on primary key. For large-range updates: CTAS target_filtered (replace affected partitions) and ATOMIC SWAP.SQL patterns:-- 1. dedupe + true-delta detection (assumes json or columns c1..cN)sql
create or replace table stg_delta as
select s.pk,
s.*,
hash_md5(concat_ws('|', s.c1, s.c2, s.c3)) as new_hash
from (
select distinct on (pk) * from stg_raw -- or use ROW_NUMBER() to dedupe
) s
left join target t on s.pk = t.pk
where t.pk is null OR hash_md5(concat_ws('|', t.c1, t.c2, t.c3)) <> hash_md5(concat_ws('|', s.c1, s.c2, s.c3));
-- 2. small-batch MERGE (repeat for partitions/batches)sql
merge into target tgt
using (
select * from stg_delta where mod(abs(hash_md5(pk)::bigint), 100) between 0 and 9
) src
on src.pk = tgt.pk
when matched then update set c1 = src.c1, c2 = src.c2, ...
when not matched then insert (pk, c1, c2, ...) values (src.pk, src.c1, src.c2, ...);
-- 3. CTAS + atomic swap for heavy range replacement (e.g., bulk date partition)sql
create or replace table target_new as
select coalesce(src.pk, tgt.pk) as pk, coalesce(src.c1, tgt.c1) as c1, ...
from target tgt
full outer join (
select * from stg_delta where date_col between '2025-11-01' and '2025-11-07'
) src on src.pk = tgt.pk
where -- keep only rows for unaffected partitions + merged results
;
alter table target rename to target_old;
alter table target_new rename to target; -- fast metadata swap
drop table if exists target_old;
Performance & operational tips:- Use Snowflake Streams to capture change data and avoid full-stage scans.- Use clustering keys on frequently filtered columns (date, region) to enable micro-partition pruning; re-cluster only affected ranges.- Batch MERGEs to ~1–10M rows to avoid huge transactions; tune by observing transaction time.- Use hash-based change detection to avoid column-by-column comparisons.- For mostly-insert workloads, prefer COPY INTO + insert-only staging then swap.- Monitor bytes scanned and query history; adjust cluster key / batch granularity.Trade-offs:- CTAS + swap is fastest for big replacements but needs careful transactional control and may double storage temporarily.- Many small MERGEs reduce scan per op but increase overhead; balance by measuring.