Home > Database > Mysql Tutorial > How Can I Update Multiple Rows in a Single PostgreSQL Query?

How Can I Update Multiple Rows in a Single PostgreSQL Query?

Linda Hamilton
Release: 2025-01-12 22:42:43
Original
508 people have browsed it

How Can I Update Multiple Rows in a Single PostgreSQL Query?

PostgreSQL single query updates multiple rows

This article explores how to update multiple rows of data using a single query in a PostgreSQL database. Although PostgreSQL does not support updating multiple rows directly, there are several ways to achieve this goal.

One approach is to use a combination of the UPDATE ... FROM syntax and a mapping table. This allows multiple columns to be updated and provides greater flexibility. The following code demonstrates this approach:

<code class="language-sql">UPDATE test AS t
SET column_a = c.column_a
FROM (VALUES
    ('123', 1),
    ('345', 2)
) AS c(column_b, column_a)
WHERE c.column_b = t.column_b;</code>
Copy after login

More columns can be added as needed:

<code class="language-sql">UPDATE test AS t
SET column_a = c.column_a,
    column_c = c.column_c
FROM (VALUES
    ('123', 1, '---'),
    ('345', 2, '+++')
) AS c(column_b, column_a, column_c)
WHERE c.column_b = t.column_b;</code>
Copy after login

Another, cleaner approach is to use PostgreSQL's INSERT ... ON CONFLICT ... UPDATE syntax, which combines insert and update functionality into a single query. However, this method requires creating a unique index on the column that identifies the row to be updated.

The above is the detailed content of How Can I Update Multiple Rows in a Single PostgreSQL Query?. 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