Skip to main content

Update Statement

Update(tableName, input) builds an UPDATE ... SET ... statement.

import { Update, Eq } from '@sqb/builder';

const query = Update('customers', { name: 'Jane' }).where(Eq('id', 1));
query.generate().sql;
// update customers set name = 'Jane' where id = 1

Update is dual-callable and extends ReturningQuery (itself extending Query) — see the Update class reference for the full member list.

Arguments

Update(tableName: string | TableName | Raw, input: Record<string, any> | Select | Raw): Update
  • tableName — a table name string, a TableName instance, or a Raw fragment. Anything else throws a TypeError.
  • input — a plain object of column/value pairs, a Select, or a Raw fragment. An array or any other non-object value throws a TypeError.
Update(null, { id: 1 });
// TypeError: String or Raw instance required as first argument (tableName) for Update

Update('customers', 'not-an-object');
// TypeError: Object or Raw instance required as second argument (input) for Update

where()

.where(...) behaves exactly like Select's — conditions accumulate into an implicit top-level And. See Operators and Conditions. Omitting .where() updates every row in the table, just like plain SQL.

Column values

A value can be a literal, a Param, or even a sub-Select:

Update('customers', { id: 2, name: Select('name').from('staging') }).where(Eq('id', 1));
// update customers set id = 2, name = (select name from staging) where id = 1

Reserved-word column names are escaped in the SET clause automatically:

Update('customers', { id: 2, with: 'aaa' }).where(Eq('id', 1)).generate().sql;
// update customers set id = 2, "with" = 'aaa' where id = 1

values()

Same as Insert.values(obj) merges bind parameter values, equivalent to generate({ params }):

Update('customers', { id: Param('id'), name: Param('name') })
.values({ id: 1, name: 'Abc' })
.generate().sql;
// update customers set id = :id, name = :name

returning()

Inherited from ReturningQuery:

Update('customers', { id: 1, name: 'aaa' }).returning('id', 'name as n').generate().sql;
// update customers set id = 1, name = 'aaa' returning id, name as n

See Raw SQL and Parameters and Generating SQL per dialect for more on Param and .generate() options.