UPSERT & Merge (ON CONFLICT)
Perform atomic insert-or-update operations using PostgreSQL ON CONFLICT and standard MERGE statements.
UPSERT & Merge (ON CONFLICT) is an essential topic in SQL and relational database engineering.
Overview
Building on foundational principles introduced in delete-vs-truncate, mastering upsert & merge (on conflict) provides the core mental model and practical query skills needed for production relational database engineering.
INSERT INTO product_views (product_id, view_count)
VALUES (402, 1)
ON CONFLICT (product_id)
DO UPDATE SET view_count = product_views.view_count + 1;
Key Concepts
- Understand the fundamental syntax, conventions, and mental model.
- Avoid common beginner traps, data type mismatches, and performance pitfalls.
- Apply practical idioms directly in production applications.
[!TIP] Master this concept to build a rock-solid foundation. Next, proceed to sql-data-types.