Skip to content
Christoph Herrmann edited this page Nov 13, 2019 · 8 revisions

The return value is the count of the rows affected by the update located in result.rowCount of the pg result object.

const rowCount = await sql.update(
  'users',
  { email: 'new email', name: 'new name' },
  { email: 'old email', name: 'old name' }
)

// text: UPDATE "users" SET "email" = $1, "name" = $2 
//   WHERE "email" = $3 AND "name" = $4
// values: ['new email', 'new name', 'old email', 'old name']

table can also be given as an array with the schema. Otherwise if it's defined the defaultSchema option will be used.

Use SQL Tag updating data

For more complex update queries the SQL Tag can be used.

const newEmail = 'new email'
const newName = 'new name'
const oldEmail = 'old email'
const oldName = 'old name'

const rowCount = await sql.update(
  sql`
    UPDATE "users" SET "email" = ${newEmail}, "name" = ${newName}
      WHERE "email" = ${oldEmail} AND "name" = ${oldName}
  `
)

// text: UPDATE "users" SET "email" = $1, "name" = $2 
//   WHERE "email" = $3 AND "name" = $4
// values: ['new email', 'new name', 'old email', 'old name']

Where .update() throws an error if no conditions are given, .updateAll() comes in place allowing to be called without conditions.

Clone this wiki locally