Query and finder options
Options of findAll, findOne, findByPk, findAndCountAll, count, aggregates, include and scopes. Every finder also accepts the common query options.
Options marked postgrelize extension exist only in postgrelize; Sequelize v6 has no such option. This page is generated from the TypeScript declarations and their TSDoc, so it always matches the code.
FindOptionsFindAndCountOptionsFindOrCreateOptionsFindOrBuildOptionsCountOptionsCountWithOptionsAggregateOptionsIncludeOptionsIncludeThroughOptionsSelectOptionsCteFindOptionsCteSearchOptionsCteCycleOptionsTableSampleOptionsSetOperationOptionsWindowOptionsJsonTableOptionsJsonTableColumnOptionsJsonbPathOptionsTsRankOptionsTsHeadlineOptions
FindOptions
Options of the finders (findAll, findOne, findByPk, ...), without association loading details. Extends the query options (transaction, logging, ...) and the SELECT options with finder flags and the PostgreSQL CTE extension. include is typed through IncludeOption. A beforeFind hook may change these options before the query runs.
See also: Model.findAll, WhereOptions.
const opts: FindOptions<User> = {
where: { active: true, age: { [Op.gte]: 18 } },
attributes: ['id', 'name'],
order: [['name', 'ASC']],
limit: 10,
include: [Post],
};
const rows = await User.findAll(opts);| Option | Type | Description |
|---|---|---|
transaction | Transaction | Transaction to run in; null forces running outside the CLS transaction. |
logging | false | LoggingFunction | SQL logger for this query, or false. |
benchmark | boolean | Pass query duration to the logger. |
statementTimeout postgrelize extension | number | statement_timeout for this query only, in milliseconds (non-negative integer; 0 disables it). PostgreSQL cancels the statement with a DatabaseError (code 57014) when it runs longer. Outside a transaction the query runs in its own short transaction; inside one the previous timeout is restored afterwards. PostgreSQL extension. |
retry | Readonly<{ max?: number | undefined; match?: readonly RetryMatch[] | undefined; backoff… | Retries this query when it fails, merged over the instance retry option (Sequelize v6). The connection acquisition is part of the retried work; a query that runs in a transaction is never retried. |
useMaster postgrelize extension | boolean | Force the writer even for SELECTs when read replicas are configured. postgrelize extension. |
replacements | Replacements | Values of ? (array) or :name (object) placeholders written in raw SQL inside the options (where: literal('"a" = :a'), attributes: [[literal(...), 'x']]), as in Sequelize v6. Every value is sent as a bound parameter, never concatenated into the SQL text; arrays expand to a comma separated list of parameters. |
attributes | FindAttributeOptions | Selected attributes. All attributes when omitted. |
order | Order | readonly unknown[] | Sort order: attribute names, [attribute, 'ASC' | 'DESC'] pairs or expressions. |
group | {} | GROUP BY attributes or expressions. |
having | {} | HAVING condition. |
limit | number | Maximum number of rows; null or undefined for no limit. |
offset | number | Number of rows to skip; null or undefined to skip none. |
lock | LockOption | Row lock (FOR UPDATE etc.); requires a transaction. |
skipLocked | boolean | Add SKIP LOCKED to the row lock; only with lock. |
noWait postgrelize extension | boolean | Add NOWAIT to the row lock so the query fails instead of waiting; only with lock. PostgreSQL extension. |
distinctOn postgrelize extension | readonly unknown[] | SELECT DISTINCT ON (...): attributes or expressions. PostgreSQL extension. |
withTies postgrelize extension | boolean | FETCH FIRST limit ROWS WITH TIES instead of LIMIT: also returns the rows that tie with the last one on the order columns. Needs limit and order. PostgreSQL extension. |
sample postgrelize extension | Readonly<{ method: "BERNOULLI" | "SYSTEM"; percent: number; seed?: number | undefined; }> | Read only a random sample of the model table (TABLESAMPLE). PostgreSQL extension. |
where | WhereOptions<T> | Filter rows; see WhereOptions. All rows when omitted. |
raw | boolean | Return plain row objects instead of model instances. Default: false. |
nest | boolean | With raw, build nested objects from dotted keys such as 'posts.title'. Default: false. |
plain | boolean | Return a single row instead of an array (set internally by findOne). Default: false. |
rejectOnEmpty | boolean | Error | Throw EmptyResultError (or the given Error) when no row is found. Default: false. |
paranoid | boolean | For paranoid models: false includes soft-deleted rows. Default: true. |
hooks | boolean | Run beforeFind / afterFind hooks. Default: true. |
include | IncludeOption | Eager-load associations through JOINs (or separate queries for separate includes). |
subQuery | boolean | false disables the sub-query used for limit combined with multi-row includes. |
tableAs | string | Alias of the main table in FROM instead of the model name, so literals and col('alias.x') can refer to it (a v6 internal option that v6's typings omit). Ignored when include is set. |
with postgrelize extension | Readonly<Record<string, Subquery | Readonly<{ query: Subquery | WriteStatement; recursi… | Common table expressions (WITH [RECURSIVE] ...). PostgreSQL extension. |
source postgrelize extension | string | Subquery | Read model rows from this relation instead of the model table: a CTE or table name, or a subquery such as a set operation (a.union(b)), aliased with the model name. Columns are named like the attributes. PostgreSQL extension. |
from postgrelize extension | Readonly<Record<string, FromSourceOption>> | Extra relations (FROM "Model", "alias"), keyed by alias; correlate them in where. PostgreSQL extension. |
FindAndCountOptions
Options of findAndCountAll (Sequelize v6 FindAndCountOptions): the finder options plus the count options distinct and col. The count query reuses where, include, paranoid, distinct, col, group, replacements, transaction and logging. With group, count is an array of GroupedCountResultItem like in v6.
See also: Model.findAndCountAll.
const options: FindAndCountOptions<User> = { where: { active: true }, limit: 10, offset: 20 };
const { count, rows } = await User.findAndCountAll(options);| Option | Type | Description |
|---|---|---|
transaction | Transaction | Transaction to run in; null forces running outside the CLS transaction. |
logging | false | LoggingFunction | SQL logger for this query, or false. |
benchmark | boolean | Pass query duration to the logger. |
statementTimeout postgrelize extension | number | statement_timeout for this query only, in milliseconds (non-negative integer; 0 disables it). PostgreSQL cancels the statement with a DatabaseError (code 57014) when it runs longer. Outside a transaction the query runs in its own short transaction; inside one the previous timeout is restored afterwards. PostgreSQL extension. |
retry | Readonly<{ max?: number | undefined; match?: readonly RetryMatch[] | undefined; backoff… | Retries this query when it fails, merged over the instance retry option (Sequelize v6). The connection acquisition is part of the retried work; a query that runs in a transaction is never retried. |
useMaster postgrelize extension | boolean | Force the writer even for SELECTs when read replicas are configured. postgrelize extension. |
replacements | Replacements | Values of ? (array) or :name (object) placeholders written in raw SQL inside the options (where: literal('"a" = :a'), attributes: [[literal(...), 'x']]), as in Sequelize v6. Every value is sent as a bound parameter, never concatenated into the SQL text; arrays expand to a comma separated list of parameters. |
attributes | FindAttributeOptions | Selected attributes. All attributes when omitted. |
order | Order | readonly unknown[] | Sort order: attribute names, [attribute, 'ASC' | 'DESC'] pairs or expressions. |
group | {} | GROUP BY attributes or expressions. |
having | {} | HAVING condition. |
limit | number | Maximum number of rows; null or undefined for no limit. |
offset | number | Number of rows to skip; null or undefined to skip none. |
lock | LockOption | Row lock (FOR UPDATE etc.); requires a transaction. |
skipLocked | boolean | Add SKIP LOCKED to the row lock; only with lock. |
noWait postgrelize extension | boolean | Add NOWAIT to the row lock so the query fails instead of waiting; only with lock. PostgreSQL extension. |
distinctOn postgrelize extension | readonly unknown[] | SELECT DISTINCT ON (...): attributes or expressions. PostgreSQL extension. |
withTies postgrelize extension | boolean | FETCH FIRST limit ROWS WITH TIES instead of LIMIT: also returns the rows that tie with the last one on the order columns. Needs limit and order. PostgreSQL extension. |
sample postgrelize extension | Readonly<{ method: "BERNOULLI" | "SYSTEM"; percent: number; seed?: number | undefined; }> | Read only a random sample of the model table (TABLESAMPLE). PostgreSQL extension. |
where | WhereOptions<T> | Filter rows; see WhereOptions. All rows when omitted. |
raw | boolean | Return plain row objects instead of model instances. Default: false. |
nest | boolean | With raw, build nested objects from dotted keys such as 'posts.title'. Default: false. |
plain | boolean | Return a single row instead of an array (set internally by findOne). Default: false. |
rejectOnEmpty | boolean | Error | Throw EmptyResultError (or the given Error) when no row is found. Default: false. |
paranoid | boolean | For paranoid models: false includes soft-deleted rows. Default: true. |
hooks | boolean | Run beforeFind / afterFind hooks. Default: true. |
include | IncludeOption | Eager-load associations through JOINs (or separate queries for separate includes). |
subQuery | boolean | false disables the sub-query used for limit combined with multi-row includes. |
tableAs | string | Alias of the main table in FROM instead of the model name, so literals and col('alias.x') can refer to it (a v6 internal option that v6's typings omit). Ignored when include is set. |
with postgrelize extension | Readonly<Record<string, Subquery | Readonly<{ query: Subquery | WriteStatement; recursi… | Common table expressions (WITH [RECURSIVE] ...). PostgreSQL extension. |
source postgrelize extension | string | Subquery | Read model rows from this relation instead of the model table: a CTE or table name, or a subquery such as a set operation (a.union(b)), aliased with the model name. Columns are named like the attributes. PostgreSQL extension. |
from postgrelize extension | Readonly<Record<string, FromSourceOption>> | Extra relations (FROM "Model", "alias"), keyed by alias; correlate them in where. PostgreSQL extension. |
distinct | boolean | Count with count(DISTINCT ...). Default: false. |
col | string | Column to count. Default: * (the primary key with distinct). |
FindOrCreateOptions
Options of findOrCreate and findOrBuild. Extends FindOptions; the where values are also used when creating the row.
See also: Model.findOrCreate.
const [user, created] = await User.findOrCreate({
where: { email: 'a@example.com' },
defaults: { name: 'Ann' },
});| Option | Type | Description |
|---|---|---|
transaction | Transaction | Transaction to run in; null forces running outside the CLS transaction. |
logging | false | LoggingFunction | SQL logger for this query, or false. |
benchmark | boolean | Pass query duration to the logger. |
statementTimeout postgrelize extension | number | statement_timeout for this query only, in milliseconds (non-negative integer; 0 disables it). PostgreSQL cancels the statement with a DatabaseError (code 57014) when it runs longer. Outside a transaction the query runs in its own short transaction; inside one the previous timeout is restored afterwards. PostgreSQL extension. |
retry | Readonly<{ max?: number | undefined; match?: readonly RetryMatch[] | undefined; backoff… | Retries this query when it fails, merged over the instance retry option (Sequelize v6). The connection acquisition is part of the retried work; a query that runs in a transaction is never retried. |
useMaster postgrelize extension | boolean | Force the writer even for SELECTs when read replicas are configured. postgrelize extension. |
replacements | Replacements | Values of ? (array) or :name (object) placeholders written in raw SQL inside the options (where: literal('"a" = :a'), attributes: [[literal(...), 'x']]), as in Sequelize v6. Every value is sent as a bound parameter, never concatenated into the SQL text; arrays expand to a comma separated list of parameters. |
attributes | FindAttributeOptions | Selected attributes. All attributes when omitted. |
order | Order | readonly unknown[] | Sort order: attribute names, [attribute, 'ASC' | 'DESC'] pairs or expressions. |
group | {} | GROUP BY attributes or expressions. |
having | {} | HAVING condition. |
limit | number | Maximum number of rows; null or undefined for no limit. |
offset | number | Number of rows to skip; null or undefined to skip none. |
lock | LockOption | Row lock (FOR UPDATE etc.); requires a transaction. |
skipLocked | boolean | Add SKIP LOCKED to the row lock; only with lock. |
noWait postgrelize extension | boolean | Add NOWAIT to the row lock so the query fails instead of waiting; only with lock. PostgreSQL extension. |
distinctOn postgrelize extension | readonly unknown[] | SELECT DISTINCT ON (...): attributes or expressions. PostgreSQL extension. |
withTies postgrelize extension | boolean | FETCH FIRST limit ROWS WITH TIES instead of LIMIT: also returns the rows that tie with the last one on the order columns. Needs limit and order. PostgreSQL extension. |
sample postgrelize extension | Readonly<{ method: "BERNOULLI" | "SYSTEM"; percent: number; seed?: number | undefined; }> | Read only a random sample of the model table (TABLESAMPLE). PostgreSQL extension. |
where | WhereOptions<T> | Filter rows; see WhereOptions. All rows when omitted. |
raw | boolean | Return plain row objects instead of model instances. Default: false. |
nest | boolean | With raw, build nested objects from dotted keys such as 'posts.title'. Default: false. |
plain | boolean | Return a single row instead of an array (set internally by findOne). Default: false. |
rejectOnEmpty | boolean | Error | Throw EmptyResultError (or the given Error) when no row is found. Default: false. |
paranoid | boolean | For paranoid models: false includes soft-deleted rows. Default: true. |
hooks | boolean | Run beforeFind / afterFind hooks. Default: true. |
include | IncludeOption | Eager-load associations through JOINs (or separate queries for separate includes). |
subQuery | boolean | false disables the sub-query used for limit combined with multi-row includes. |
tableAs | string | Alias of the main table in FROM instead of the model name, so literals and col('alias.x') can refer to it (a v6 internal option that v6's typings omit). Ignored when include is set. |
with postgrelize extension | Readonly<Record<string, Subquery | Readonly<{ query: Subquery | WriteStatement; recursi… | Common table expressions (WITH [RECURSIVE] ...). PostgreSQL extension. |
source postgrelize extension | string | Subquery | Read model rows from this relation instead of the model table: a CTE or table name, or a subquery such as a set operation (a.union(b)), aliased with the model name. Columns are named like the attributes. PostgreSQL extension. |
from postgrelize extension | Readonly<Record<string, FromSourceOption>> | Extra relations (FROM "Model", "alias"), keyed by alias; correlate them in where. PostgreSQL extension. |
defaults | Partial<T> | Values used in addition to the plain equality values of where when the row is created. |
FindOrBuildOptions
Options of findOrBuild (Sequelize v6 FindOrBuildOptions); the same as FindOrCreateOptions.
const options: FindOrBuildOptions<User> = { where: { email: 'a@example.com' }, defaults: { name: 'Ann' } };| Option | Type | Description |
|---|---|---|
transaction | Transaction | Transaction to run in; null forces running outside the CLS transaction. |
logging | false | LoggingFunction | SQL logger for this query, or false. |
benchmark | boolean | Pass query duration to the logger. |
statementTimeout postgrelize extension | number | statement_timeout for this query only, in milliseconds (non-negative integer; 0 disables it). PostgreSQL cancels the statement with a DatabaseError (code 57014) when it runs longer. Outside a transaction the query runs in its own short transaction; inside one the previous timeout is restored afterwards. PostgreSQL extension. |
retry | Readonly<{ max?: number | undefined; match?: readonly RetryMatch[] | undefined; backoff… | Retries this query when it fails, merged over the instance retry option (Sequelize v6). The connection acquisition is part of the retried work; a query that runs in a transaction is never retried. |
useMaster postgrelize extension | boolean | Force the writer even for SELECTs when read replicas are configured. postgrelize extension. |
replacements | Replacements | Values of ? (array) or :name (object) placeholders written in raw SQL inside the options (where: literal('"a" = :a'), attributes: [[literal(...), 'x']]), as in Sequelize v6. Every value is sent as a bound parameter, never concatenated into the SQL text; arrays expand to a comma separated list of parameters. |
attributes | FindAttributeOptions | Selected attributes. All attributes when omitted. |
order | Order | readonly unknown[] | Sort order: attribute names, [attribute, 'ASC' | 'DESC'] pairs or expressions. |
group | {} | GROUP BY attributes or expressions. |
having | {} | HAVING condition. |
limit | number | Maximum number of rows; null or undefined for no limit. |
offset | number | Number of rows to skip; null or undefined to skip none. |
lock | LockOption | Row lock (FOR UPDATE etc.); requires a transaction. |
skipLocked | boolean | Add SKIP LOCKED to the row lock; only with lock. |
noWait postgrelize extension | boolean | Add NOWAIT to the row lock so the query fails instead of waiting; only with lock. PostgreSQL extension. |
distinctOn postgrelize extension | readonly unknown[] | SELECT DISTINCT ON (...): attributes or expressions. PostgreSQL extension. |
withTies postgrelize extension | boolean | FETCH FIRST limit ROWS WITH TIES instead of LIMIT: also returns the rows that tie with the last one on the order columns. Needs limit and order. PostgreSQL extension. |
sample postgrelize extension | Readonly<{ method: "BERNOULLI" | "SYSTEM"; percent: number; seed?: number | undefined; }> | Read only a random sample of the model table (TABLESAMPLE). PostgreSQL extension. |
where | WhereOptions<T> | Filter rows; see WhereOptions. All rows when omitted. |
raw | boolean | Return plain row objects instead of model instances. Default: false. |
nest | boolean | With raw, build nested objects from dotted keys such as 'posts.title'. Default: false. |
plain | boolean | Return a single row instead of an array (set internally by findOne). Default: false. |
rejectOnEmpty | boolean | Error | Throw EmptyResultError (or the given Error) when no row is found. Default: false. |
paranoid | boolean | For paranoid models: false includes soft-deleted rows. Default: true. |
hooks | boolean | Run beforeFind / afterFind hooks. Default: true. |
include | IncludeOption | Eager-load associations through JOINs (or separate queries for separate includes). |
subQuery | boolean | false disables the sub-query used for limit combined with multi-row includes. |
tableAs | string | Alias of the main table in FROM instead of the model name, so literals and col('alias.x') can refer to it (a v6 internal option that v6's typings omit). Ignored when include is set. |
with postgrelize extension | Readonly<Record<string, Subquery | Readonly<{ query: Subquery | WriteStatement; recursi… | Common table expressions (WITH [RECURSIVE] ...). PostgreSQL extension. |
source postgrelize extension | string | Subquery | Read model rows from this relation instead of the model table: a CTE or table name, or a subquery such as a set operation (a.union(b)), aliased with the model name. Columns are named like the attributes. PostgreSQL extension. |
from postgrelize extension | Readonly<Record<string, FromSourceOption>> | Extra relations (FROM "Model", "alias"), keyed by alias; correlate them in where. PostgreSQL extension. |
defaults | Partial<T> | Values used in addition to the plain equality values of where when the row is created. |
CountOptions
Options of count. Includes joins and CTE options; count fires beforeCount hooks.
See also: Model.count.
const total = await Post.count({ where: { published: true }, distinct: true, col: 'authorId' });
const opts: CountOptions<Post> = { group: 'authorId' };
const perAuthor = await Post.count(opts); // [{ authorId, count }, ...]| Option | Type | Description |
|---|---|---|
transaction | Transaction | Transaction to run in; null forces running outside the CLS transaction. |
logging | false | LoggingFunction | SQL logger for this query, or false. |
benchmark | boolean | Pass query duration to the logger. |
statementTimeout postgrelize extension | number | statement_timeout for this query only, in milliseconds (non-negative integer; 0 disables it). PostgreSQL cancels the statement with a DatabaseError (code 57014) when it runs longer. Outside a transaction the query runs in its own short transaction; inside one the previous timeout is restored afterwards. PostgreSQL extension. |
retry | Readonly<{ max?: number | undefined; match?: readonly RetryMatch[] | undefined; backoff… | Retries this query when it fails, merged over the instance retry option (Sequelize v6). The connection acquisition is part of the retried work; a query that runs in a transaction is never retried. |
useMaster postgrelize extension | boolean | Force the writer even for SELECTs when read replicas are configured. postgrelize extension. |
replacements | Replacements | Values of ? (array) or :name (object) placeholders written in raw SQL inside the options (where: literal('"a" = :a'), attributes: [[literal(...), 'x']]), as in Sequelize v6. Every value is sent as a bound parameter, never concatenated into the SQL text; arrays expand to a comma separated list of parameters. |
where | WhereOptions<T> | Filter rows; see WhereOptions. |
col | string | Column to count. Default: * (primary key with distinct). |
distinct | boolean | Use count(DISTINCT ...). Default: false. |
group | string | readonly string[] | Group by attributes; the result becomes an array of { count, ...groups }. |
paranoid | boolean | For paranoid models: false includes soft-deleted rows. Default: true. |
hooks | boolean | Run beforeCount hooks. Default: true. |
include | IncludeOption | Join associations (rows are counted per joined row unless distinct). |
sample postgrelize extension | Readonly<{ method: "BERNOULLI" | "SYSTEM"; percent: number; seed?: number | undefined; }> | Count only a random sample of the table (TABLESAMPLE). PostgreSQL extension. |
with postgrelize extension | Readonly<Record<string, Subquery | Readonly<{ query: Subquery | WriteStatement; recursi… | Common table expressions (WITH [RECURSIVE] ...). PostgreSQL extension. |
source postgrelize extension | string | Subquery | Read model rows from this relation instead of the model table: a CTE or table name, or a subquery such as a set operation (a.union(b)), aliased with the model name. Columns are named like the attributes. PostgreSQL extension. |
from postgrelize extension | Readonly<Record<string, FromSourceOption>> | Extra relations (FROM "Model", "alias"), keyed by alias; correlate them in where. PostgreSQL extension. |
CountWithOptions
CountOptions with a required group, which makes Model.count resolve to one GroupedCountResultItem per group.
See also: Model.count.
const opts: CountWithOptions<Post> = { group: ['authorId'] };
const perAuthor = await Post.count(opts); // [{ authorId, count }, ...]| Option | Type | Description |
|---|---|---|
transaction | Transaction | Transaction to run in; null forces running outside the CLS transaction. |
logging | false | LoggingFunction | SQL logger for this query, or false. |
benchmark | boolean | Pass query duration to the logger. |
statementTimeout postgrelize extension | number | statement_timeout for this query only, in milliseconds (non-negative integer; 0 disables it). PostgreSQL cancels the statement with a DatabaseError (code 57014) when it runs longer. Outside a transaction the query runs in its own short transaction; inside one the previous timeout is restored afterwards. PostgreSQL extension. |
retry | Readonly<{ max?: number | undefined; match?: readonly RetryMatch[] | undefined; backoff… | Retries this query when it fails, merged over the instance retry option (Sequelize v6). The connection acquisition is part of the retried work; a query that runs in a transaction is never retried. |
useMaster postgrelize extension | boolean | Force the writer even for SELECTs when read replicas are configured. postgrelize extension. |
replacements | Replacements | Values of ? (array) or :name (object) placeholders written in raw SQL inside the options (where: literal('"a" = :a'), attributes: [[literal(...), 'x']]), as in Sequelize v6. Every value is sent as a bound parameter, never concatenated into the SQL text; arrays expand to a comma separated list of parameters. |
where | WhereOptions<T> | Filter rows; see WhereOptions. |
col | string | Column to count. Default: * (primary key with distinct). |
distinct | boolean | Use count(DISTINCT ...). Default: false. |
group | (string | readonly string[] | undefined) & (string | readonly string[]) | Group by attributes; the result becomes an array of { count, ...groups }. Group by attributes; the result is an array of { count, ...groups }. |
paranoid | boolean | For paranoid models: false includes soft-deleted rows. Default: true. |
hooks | boolean | Run beforeCount hooks. Default: true. |
include | IncludeOption | Join associations (rows are counted per joined row unless distinct). |
sample postgrelize extension | Readonly<{ method: "BERNOULLI" | "SYSTEM"; percent: number; seed?: number | undefined; }> | Count only a random sample of the table (TABLESAMPLE). PostgreSQL extension. |
with postgrelize extension | Readonly<Record<string, Subquery | Readonly<{ query: Subquery | WriteStatement; recursi… | Common table expressions (WITH [RECURSIVE] ...). PostgreSQL extension. |
source postgrelize extension | string | Subquery | Read model rows from this relation instead of the model table: a CTE or table name, or a subquery such as a set operation (a.union(b)), aliased with the model name. Columns are named like the attributes. PostgreSQL extension. |
from postgrelize extension | Readonly<Record<string, FromSourceOption>> | Extra relations (FROM "Model", "alias"), keyed by alias; correlate them in where. PostgreSQL extension. |
AggregateOptions
Options of aggregate, max, min and sum. Same as CountOptions plus plain.
See also: Model.aggregate.
const opts: AggregateOptions<Product> = { where: { active: true }, paranoid: false };
const highest = await Product.max('price', opts);| Option | Type | Description |
|---|---|---|
transaction | Transaction | Transaction to run in; null forces running outside the CLS transaction. |
logging | false | LoggingFunction | SQL logger for this query, or false. |
benchmark | boolean | Pass query duration to the logger. |
statementTimeout postgrelize extension | number | statement_timeout for this query only, in milliseconds (non-negative integer; 0 disables it). PostgreSQL cancels the statement with a DatabaseError (code 57014) when it runs longer. Outside a transaction the query runs in its own short transaction; inside one the previous timeout is restored afterwards. PostgreSQL extension. |
retry | Readonly<{ max?: number | undefined; match?: readonly RetryMatch[] | undefined; backoff… | Retries this query when it fails, merged over the instance retry option (Sequelize v6). The connection acquisition is part of the retried work; a query that runs in a transaction is never retried. |
useMaster postgrelize extension | boolean | Force the writer even for SELECTs when read replicas are configured. postgrelize extension. |
replacements | Replacements | Values of ? (array) or :name (object) placeholders written in raw SQL inside the options (where: literal('"a" = :a'), attributes: [[literal(...), 'x']]), as in Sequelize v6. Every value is sent as a bound parameter, never concatenated into the SQL text; arrays expand to a comma separated list of parameters. |
where | WhereOptions<T> | Filter rows; see WhereOptions. |
col | string | Column to count. Default: * (primary key with distinct). |
distinct | boolean | Use count(DISTINCT ...). Default: false. |
group | string | readonly string[] | Group by attributes; the result becomes an array of { count, ...groups }. |
paranoid | boolean | For paranoid models: false includes soft-deleted rows. Default: true. |
hooks | boolean | Run beforeCount hooks. Default: true. |
include | IncludeOption | Join associations (rows are counted per joined row unless distinct). |
sample postgrelize extension | Readonly<{ method: "BERNOULLI" | "SYSTEM"; percent: number; seed?: number | undefined; }> | Count only a random sample of the table (TABLESAMPLE). PostgreSQL extension. |
with postgrelize extension | Readonly<Record<string, Subquery | Readonly<{ query: Subquery | WriteStatement; recursi… | Common table expressions (WITH [RECURSIVE] ...). PostgreSQL extension. |
source postgrelize extension | string | Subquery | Read model rows from this relation instead of the model table: a CTE or table name, or a subquery such as a set operation (a.union(b)), aliased with the model name. Columns are named like the attributes. PostgreSQL extension. |
from postgrelize extension | Readonly<Record<string, FromSourceOption>> | Extra relations (FROM "Model", "alias"), keyed by alias; correlate them in where. PostgreSQL extension. |
plain | boolean | Return all rows exactly as the driver delivers them (numeric results such as sum are strings, like in Sequelize v6) instead of one converted value. Default: true. |
dataType | DataTypeInput | Data type that the single result is converted to: INTEGER / BIGINT give a number, FLOAT / DECIMAL a float, DATE a Date. Defaults to the type of the aggregated attribute, or FLOAT for '*'. Ignored with plain: false. |
IncludeOptions
One include entry (Sequelize v6 IncludeOptions): which association to load and how. Name the association with model, as or association. Eager loading uses JOINs (see the guide), except separate, which runs another query.
See also: FindOptions.
const opts: IncludeOptions = {
model: Post,
as: 'posts',
where: { published: true },
required: false,
attributes: ['id', 'title'],
include: [{ model: Tag }],
};
const users = await User.findAll({ include: [opts] });| Option | Type | Description |
|---|---|---|
model | Model | Associated model; the association is looked up by model (and as). |
as | string | Alias of the association, as given when it was defined. |
association | string | Readonly<{ associationType: AssociationType; source: ModelStatic<AnyModel>; ta… | Association object or alias. |
where | {} | Filter on the included rows; makes the include required unless required: false. See WhereOptions. |
on | {} | Custom ON condition of the join; replaces the condition derived from the association keys. Not used by belongsToMany includes (the junction joins keep their key conditions). See WhereOptions. |
required | boolean | INNER JOIN (true) or LEFT OUTER JOIN (false). |
right | boolean | Use RIGHT OUTER JOIN. Default: false. |
attributes | FindAttributeOptions | Selected attributes. |
include | IncludeOption | Nested includes. |
separate | boolean | Load a hasMany association with a separate query instead of a JOIN. Default: false. |
through | Readonly<{ attributes?: FindAttributeOptions | undefined; where?: unknown; }> | Junction options for belongsToMany. |
lateral postgrelize extension | boolean | Fetch only the first limit rows per parent in the database (JOIN LATERAL over the parent keys) instead of loading every child and trimming in memory. Needs separate and limit. PostgreSQL extension. Default: false. |
order | {} | Order of a separate include. |
limit | number | Maximum rows per include of a separate include. |
paranoid | boolean | For paranoid targets: false includes soft-deleted rows. Default: true. |
all | boolean | Include every association of the model ({ all: true }). Default: false. |
IncludeThroughOptions
Options of the junction table of an included belongsToMany association.
const through: IncludeThroughOptions = { attributes: ['role'], where: { role: 'owner' } };
const rows = await Project.findAll({ include: [{ model: User, through }] });| Option | Type | Description |
|---|---|---|
attributes | FindAttributeOptions | Junction attributes to select ([] for none). Default: all. |
where | {} | Filter on junction rows; see WhereOptions. |
SelectOptions
Options that shape a SELECT statement, shared by finders and copyTo. Finders extend this with flags such as raw and include (FindOptions).
const opts: SelectOptions = {
attributes: ['status', [fn('count', col('id')), 'n']],
group: ['status'],
having: { n: { [Op.gt]: 1 } },
order: [['status', 'DESC']],
limit: 20,
offset: 40,
};| Option | Type | Description |
|---|---|---|
where | {} | Filter; finders type this as WhereOptions. |
attributes | FindAttributeOptions | Selected attributes. All attributes when omitted. |
order | Order | readonly unknown[] | Sort order: attribute names, [attribute, 'ASC' | 'DESC'] pairs or expressions. |
group | {} | GROUP BY attributes or expressions. |
having | {} | HAVING condition. |
limit | number | Maximum number of rows; null or undefined for no limit. |
offset | number | Number of rows to skip; null or undefined to skip none. |
lock | LockOption | Row lock (FOR UPDATE etc.); requires a transaction. |
skipLocked | boolean | Add SKIP LOCKED to the row lock; only with lock. |
noWait postgrelize extension | boolean | Add NOWAIT to the row lock so the query fails instead of waiting; only with lock. PostgreSQL extension. |
distinctOn postgrelize extension | readonly unknown[] | SELECT DISTINCT ON (...): attributes or expressions. PostgreSQL extension. |
withTies postgrelize extension | boolean | FETCH FIRST limit ROWS WITH TIES instead of LIMIT: also returns the rows that tie with the last one on the order columns. Needs limit and order. PostgreSQL extension. |
sample postgrelize extension | Readonly<{ method: "BERNOULLI" | "SYSTEM"; percent: number; seed?: number | undefined; }> | Read only a random sample of the model table (TABLESAMPLE). PostgreSQL extension. |
CteFindOptions postgrelize extension
CTE-related find options. PostgreSQL extension. Combined into FindOptions and CountOptions.
const opts: CteFindOptions = {
with: { recent: { query: Post.subquery({ where: { published: true } }) } },
source: 'recent',
};| Option | Type | Description |
|---|---|---|
with postgrelize extension | Readonly<Record<string, Subquery | Readonly<{ query: Subquery | WriteStatement; recursi… | Common table expressions (WITH [RECURSIVE] ...). PostgreSQL extension. |
source postgrelize extension | string | Subquery | Read model rows from this relation instead of the model table: a CTE or table name, or a subquery such as a set operation (a.union(b)), aliased with the model name. Columns are named like the attributes. PostgreSQL extension. |
from postgrelize extension | Readonly<Record<string, FromSourceOption>> | Extra relations (FROM "Model", "alias"), keyed by alias; correlate them in where. PostgreSQL extension. |
CteSearchOptions postgrelize extension
search of a recursive CTE definition. PostgreSQL extension.
const search: CteSearchOptions = { by: ['id'], mode: 'breadth', set: 'ordercol' };| Option | Type | Description |
|---|---|---|
by | readonly string[] | Columns of the CTE that define the order. |
mode | "breadth" | "depth" | Traversal order. Default: 'depth'. |
set | string | Name of the added ordering column. |
CteCycleOptions postgrelize extension
cycle of a recursive CTE definition. PostgreSQL extension.
const cycle: CteCycleOptions = { columns: ['id'], set: 'is_cycle', using: 'path' };| Option | Type | Description |
|---|---|---|
columns | readonly string[] | Columns that identify a visited row. |
set | string | Name of the added boolean column that is true on the row that closes a cycle. |
using | string | Name of the added array column with the path of visited keys (required: PostgreSQL 16 and 17 need it). |
TableSampleOptions postgrelize extension
TABLESAMPLE of a table. PostgreSQL extension.
const sample: TableSampleOptions = { method: 'BERNOULLI', percent: 10, seed: 42 };
const rows = await Post.findAll({ sample });| Option | Type | Description |
|---|---|---|
method | "BERNOULLI" | "SYSTEM" | Sampling method: BERNOULLI (row by row) or SYSTEM (block by block, faster). |
percent | number | Percentage of the table to read, from 0 to 100. Bound as a parameter. |
seed | number | REPEATABLE seed: the same seed returns the same sample while the data does not change. |
SetOperationOptions postgrelize extension
Options of Subquery.union, Subquery.intersect and Subquery.except. PostgreSQL extension.
const opts: SetOperationOptions = { all: true };
const rows = Post.subquery({ attributes: ['userId'] }).union(Task.subquery({ attributes: ['userId'] }), opts);| Option | Type | Description |
|---|---|---|
all | boolean | Keep duplicate rows (UNION ALL, INTERSECT ALL, EXCEPT ALL). Default: false. |
WindowOptions postgrelize extension
Window definition of over. PostgreSQL extension.
const window: WindowOptions = { partitionBy: ['userId'], orderBy: [['createdAt', 'DESC']] };| Option | Type | Description |
|---|---|---|
partitionBy | readonly unknown[] | PARTITION BY attributes or expressions. |
orderBy | readonly unknown[] | ORDER BY items: attribute, [attribute, direction] or expression. |
JsonTableOptions postgrelize extension
JSON_TABLE source: turns a JSON document into rows. PostgreSQL extension. Needs PostgreSQL 17.
const source: JsonTableOptions = {
doc: { items: [{ sku: 'a', qty: 2 }] },
path: '$.items[*]',
columns: [{ name: 'sku', type: 'text' }, { name: 'qty', type: 'integer' }],
};| Option | Type | Description |
|---|---|---|
doc | {} | Document: a JSON value (bound as jsonb) or an expression such as col('Order.data'). |
path | string | jsonpath that selects the rows; rendered as an escaped string literal. |
columns | readonly Readonly<{ name: string; ordinality?: boolean | undefined; type?: string | und… | Output columns. |
JsonTableColumnOptions postgrelize extension
One column of a JsonTableOptions. PostgreSQL extension.
const columns: JsonTableColumnOptions[] = [
{ name: 'position', ordinality: true },
{ name: 'qty', type: 'integer', path: '$.quantity' },
{ name: 'hasNote', exists: true, path: '$.note' },
];| Option | Type | Description |
|---|---|---|
name | string | Output column name. |
ordinality | boolean | Number the rows (FOR ORDINALITY); no type or path. |
type | string | Column type: one of the cast types (integer, text, jsonb, timestamptz, …). |
path | string | jsonpath of the value, relative to the row; defaults to the column name. |
exists | boolean | Return whether the path matches (EXISTS); type defaults to boolean. |
JsonbPathOptions postgrelize extension
Options of jsonbPath. PostgreSQL extension.
const options: JsonbPathOptions = { vars: { min: 10 }, silent: true };| Option | Type | Description |
|---|---|---|
vars | Readonly<Record<string, unknown>> | Values of the $name variables of the path; serialized to jsonb and bound as a parameter. |
silent | boolean | Suppresses missing-key and type errors of the path (the silent argument). |
tz | boolean | Uses the _tz variant, which converts between time zones (stable instead of immutable). |
TsRankOptions postgrelize extension
Options of tsRank. PostgreSQL extension.
const options: TsRankOptions = { cd: true, weights: [0.1, 0.2, 0.4, 1], normalization: 1 };| Option | Type | Description |
|---|---|---|
cd | boolean | Uses ts_rank_cd (cover density) instead of ts_rank. |
weights | readonly [number, number, number, number] | Weights of the labels D, C, B, A, in this order. |
normalization | number | Normalization bit mask, an integer from 0 to 63. |
TsHeadlineOptions postgrelize extension
Options of tsHeadline. PostgreSQL extension.
const options: TsHeadlineOptions = { config: 'english', options: 'StartSel=<b>, StopSel=</b>' };| Option | Type | Description |
|---|---|---|
config | string | Text search configuration, e.g. 'english'. |
options | string | ts_headline options string, e.g. 'StartSel=<b>, StopSel=</b>'. Bound as a parameter. |