ON CONFLICT를 활용한 대규모 업서트
잠금 경합과 팽창을 피하면서 대규모 배치에 효율적인 병합 로직을 구현하는 방법을 배웁니다.
ON CONFLICT를 활용한 대규모 업서트은(는) CoddyKit의 무료 PostgreSQL Performance & Query Optimization 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 PostgreSQL Performance & Query Optimization 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. PostgreSQL Performance & Query Optimization 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Upserts Need Care at Scale
An upsert inserts a row, but if it would collide with an existing key, it updates the existing row instead. PostgreSQL spells this INSERT ... ON CONFLICT.
For small workloads it is trivial. For ETL-sized batches (tens of thousands to millions of rows) the naive approach causes three problems:
- Lock contention — concurrent writers fighting over the same rows or index pages.
- Table bloat — every UPDATE writes a new row version (dead tuple) that VACUUM must later reclaim.
- WAL and round-trip overhead — row-by-row upserts multiply network and transaction cost.
This lesson builds a merge that is both correct and throughput-friendly.
The ON CONFLICT Shape
ON CONFLICT requires a conflict target: the column(s) or constraint that define a duplicate. PostgreSQL needs a unique or exclusion constraint on that target to arbitrate.
The two actions are DO NOTHING (skip the colliding row) and DO UPDATE (merge new values in).
Inside DO UPDATE, the incoming row is exposed through the special EXCLUDED pseudo-table.
INSERT INTO products (sku, name, price)
VALUES ('A-100', 'Widget', 9.99)
ON CONFLICT (sku) DO UPDATE
SET name = EXCLUDED.name,
price = EXCLUDED.price;One Statement, Many Rows
The single most important throughput rule: batch your rows into one statement. A multi-row VALUES list (or a feeding SELECT) is parsed, planned, and committed once instead of N times.
This collapses N network round-trips and N transaction commits into one, often a 10-100x speedup over row-by-row upserts.
INSERT INTO products (sku, name, price)
VALUES
('A-100', 'Widget', 9.99),
('A-101', 'Gadget', 14.50),
('A-102', 'Gizmo', 7.25)
ON CONFLICT (sku) DO UPDATE
SET name = EXCLUDED.name,
price = EXCLUDED.price;Staging Table + INSERT...SELECT
For real ETL, load raw data into an unlogged staging table first (often via COPY, the fastest bulk path), then merge from staging into the target with one INSERT ... SELECT ... ON CONFLICT.
Benefits:
COPYavoids per-row INSERT overhead.- An
UNLOGGEDstaging table skips WAL for the load phase. - You can dedupe and transform in the SELECT before merging.
CREATE UNLOGGED TABLE products_stage (LIKE products);
-- bulk load: COPY products_stage FROM '/data/products.csv' CSV;
INSERT INTO products (sku, name, price)
SELECT sku, name, price FROM products_stage
ON CONFLICT (sku) DO UPDATE
SET name = EXCLUDED.name,
price = EXCLUDED.price;Deduplicate the Batch First
A subtle but fatal error: a single INSERT statement cannot update the same target row twice. If your batch contains two rows with the same conflict key, PostgreSQL raises:
ERROR: ON CONFLICT DO UPDATE command cannot affect row a second time
Fix it by collapsing duplicates in the source before merging. DISTINCT ON keeps one row per key — typically the newest.
INSERT INTO products (sku, name, price)
SELECT DISTINCT ON (sku) sku, name, price
FROM products_stage
ORDER BY sku, updated_at DESC
ON CONFLICT (sku) DO UPDATE
SET name = EXCLUDED.name,
price = EXCLUDED.price;Skip No-Op Updates to Cut Bloat
Every DO UPDATE writes a new row version, even when the new values are identical to the old ones. Those dead tuples bloat the table and create extra work for VACUUM.
Add a WHERE clause to the DO UPDATE so it fires only when something actually changed. Use IS DISTINCT FROM so NULLs compare correctly.
INSERT INTO products (sku, name, price)
SELECT sku, name, price FROM products_stage
ON CONFLICT (sku) DO UPDATE
SET name = EXCLUDED.name,
price = EXCLUDED.price
WHERE products.name IS DISTINCT FROM EXCLUDED.name
OR products.price IS DISTINCT FROM EXCLUDED.price;Order Batches to Tame Lock Contention
When several ETL workers run concurrently, deadlocks appear if they touch the same keys in different orders. Worker 1 locks key X then Y; worker 2 locks Y then X — both block forever until PostgreSQL kills one.
Defenses:
- Sort each batch by the conflict key so all workers acquire locks in the same order.
- Partition work by key range so no two workers share keys.
- Keep transactions short — long-held row locks magnify contention.
INSERT INTO products (sku, name, price)
SELECT sku, name, price
FROM products_stage
ORDER BY sku -- consistent lock acquisition order
ON CONFLICT (sku) DO UPDATE
SET name = EXCLUDED.name,
price = EXCLUDED.price;Chunk Giant Merges
One enormous transaction merging millions of rows holds locks for a long time, balloons WAL, and blocks autovacuum from cleaning up. Break the work into chunks (for example 10k-50k rows) and commit between them.
Smaller transactions release locks sooner, let autovacuum keep pace, and make retries cheap after a failure. The trade-off is slightly more commit overhead — tune the chunk size against your hardware.
-- Merge one bounded slice; loop over key ranges from the app side.
INSERT INTO products (sku, name, price)
SELECT sku, name, price
FROM products_stage
WHERE sku >= 'A-0000' AND sku < 'A-5000'
ON CONFLICT (sku) DO UPDATE
SET name = EXCLUDED.name,
price = EXCLUDED.price;Choosing the Right Conflict Target
The conflict target must match an actual unique/primary-key or exclusion constraint. You can target by column list ON CONFLICT (sku) or by constraint name ON CONFLICT ON CONSTRAINT products_sku_key.
For partial unique indexes, repeat the index predicate so PostgreSQL can pick the right one:
-- Unique only among active rows
CREATE UNIQUE INDEX products_active_sku
ON products (sku) WHERE is_active;
INSERT INTO products (sku, name, is_active)
VALUES ('A-100', 'Widget', true)
ON CONFLICT (sku) WHERE is_active DO UPDATE
SET name = EXCLUDED.name;ON CONFLICT vs MERGE
PostgreSQL 15+ adds the SQL-standard MERGE, which can INSERT, UPDATE, and DELETE in one pass. For high-throughput upserts, INSERT ... ON CONFLICT is usually still preferred:
ON CONFLICTis atomic against concurrent inserts — it handles a race where another transaction inserts the same key, retrying internally.- Classic
MERGEcan raise a unique-violation under heavy concurrency because it does not have that built-in conflict arbitration.
Use MERGE when you need DELETE branches or complex conditional logic; use ON CONFLICT for plain, concurrency-safe upserts.
Maintenance: VACUUM and Indexes
Even an optimized merge produces dead tuples on the updated rows. Keep performance steady with maintenance discipline:
- Ensure autovacuum keeps up; for hot ETL tables lower
autovacuum_vacuum_scale_factorso it triggers more often. - After a massive one-off backfill, run
VACUUM (ANALYZE)to reclaim space and refresh planner statistics. - Every extra index on the target slows the merge (each insert/update maintains all of them) — keep only the indexes you truly need.
VACUUM (ANALYZE) products;Quick Check
Test your understanding of safe, high-throughput merges.
Recap
Efficient upserts at scale come from a few combined habits:
- Batch rows into one statement; for ETL, stage with
COPYthenINSERT ... SELECT ... ON CONFLICT. - Deduplicate the batch (
DISTINCT ON) so no key appears twice. - Skip no-op updates with a
WHERE ... IS DISTINCT FROMclause to curb dead tuples and bloat. - Order by the conflict key and partition work to avoid deadlocks; chunk huge merges into short transactions.
- Prefer
ON CONFLICTfor concurrency-safe upserts; keep autovacuum healthy and indexes lean.
Together these turn a fragile row-by-row merge into a fast, low-contention ETL load.
자주 묻는 질문
“ON CONFLICT를 활용한 대규모 업서트” 강의는 무료인가요?
네 — “ON CONFLICT를 활용한 대규모 업서트” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 PostgreSQL Performance & Query Optimization 강의 전체를 잠금 해제할 수 있습니다. PostgreSQL Performance & Query Optimization 강의에는 총 4개의 강의가 포함되어 있습니다.
“ON CONFLICT를 활용한 대규모 업서트”에서 뭘 배우나요?
잠금 경합과 팽창을 피하면서 대규모 배치에 효율적인 병합 로직을 구현하는 방법을 배웁니다. 브라우저에서 직접 실행하는 실습 코드로 PostgreSQL Performance & Query Optimization을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
PostgreSQL Performance & Query Optimization을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 PostgreSQL Performance & Query Optimization은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“ON CONFLICT를 활용한 대규모 업서트” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 PostgreSQL Performance & Query Optimization 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 PostgreSQL Performance & Query Optimization 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- COPY와 다중 행 INSERT 처리량 비교
- 로드 중 인덱스와 제약 조건 지연
- 수집을 위한 WAL과 체크포인트 조정
- ON CONFLICT를 활용한 대규모 업서트