PostgreSQL multi-row updates in Node.js

The example below is based on library pg-promise, and its method helpers.update:

// library initialization, usually placed in its own module:
const pgp = require('pg-promise')({
    capSQL: true // capitalize all generated SQL
});

const db = pgp(/*your connection details*/);

// records to be updated:
const updateData = [
    {id: 1, value: 1234},
    {id: 2, value: 5678},
    {id: 3, value: 91011}
];

// declare your ColumnSet once, and then reuse it:
const cs = new pgp.helpers.ColumnSet(['?id', 'value'], {table: 'fit_ratios'});

// generating the update query where it is needed:
const update = pgp.helpers.update(updateData, cs) + ' WHERE v.id = t.id';
//=> UPDATE "fit_ratios" AS t SET "value"=v."value"
//   FROM (VALUES(1,1234),(2,5678),(3,91011))
//   AS v("id","value") WHERE v.id = t.id

// executing the query:
await db.none(update);

This method of generating multi-row updates can be characterized as:

  • very fast, as it relies on type ColumnSet that implements smart caching for query generation
  • completely safe, as all data types are going through the library’s query formatting engine to make sure everything is formatted and escaped correctly.
  • very flexible, due to advanced ColumnConfig syntax supported for the columns definition.
  • very easy to use, due to the simplified interface implemented by pg-promise.

Note that we use ? in front of column id to indicate that the column is part of the condition, but not to be updated. For complete column syntax see class Column and ColumnConfig structure.


Related question: Multi-row insert with pg-promise.

Leave a Comment