Skip to main content

Insert

Builds an INSERT INTO ... VALUES (...) (or INSERT INTO ... (SELECT ...)) query. Extends ReturningQuery (which extends Query). See the Insert Statement guide for a full walkthrough.

Constructor

Insert(tableName: string | Raw, input: Record<string, any> | Select | Raw): Insert
new Insert(tableName: string | Raw, input: Record<string, any> | Select | Raw): Insert

Dual-callable. Validates both arguments and throws a TypeError if they don't match:

  • tableName must be a non-empty string or a Raw instance, otherwise: "String or Raw instance required as first argument (tableName) for Insert".
  • input must be a plain object, a Select, or a Raw instance (not an array), otherwise: "Object or Select instance required as second argument (input) for Insert".
import { Insert } from '@sqb/builder';

Insert('customers', { given_name: 'John', family_name: 'Doe' });
Insert('customers', Select('id', 'name').from('staging')); // INSERT ... SELECT

Properties

KeyTypeReadonlyDescription
_typeSerializationType.INSERT_QUERYYesDiscriminates this node during serialization.
_tableTableName | RawNoThe target table, set from the constructor's tableName argument.
_inputRecord<string, any> | Select | RawNoThe column values / sub-select set from the constructor's input argument.

Plus everything inherited from ReturningQuery (_returningColumns, _comment, _params, EventEmitter).

Methods

Inherits all of its behavior from ReturningQuery (.returning()) and Query (.generate(), .values(), .comment()). Insert adds no methods of its own beyond its constructor validation and serialization logic.

import { Insert, Param } from '@sqb/builder';

const query = Insert('customers', { id: Param('id'), name: Param('name') })
.returning('id');

query.generate({ params: { id: 1, name: 'Abc' } });
// sql: insert into customers (id, name) values (:id, :name) returning id

See also