Skip to content

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.

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.

ts
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);
OptionTypeDescription
transactionTransactionTransaction to run in; null forces running outside the CLS transaction.
loggingfalse | LoggingFunctionSQL logger for this query, or false.
benchmarkbooleanPass query duration to the logger.
statementTimeout postgrelize extensionnumberstatement_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.
retryReadonly<{ 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 extensionbooleanForce the writer even for SELECTs when read replicas are configured. postgrelize extension.
replacementsReplacementsValues 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.
attributesFindAttributeOptionsSelected attributes. All attributes when omitted.
orderOrder | readonly unknown[]Sort order: attribute names, [attribute, 'ASC' | 'DESC'] pairs or expressions.
group{}GROUP BY attributes or expressions.
having{}HAVING condition.
limitnumberMaximum number of rows; null or undefined for no limit.
offsetnumberNumber of rows to skip; null or undefined to skip none.
lockLockOptionRow lock (FOR UPDATE etc.); requires a transaction.
skipLockedbooleanAdd SKIP LOCKED to the row lock; only with lock.
noWait postgrelize extensionbooleanAdd NOWAIT to the row lock so the query fails instead of waiting; only with lock. PostgreSQL extension.
distinctOn postgrelize extensionreadonly unknown[]SELECT DISTINCT ON (...): attributes or expressions. PostgreSQL extension.
withTies postgrelize extensionbooleanFETCH 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 extensionReadonly<{ method: "BERNOULLI" | "SYSTEM"; percent: number; seed?: number | undefined; }>Read only a random sample of the model table (TABLESAMPLE). PostgreSQL extension.
whereWhereOptions<T>Filter rows; see WhereOptions. All rows when omitted.
rawbooleanReturn plain row objects instead of model instances. Default: false.
nestbooleanWith raw, build nested objects from dotted keys such as 'posts.title'. Default: false.
plainbooleanReturn a single row instead of an array (set internally by findOne). Default: false.
rejectOnEmptyboolean | ErrorThrow EmptyResultError (or the given Error) when no row is found. Default: false.
paranoidbooleanFor paranoid models: false includes soft-deleted rows. Default: true.
hooksbooleanRun beforeFind / afterFind hooks. Default: true.
includeIncludeOptionEager-load associations through JOINs (or separate queries for separate includes).
subQuerybooleanfalse disables the sub-query used for limit combined with multi-row includes.
tableAsstringAlias 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 extensionReadonly<Record<string, Subquery | Readonly<{ query: Subquery | WriteStatement; recursi…Common table expressions (WITH [RECURSIVE] ...). PostgreSQL extension.
source postgrelize extensionstring | SubqueryRead 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 extensionReadonly<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.

ts
const options: FindAndCountOptions<User> = { where: { active: true }, limit: 10, offset: 20 };
const { count, rows } = await User.findAndCountAll(options);
OptionTypeDescription
transactionTransactionTransaction to run in; null forces running outside the CLS transaction.
loggingfalse | LoggingFunctionSQL logger for this query, or false.
benchmarkbooleanPass query duration to the logger.
statementTimeout postgrelize extensionnumberstatement_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.
retryReadonly<{ 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 extensionbooleanForce the writer even for SELECTs when read replicas are configured. postgrelize extension.
replacementsReplacementsValues 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.
attributesFindAttributeOptionsSelected attributes. All attributes when omitted.
orderOrder | readonly unknown[]Sort order: attribute names, [attribute, 'ASC' | 'DESC'] pairs or expressions.
group{}GROUP BY attributes or expressions.
having{}HAVING condition.
limitnumberMaximum number of rows; null or undefined for no limit.
offsetnumberNumber of rows to skip; null or undefined to skip none.
lockLockOptionRow lock (FOR UPDATE etc.); requires a transaction.
skipLockedbooleanAdd SKIP LOCKED to the row lock; only with lock.
noWait postgrelize extensionbooleanAdd NOWAIT to the row lock so the query fails instead of waiting; only with lock. PostgreSQL extension.
distinctOn postgrelize extensionreadonly unknown[]SELECT DISTINCT ON (...): attributes or expressions. PostgreSQL extension.
withTies postgrelize extensionbooleanFETCH 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 extensionReadonly<{ method: "BERNOULLI" | "SYSTEM"; percent: number; seed?: number | undefined; }>Read only a random sample of the model table (TABLESAMPLE). PostgreSQL extension.
whereWhereOptions<T>Filter rows; see WhereOptions. All rows when omitted.
rawbooleanReturn plain row objects instead of model instances. Default: false.
nestbooleanWith raw, build nested objects from dotted keys such as 'posts.title'. Default: false.
plainbooleanReturn a single row instead of an array (set internally by findOne). Default: false.
rejectOnEmptyboolean | ErrorThrow EmptyResultError (or the given Error) when no row is found. Default: false.
paranoidbooleanFor paranoid models: false includes soft-deleted rows. Default: true.
hooksbooleanRun beforeFind / afterFind hooks. Default: true.
includeIncludeOptionEager-load associations through JOINs (or separate queries for separate includes).
subQuerybooleanfalse disables the sub-query used for limit combined with multi-row includes.
tableAsstringAlias 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 extensionReadonly<Record<string, Subquery | Readonly<{ query: Subquery | WriteStatement; recursi…Common table expressions (WITH [RECURSIVE] ...). PostgreSQL extension.
source postgrelize extensionstring | SubqueryRead 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 extensionReadonly<Record<string, FromSourceOption>>Extra relations (FROM "Model", "alias"), keyed by alias; correlate them in where. PostgreSQL extension.
distinctbooleanCount with count(DISTINCT ...). Default: false.
colstringColumn 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.

ts
const [user, created] = await User.findOrCreate({
  where: { email: 'a@example.com' },
  defaults: { name: 'Ann' },
});
OptionTypeDescription
transactionTransactionTransaction to run in; null forces running outside the CLS transaction.
loggingfalse | LoggingFunctionSQL logger for this query, or false.
benchmarkbooleanPass query duration to the logger.
statementTimeout postgrelize extensionnumberstatement_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.
retryReadonly<{ 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 extensionbooleanForce the writer even for SELECTs when read replicas are configured. postgrelize extension.
replacementsReplacementsValues 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.
attributesFindAttributeOptionsSelected attributes. All attributes when omitted.
orderOrder | readonly unknown[]Sort order: attribute names, [attribute, 'ASC' | 'DESC'] pairs or expressions.
group{}GROUP BY attributes or expressions.
having{}HAVING condition.
limitnumberMaximum number of rows; null or undefined for no limit.
offsetnumberNumber of rows to skip; null or undefined to skip none.
lockLockOptionRow lock (FOR UPDATE etc.); requires a transaction.
skipLockedbooleanAdd SKIP LOCKED to the row lock; only with lock.
noWait postgrelize extensionbooleanAdd NOWAIT to the row lock so the query fails instead of waiting; only with lock. PostgreSQL extension.
distinctOn postgrelize extensionreadonly unknown[]SELECT DISTINCT ON (...): attributes or expressions. PostgreSQL extension.
withTies postgrelize extensionbooleanFETCH 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 extensionReadonly<{ method: "BERNOULLI" | "SYSTEM"; percent: number; seed?: number | undefined; }>Read only a random sample of the model table (TABLESAMPLE). PostgreSQL extension.
whereWhereOptions<T>Filter rows; see WhereOptions. All rows when omitted.
rawbooleanReturn plain row objects instead of model instances. Default: false.
nestbooleanWith raw, build nested objects from dotted keys such as 'posts.title'. Default: false.
plainbooleanReturn a single row instead of an array (set internally by findOne). Default: false.
rejectOnEmptyboolean | ErrorThrow EmptyResultError (or the given Error) when no row is found. Default: false.
paranoidbooleanFor paranoid models: false includes soft-deleted rows. Default: true.
hooksbooleanRun beforeFind / afterFind hooks. Default: true.
includeIncludeOptionEager-load associations through JOINs (or separate queries for separate includes).
subQuerybooleanfalse disables the sub-query used for limit combined with multi-row includes.
tableAsstringAlias 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 extensionReadonly<Record<string, Subquery | Readonly<{ query: Subquery | WriteStatement; recursi…Common table expressions (WITH [RECURSIVE] ...). PostgreSQL extension.
source postgrelize extensionstring | SubqueryRead 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 extensionReadonly<Record<string, FromSourceOption>>Extra relations (FROM "Model", "alias"), keyed by alias; correlate them in where. PostgreSQL extension.
defaultsPartial<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.

ts
const options: FindOrBuildOptions<User> = { where: { email: 'a@example.com' }, defaults: { name: 'Ann' } };
OptionTypeDescription
transactionTransactionTransaction to run in; null forces running outside the CLS transaction.
loggingfalse | LoggingFunctionSQL logger for this query, or false.
benchmarkbooleanPass query duration to the logger.
statementTimeout postgrelize extensionnumberstatement_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.
retryReadonly<{ 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 extensionbooleanForce the writer even for SELECTs when read replicas are configured. postgrelize extension.
replacementsReplacementsValues 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.
attributesFindAttributeOptionsSelected attributes. All attributes when omitted.
orderOrder | readonly unknown[]Sort order: attribute names, [attribute, 'ASC' | 'DESC'] pairs or expressions.
group{}GROUP BY attributes or expressions.
having{}HAVING condition.
limitnumberMaximum number of rows; null or undefined for no limit.
offsetnumberNumber of rows to skip; null or undefined to skip none.
lockLockOptionRow lock (FOR UPDATE etc.); requires a transaction.
skipLockedbooleanAdd SKIP LOCKED to the row lock; only with lock.
noWait postgrelize extensionbooleanAdd NOWAIT to the row lock so the query fails instead of waiting; only with lock. PostgreSQL extension.
distinctOn postgrelize extensionreadonly unknown[]SELECT DISTINCT ON (...): attributes or expressions. PostgreSQL extension.
withTies postgrelize extensionbooleanFETCH 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 extensionReadonly<{ method: "BERNOULLI" | "SYSTEM"; percent: number; seed?: number | undefined; }>Read only a random sample of the model table (TABLESAMPLE). PostgreSQL extension.
whereWhereOptions<T>Filter rows; see WhereOptions. All rows when omitted.
rawbooleanReturn plain row objects instead of model instances. Default: false.
nestbooleanWith raw, build nested objects from dotted keys such as 'posts.title'. Default: false.
plainbooleanReturn a single row instead of an array (set internally by findOne). Default: false.
rejectOnEmptyboolean | ErrorThrow EmptyResultError (or the given Error) when no row is found. Default: false.
paranoidbooleanFor paranoid models: false includes soft-deleted rows. Default: true.
hooksbooleanRun beforeFind / afterFind hooks. Default: true.
includeIncludeOptionEager-load associations through JOINs (or separate queries for separate includes).
subQuerybooleanfalse disables the sub-query used for limit combined with multi-row includes.
tableAsstringAlias 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 extensionReadonly<Record<string, Subquery | Readonly<{ query: Subquery | WriteStatement; recursi…Common table expressions (WITH [RECURSIVE] ...). PostgreSQL extension.
source postgrelize extensionstring | SubqueryRead 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 extensionReadonly<Record<string, FromSourceOption>>Extra relations (FROM "Model", "alias"), keyed by alias; correlate them in where. PostgreSQL extension.
defaultsPartial<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.

ts
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 }, ...]
OptionTypeDescription
transactionTransactionTransaction to run in; null forces running outside the CLS transaction.
loggingfalse | LoggingFunctionSQL logger for this query, or false.
benchmarkbooleanPass query duration to the logger.
statementTimeout postgrelize extensionnumberstatement_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.
retryReadonly<{ 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 extensionbooleanForce the writer even for SELECTs when read replicas are configured. postgrelize extension.
replacementsReplacementsValues 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.
whereWhereOptions<T>Filter rows; see WhereOptions.
colstringColumn to count. Default: * (primary key with distinct).
distinctbooleanUse count(DISTINCT ...). Default: false.
groupstring | readonly string[]Group by attributes; the result becomes an array of { count, ...groups }.
paranoidbooleanFor paranoid models: false includes soft-deleted rows. Default: true.
hooksbooleanRun beforeCount hooks. Default: true.
includeIncludeOptionJoin associations (rows are counted per joined row unless distinct).
sample postgrelize extensionReadonly<{ method: "BERNOULLI" | "SYSTEM"; percent: number; seed?: number | undefined; }>Count only a random sample of the table (TABLESAMPLE). PostgreSQL extension.
with postgrelize extensionReadonly<Record<string, Subquery | Readonly<{ query: Subquery | WriteStatement; recursi…Common table expressions (WITH [RECURSIVE] ...). PostgreSQL extension.
source postgrelize extensionstring | SubqueryRead 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 extensionReadonly<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.

ts
const opts: CountWithOptions<Post> = { group: ['authorId'] };
const perAuthor = await Post.count(opts); // [{ authorId, count }, ...]
OptionTypeDescription
transactionTransactionTransaction to run in; null forces running outside the CLS transaction.
loggingfalse | LoggingFunctionSQL logger for this query, or false.
benchmarkbooleanPass query duration to the logger.
statementTimeout postgrelize extensionnumberstatement_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.
retryReadonly<{ 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 extensionbooleanForce the writer even for SELECTs when read replicas are configured. postgrelize extension.
replacementsReplacementsValues 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.
whereWhereOptions<T>Filter rows; see WhereOptions.
colstringColumn to count. Default: * (primary key with distinct).
distinctbooleanUse 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 }.
paranoidbooleanFor paranoid models: false includes soft-deleted rows. Default: true.
hooksbooleanRun beforeCount hooks. Default: true.
includeIncludeOptionJoin associations (rows are counted per joined row unless distinct).
sample postgrelize extensionReadonly<{ method: "BERNOULLI" | "SYSTEM"; percent: number; seed?: number | undefined; }>Count only a random sample of the table (TABLESAMPLE). PostgreSQL extension.
with postgrelize extensionReadonly<Record<string, Subquery | Readonly<{ query: Subquery | WriteStatement; recursi…Common table expressions (WITH [RECURSIVE] ...). PostgreSQL extension.
source postgrelize extensionstring | SubqueryRead 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 extensionReadonly<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.

ts
const opts: AggregateOptions<Product> = { where: { active: true }, paranoid: false };
const highest = await Product.max('price', opts);
OptionTypeDescription
transactionTransactionTransaction to run in; null forces running outside the CLS transaction.
loggingfalse | LoggingFunctionSQL logger for this query, or false.
benchmarkbooleanPass query duration to the logger.
statementTimeout postgrelize extensionnumberstatement_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.
retryReadonly<{ 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 extensionbooleanForce the writer even for SELECTs when read replicas are configured. postgrelize extension.
replacementsReplacementsValues 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.
whereWhereOptions<T>Filter rows; see WhereOptions.
colstringColumn to count. Default: * (primary key with distinct).
distinctbooleanUse count(DISTINCT ...). Default: false.
groupstring | readonly string[]Group by attributes; the result becomes an array of { count, ...groups }.
paranoidbooleanFor paranoid models: false includes soft-deleted rows. Default: true.
hooksbooleanRun beforeCount hooks. Default: true.
includeIncludeOptionJoin associations (rows are counted per joined row unless distinct).
sample postgrelize extensionReadonly<{ method: "BERNOULLI" | "SYSTEM"; percent: number; seed?: number | undefined; }>Count only a random sample of the table (TABLESAMPLE). PostgreSQL extension.
with postgrelize extensionReadonly<Record<string, Subquery | Readonly<{ query: Subquery | WriteStatement; recursi…Common table expressions (WITH [RECURSIVE] ...). PostgreSQL extension.
source postgrelize extensionstring | SubqueryRead 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 extensionReadonly<Record<string, FromSourceOption>>Extra relations (FROM "Model", "alias"), keyed by alias; correlate them in where. PostgreSQL extension.
plainbooleanReturn 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.
dataTypeDataTypeInputData 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.

ts
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] });
OptionTypeDescription
modelModelAssociated model; the association is looked up by model (and as).
asstringAlias of the association, as given when it was defined.
associationstring | 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.
requiredbooleanINNER JOIN (true) or LEFT OUTER JOIN (false).
rightbooleanUse RIGHT OUTER JOIN. Default: false.
attributesFindAttributeOptionsSelected attributes.
includeIncludeOptionNested includes.
separatebooleanLoad a hasMany association with a separate query instead of a JOIN. Default: false.
throughReadonly<{ attributes?: FindAttributeOptions | undefined; where?: unknown; }>Junction options for belongsToMany.
lateral postgrelize extensionbooleanFetch 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.
limitnumberMaximum rows per include of a separate include.
paranoidbooleanFor paranoid targets: false includes soft-deleted rows. Default: true.
allbooleanInclude every association of the model ({ all: true }). Default: false.

IncludeThroughOptions ​

Options of the junction table of an included belongsToMany association.

ts
const through: IncludeThroughOptions = { attributes: ['role'], where: { role: 'owner' } };
const rows = await Project.findAll({ include: [{ model: User, through }] });
OptionTypeDescription
attributesFindAttributeOptionsJunction 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).

ts
const opts: SelectOptions = {
  attributes: ['status', [fn('count', col('id')), 'n']],
  group: ['status'],
  having: { n: { [Op.gt]: 1 } },
  order: [['status', 'DESC']],
  limit: 20,
  offset: 40,
};
OptionTypeDescription
where{}Filter; finders type this as WhereOptions.
attributesFindAttributeOptionsSelected attributes. All attributes when omitted.
orderOrder | readonly unknown[]Sort order: attribute names, [attribute, 'ASC' | 'DESC'] pairs or expressions.
group{}GROUP BY attributes or expressions.
having{}HAVING condition.
limitnumberMaximum number of rows; null or undefined for no limit.
offsetnumberNumber of rows to skip; null or undefined to skip none.
lockLockOptionRow lock (FOR UPDATE etc.); requires a transaction.
skipLockedbooleanAdd SKIP LOCKED to the row lock; only with lock.
noWait postgrelize extensionbooleanAdd NOWAIT to the row lock so the query fails instead of waiting; only with lock. PostgreSQL extension.
distinctOn postgrelize extensionreadonly unknown[]SELECT DISTINCT ON (...): attributes or expressions. PostgreSQL extension.
withTies postgrelize extensionbooleanFETCH 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 extensionReadonly<{ 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.

ts
const opts: CteFindOptions = {
  with: { recent: { query: Post.subquery({ where: { published: true } }) } },
  source: 'recent',
};
OptionTypeDescription
with postgrelize extensionReadonly<Record<string, Subquery | Readonly<{ query: Subquery | WriteStatement; recursi…Common table expressions (WITH [RECURSIVE] ...). PostgreSQL extension.
source postgrelize extensionstring | SubqueryRead 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 extensionReadonly<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.

ts
const search: CteSearchOptions = { by: ['id'], mode: 'breadth', set: 'ordercol' };
OptionTypeDescription
byreadonly string[]Columns of the CTE that define the order.
mode"breadth" | "depth"Traversal order. Default: 'depth'.
setstringName of the added ordering column.

CteCycleOptions postgrelize extension ​

cycle of a recursive CTE definition. PostgreSQL extension.

ts
const cycle: CteCycleOptions = { columns: ['id'], set: 'is_cycle', using: 'path' };
OptionTypeDescription
columnsreadonly string[]Columns that identify a visited row.
setstringName of the added boolean column that is true on the row that closes a cycle.
usingstringName 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.

ts
const sample: TableSampleOptions = { method: 'BERNOULLI', percent: 10, seed: 42 };
const rows = await Post.findAll({ sample });
OptionTypeDescription
method"BERNOULLI" | "SYSTEM"Sampling method: BERNOULLI (row by row) or SYSTEM (block by block, faster).
percentnumberPercentage of the table to read, from 0 to 100. Bound as a parameter.
seednumberREPEATABLE 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.

ts
const opts: SetOperationOptions = { all: true };
const rows = Post.subquery({ attributes: ['userId'] }).union(Task.subquery({ attributes: ['userId'] }), opts);
OptionTypeDescription
allbooleanKeep duplicate rows (UNION ALL, INTERSECT ALL, EXCEPT ALL). Default: false.

WindowOptions postgrelize extension ​

Window definition of over. PostgreSQL extension.

ts
const window: WindowOptions = { partitionBy: ['userId'], orderBy: [['createdAt', 'DESC']] };
OptionTypeDescription
partitionByreadonly unknown[]PARTITION BY attributes or expressions.
orderByreadonly 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.

ts
const source: JsonTableOptions = {
  doc: { items: [{ sku: 'a', qty: 2 }] },
  path: '$.items[*]',
  columns: [{ name: 'sku', type: 'text' }, { name: 'qty', type: 'integer' }],
};
OptionTypeDescription
doc{}Document: a JSON value (bound as jsonb) or an expression such as col('Order.data').
pathstringjsonpath that selects the rows; rendered as an escaped string literal.
columnsreadonly Readonly<{ name: string; ordinality?: boolean | undefined; type?: string | und…Output columns.

JsonTableColumnOptions postgrelize extension ​

One column of a JsonTableOptions. PostgreSQL extension.

ts
const columns: JsonTableColumnOptions[] = [
  { name: 'position', ordinality: true },
  { name: 'qty', type: 'integer', path: '$.quantity' },
  { name: 'hasNote', exists: true, path: '$.note' },
];
OptionTypeDescription
namestringOutput column name.
ordinalitybooleanNumber the rows (FOR ORDINALITY); no type or path.
typestringColumn type: one of the cast types (integer, text, jsonb, timestamptz, …).
pathstringjsonpath of the value, relative to the row; defaults to the column name.
existsbooleanReturn whether the path matches (EXISTS); type defaults to boolean.

JsonbPathOptions postgrelize extension ​

Options of jsonbPath. PostgreSQL extension.

ts
const options: JsonbPathOptions = { vars: { min: 10 }, silent: true };
OptionTypeDescription
varsReadonly<Record<string, unknown>>Values of the $name variables of the path; serialized to jsonb and bound as a parameter.
silentbooleanSuppresses missing-key and type errors of the path (the silent argument).
tzbooleanUses the _tz variant, which converts between time zones (stable instead of immutable).

TsRankOptions postgrelize extension ​

Options of tsRank. PostgreSQL extension.

ts
const options: TsRankOptions = { cd: true, weights: [0.1, 0.2, 0.4, 1], normalization: 1 };
OptionTypeDescription
cdbooleanUses ts_rank_cd (cover density) instead of ts_rank.
weightsreadonly [number, number, number, number]Weights of the labels D, C, B, A, in this order.
normalizationnumberNormalization bit mask, an integer from 0 to 63.

TsHeadlineOptions postgrelize extension ​

Options of tsHeadline. PostgreSQL extension.

ts
const options: TsHeadlineOptions = { config: 'english', options: 'StartSel=<b>, StopSel=</b>' };
OptionTypeDescription
configstringText search configuration, e.g. 'english'.
optionsstringts_headline options string, e.g. 'StartSel=<b>, StopSel=</b>'. Bound as a parameter.

Released under the MIT License.