Conditional INSERT with ON CONFLICT in PostgreSQL
📖 Scenario: You are managing a small library database. You want to add new books to the books table. However, if a book with the same isbn already exists, you want to update its copies count only if the new count is higher than the existing one.
🎯 Goal: Build a SQL query that inserts a new book into the books table. If a conflict occurs on the isbn column, update the copies column only if the new value is greater than the existing value.
📋 What You'll Learn
Create a
books table with columns isbn (text, primary key), title (text), and copies (integer).Insert a new book with specific
isbn, title, and copies values.Use
ON CONFLICT on the isbn column to handle duplicates.Update the
copies column only if the new copies value is greater than the existing one.💡 Why This Matters
🌍 Real World
Managing inventory or catalog data where duplicates may occur and updates depend on conditions is common in libraries, stores, and many applications.
💼 Career
Understanding conditional inserts and conflict handling is essential for database administrators and backend developers to maintain data integrity and efficiency.
Progress0 / 4 steps