Using INSERT ON CONFLICT (upsert) in PostgreSQL
📖 Scenario: You are managing a small bookstore database. You want to add new books or update the stock if the book already exists.
🎯 Goal: Build a PostgreSQL query that inserts a new book into the books table. If the book already exists (same isbn), update the stock count instead.
📋 What You'll Learn
Create a
books table with columns isbn (primary key), title, and stock.Insert a book with specific values.
Add a conflict handling clause to update
stock if isbn already exists.Use the
INSERT ON CONFLICT syntax.💡 Why This Matters
🌍 Real World
Managing inventory in a bookstore or any retail system where you need to add new items or update existing stock without duplicates.
💼 Career
Database administrators and backend developers often use UPSERT to maintain data integrity and simplify code that handles insert-or-update logic.
Progress0 / 4 steps