A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.w3resource.com/PostgreSQL/snippets/postgres-on-conflict-do-nothing.php below:

Website Navigation


Mastering PostgreSQL ON CONFLICT DO NOTHING

Mastering PostgreSQL ON CONFLICT DO NOTHINGLast update on December 31 2024 13:03:53 (UTC/GMT +8 hours)

PostgreSQL: ON CONFLICT DO NOTHING

The ON CONFLICT DO NOTHING clause in PostgreSQL allows you to handle conflicts that arise when attempting to insert data into a table with unique constraints or primary keys. Instead of throwing an error when a conflict occurs, the database ignores the conflicting row, ensuring smooth data handling.

This guide covers the syntax, use cases, examples, and best practices for using ON CONFLICT DO NOTHING.

Syntax:

 
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...)
ON CONFLICT [conflict_target] DO NOTHING;

Key Elements:

Example 1: Basic Usage with Unique Constraint

Code:

-- Create a table with a unique constraint
CREATE TABLE users (
    user_id SERIAL PRIMARY KEY, -- Auto-incremented primary key
    email VARCHAR(255) UNIQUE -- Unique constraint on the email column
);

-- Insert a row into the users table
INSERT INTO users (email) 
VALUES ('[email protected]');

-- Attempt to insert the same email, but avoid an error
INSERT INTO users (email) 
VALUES ('[email protected]')
ON CONFLICT DO NOTHING;

Explanation:

Example 2: Specifying Conflict Targets

Code:

-- Create a table with composite unique constraints
CREATE TABLE orders (
    order_id SERIAL PRIMARY KEY, -- Primary key for the table
    product_id INT NOT NULL, -- Product identifier
    customer_id INT NOT NULL, -- Customer identifier
    UNIQUE (product_id, customer_id) -- Composite unique constraint
);

-- Insert an order
INSERT INTO orders (product_id, customer_id) 
VALUES (1, 100);

-- Attempt to insert the same product-customer pair
INSERT INTO orders (product_id, customer_id) 
VALUES (1, 100)
ON CONFLICT (product_id, customer_id) DO NOTHING;

Explanation

Output

Initial Table (Before Conflict):

order_id	product_id	customer_id
1	1	100

After Attempted Conflict Insert:

order_id	product_id	customer_id
1	1	100

Advantages of ON CONFLICT DO NOTHING

Common Use Cases

Potential Pitfalls

Comparison: DO NOTHING vs DO UPDATE

Example of DO UPDATE:

Code:

INSERT INTO users (email, name) 
VALUES ('[email protected]', 'Jana Isabel')
ON CONFLICT (email) 
DO UPDATE SET name = EXCLUDED.name;

Best Practices

All PostgreSQL Questions, Answers, and Code Snippets Collection.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4