Home > Database > Mysql Tutorial > How to Handle Multiple Conflict Targets in PostgreSQL's ON CONFLICT Clause?

How to Handle Multiple Conflict Targets in PostgreSQL's ON CONFLICT Clause?

Mary-Kate Olsen
Release: 2025-01-12 17:44:43
Original
450 people have browsed it

How to Handle Multiple Conflict Targets in PostgreSQL's ON CONFLICT Clause?

Using multiple conflict targets in the ON CONFLICT clause

If the table contains multiple unique columns and the INSERT ... ON CONFLICT ... DO UPDATE syntax is required to update other columns in the event of a conflict, you must create a unique index that contains all conflict target columns.

Question:

When trying to use multiple columns as conflict targets in a ON CONFLICT clause, an error occurs because a unique index is required to perform conflict detection. Consider the following example:

<code class="language-sql">INSERT INTO table
...
ON CONFLICT (col1, col2)
DO UPDATE
SET
....</code>
Copy after login
Copy after login

Solution:

To resolve this issue, create a unique index on both columns:

<code class="language-sql">CREATE UNIQUE INDEX idx_t_col1_col2 ON table (col1, col2);</code>
Copy after login

After creating a unique index, the ON CONFLICT clause can specify two columns as conflict targets to achieve the desired update behavior in the event of a conflict:

<code class="language-sql">INSERT INTO table
...
ON CONFLICT (col1, col2)
DO UPDATE
SET
....</code>
Copy after login
Copy after login

Example:

Create a table with unique columns id and a and insert data while handling conflicts:

<code class="language-sql">CREATE TABLE t (id integer, a text, b text);
CREATE UNIQUE INDEX idx_t_id_a ON t (id, a);
INSERT INTO t VALUES (1, 'a', 'foo');
INSERT INTO t VALUES (1, 'a', 'bar') ON CONFLICT (id, a) DO UPDATE SET b = 'bar';</code>
Copy after login

Run query to verify updated data:

<code class="language-sql">SELECT * FROM t;</code>
Copy after login

Output:

<code> id | a |  b  
----+---+-----
  1 | a | bar</code>
Copy after login

The above is the detailed content of How to Handle Multiple Conflict Targets in PostgreSQL's ON CONFLICT Clause?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template