Home > Backend Development > Golang > How to Perform Multi-Row Bulk Updates in PostgreSQL with Go?

How to Perform Multi-Row Bulk Updates in PostgreSQL with Go?

Susan Sarandon
Release: 2024-12-11 06:14:10
Original
738 people have browsed it

How to Perform Multi-Row Bulk Updates in PostgreSQL with Go?

Multi-Row Bulk Updates in PostgreSQL with Go

When working with large datasets, it's often necessary to update multiple rows in a database table in a single operation. This can optimize performance and reduce code complexity. In PostgreSQL, bulk updates can be achieved using various approaches.

One approach involves using a derived table to construct a set of values to update. By utilizing the FROM clause, you can specify the values for each row that needs to be updated. For example:

UPDATE t
SET column_a = v.column_a,
    column_b = v.column_b
FROM (VALUES (1, 'FINISH', 1234),
                 (2, 'UNFINISH', 3124)
         ) v(id, column_a, column_b)
WHERE v.id = t.id;
Copy after login

The derived table v contains the pairs of (id, column_a, column_b) representing the updates for each row. The UPDATE statement then uses the WHERE clause to match the id values in v with those in the target table t.

In Go, you can execute this query using a prepared statement:

const updateBulkSQL = `
UPDATE t
SET column_a = v.column_a,
    column_b = v.column_b
FROM (VALUES (, , ),
                 (, , )
         ) v(id, column_a, column_b)
WHERE v.id = t.id;
`

func main() {
    db, err := sql.Open("postgres", "")
    if err != nil {
        // Handle error
    }

    stmt, err := db.Prepare(updateBulkSQL)
    if err != nil {
        // Handle error
    }

    _, err = stmt.Exec(1, "FINISH", 1234, 2, "UNFINISH", 3124)
    if err != nil {
        // Handle error
    }
}
Copy after login

This approach provides a concise and efficient way to perform bulk updates in PostgreSQL, allowing you to update multiple rows in a single query without having to execute separate queries for each row.

The above is the detailed content of How to Perform Multi-Row Bulk Updates in PostgreSQL with Go?. 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