PostgreSQL interview question · Most asked
How does INSERT ... ON CONFLICT work in PostgreSQL?
Summary
It is PostgreSQL's atomic upsert: insert a row, and if it violates a specified unique constraint or index, either do nothing (DO NOTHING) or update the existing row (DO UPDATE SET ..., with EXCLUDED referring to the proposed row).
Longer Answer
INSERT INTO page_views (page_id, day, views)
VALUES (42, current_date, 1)
ON CONFLICT (page_id, day) DO UPDATE SET views = page_views.views + EXCLUDED.views
RETURNING views;
The conflict target must match a unique index (or constraint). It is safe under concurrency, unlike "select, then insert or update". DO UPDATE can affect each row only once per statement, so deduplicate input batches. MERGE (PostgreSQL 15+) handles more complex insert/update/delete synchronisation; it is not a drop-in concurrency-safe replacement for ON CONFLICT.
Key Points
- Atomic upsert on a unique index.
EXCLUDED= proposed row.- Concurrency-safe.
- MERGE for complex sync (PG 15+).
More most-asked PostgreSQL questions
- How does MVCC work in PostgreSQL?
- JSON or JSONB in PostgreSQL, and how do you index JSONB?
- What does VACUUM do, and how does autovacuum work?
- How do you read EXPLAIN ANALYZE output in PostgreSQL?
- What isolation levels does PostgreSQL provide, and how do they behave?
- What index types does PostgreSQL support, and when do you use each?
- Which schema changes take heavy locks in PostgreSQL, and how do you avoid outages during migrations?
- Why do PostgreSQL deployments need connection pooling, and how do PgBouncer's modes differ?