PostgreSQL ON CONFLICT Statement

PostgreSQL ON CONFLICT Statement - Explained

PostgreSQL ON CONFLICT Statement - Explained

๐Ÿ“˜ Introduction to ON CONFLICT Statement

In PostgreSQL, ON CONFLICT provides a powerful mechanism to deal with data clashes during INSERT operations. When inserting into a table that contains a UNIQUE constraint or index, you can define how the database should react—either by updating the existing record or ignoring the new one.

๐Ÿงช Syntax Overview


INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...)
ON CONFLICT (conflict_target)
DO UPDATE SET column1 = value1, column2 = value2, ...;
      

conflict_target: typically the column(s) with a UNIQUE constraint (e.g., employee_id)
DO UPDATE: specifies what should be updated
DO NOTHING: skips the insertion if conflict occurs

๐ŸŽฏ Real-World Example


INSERT INTO employees (employee_id, name, salary)
VALUES (101, 'John Doe', 50000)
ON CONFLICT (employee_id)
DO UPDATE SET
  name = EXCLUDED.name,
  salary = EXCLUDED.salary;
      

If an employee with ID 101 already exists, this query updates their name and salary instead of inserting a duplicate.

✅ Benefits of Using ON CONFLICT

  • Handles INSERT errors seamlessly
  • Reduces the need for complex conditional queries
  • Ensures data integrity through atomic operations
  • Improves performance in bulk-upsert operations

๐Ÿ“š Stay tuned for more informative articles on PostgreSQL and database management from aki13promy.

Comments

Post a Comment

Popular posts from this blog

Spicy Prawn Masala | Prawn Masala Curry Recipe | Shrimp Masala

LRT Masjid Jamek-Bandaraya

Night Park Putrajaya - Secret Garden