Querying
Finders, where operators, ordering, grouping, aggregates, scopes and raw queries follow Sequelize v6. This page shows the common patterns and the PostgreSQL-specific operators. For subqueries, CTEs and window functions see Advanced queries.
The examples use this model:
const Item = sequelize.define('Item', {
code: DataTypes.TEXT,
qty: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 },
attrs: DataTypes.JSONB,
tags: DataTypes.ARRAY(DataTypes.TEXT),
});Filtering
where takes attribute hashes, Op operators, Op.and / Op.or / Op.not, and nested JSON paths with dotted keys:
const red = await Item.findAll({ where: { 'attrs.color': 'red' } });
const big = await Item.findAll({
where: { [Op.or]: [{ qty: { [Op.gte]: 2 } }, { code: { [Op.iLike]: 'A%' } }] },
order: [['qty', 'DESC']],
});
const withSize = await Item.count({ where: { attrs: { [Op.hasKey]: 'size' } } });
const notA = await Item.count({ where: { code: { [Op.isDistinctFrom]: 'a' } } });
const listed = await Item.count({ where: { id: { [Op.any]: [1, 3] } } });Supported operators are the v6 ones for PostgreSQL: comparison (eq, ne, gt, gte, lt, lte, between, notBetween), lists (in, notIn, any, all), text (like, iLike, startsWith, endsWith, substring, regexp, iRegexp and their negations), is / not, arrays and ranges (contains, contained, overlap, adjacent, strictLeft, strictRight, noExtendLeft, noExtendRight), full-text match, and col for column comparisons.
PostgreSQL additions and fixes (postgrelize extension marks what v6 does not have):
- postgrelize extension
Op.isDistinctFrom/Op.isNotDistinctFromcompare withIS [NOT] DISTINCT FROM, which treatsNULLas a value. Op.hasKey,Op.hasAnyKeys,Op.hasAllKeysmap to the jsonb?,?|and?&operators; they also work on nested JSON paths.- postgrelize extension
{ [Op.any]: [1, 3] }is shorthand for= ANY($1)with one array parameter. INlists with 100 or more values are sent as= ANY($1)with a single array parameter instead of one parameter per value. Change the threshold with theinAsAnyThresholdconstructor option.
const ids = Array.from({ length: 150 }, (_, index) => index + 1);
const statements: string[] = [];
const longIn = await Item.count({
where: { id: { [Op.in]: ids } },
logging: (_sql, info?: unknown) =>
statements.push((info as { parameterizedSql: string }).parameterizedSql),
}); // 150 values: one array parameter, `"id" = ANY($1)`Operator and search helpers postgrelize extension
PostgreSQL operators that Sequelize v6 leaves to literal() have first-class Op entries and expression helpers. Every value is a bound parameter; regconfig names, weights and function kinds are validated.
SIMILAR TO. Op.similarTo / Op.notSimilarTo take an SQL regular expression. %, _, |, *, +, ?, {}, (), [] and \ are pattern syntax: escape them with \ to match literally.
const sqlPattern = await Doc.findAll({
where: { name: { [Op.similarTo]: '(c|d)%' } },
order,
});jsonpath. Op.jsonPathExists is @?; @@ for a jsonpath predicate is where(col('attrs'), Op.match, '$.price > 10') (use where() so the string is not serialized as a JSON value). jsonbPath(kind, target, path, { vars, silent, tz }) calls jsonb_path_exists, jsonb_path_match, jsonb_path_query, jsonb_path_query_first or jsonb_path_query_array; vars are passed as one bound jsonb parameter.
const exists = await Doc.findAll({
where: { attrs: { [Op.jsonPathExists]: '$.price ? (@ > 10)' } },
});
const withVars = await Doc.findAll({
where: where(
jsonbPath('exists', col('attrs'), '$.price ? (@ < $max)', { vars: { max: 10 } }),
true,
),
});Network. Op.containedOrEqual (<<=) and Op.containsOrEqual (>>=) are new; <<, >> and && are Op.strictLeft, Op.strictRight and Op.overlap. host(), network() and the other functions go through fn().
const inSubnet = await Doc.findAll({ where: { ip: { [Op.containedOrEqual]: '10.0.0.0/8' } } });Full-text search. toTsVector, toTsQuery, plainToTsQuery, phraseToTsQuery and websearchToTsQuery take an optional text search configuration ('english', 'pg_catalog.simple'). tsRank (with cd, weights, normalization), tsHeadline and setWeight cover ranking and highlighting. Use Op.match for @@.
const vector = toTsVector(col('body'), 'english');
const query = websearchToTsQuery('"fat cats" -dog', 'english');
const found = await Doc.findAll({
attributes: [
'name',
[tsRank(vector, query, { normalization: 1 }), 'rank'],
[
tsHeadline(col('body'), query, {
config: 'english',
options: 'StartSel=<b>, StopSel=</b>',
}),
'excerpt',
],
],
where: where(vector, Op.match, query),
order: [[tsRank(vector, query), 'DESC']],
});
// found[0].get('excerpt'): 'The <b>fat</b> <b>cats</b> sat on the mat'
const anyWord = await Doc.findAll({
where: where(vector, Op.match, plainToTsQuery('dog home', 'english')),
});Trigram similarity (pg_trgm). Run CREATE EXTENSION pg_trgm first. Op.trigramSimilar (%), Op.trigramWordSimilar (<%), Op.trigramStrictWordSimilar (<<%) and the commutators Op.trigramHasSimilarWord (%>), Op.trigramHasSimilarStrictWord (%>>) filter; trigramSimilarity, trigramWordSimilarity and trigramDistance (<->) build expressions for attributes and order. The similarity threshold is the pg_trgm.similarity_threshold setting.
const similar = await Doc.findAll({
where: { name: { [Op.trigramSimilar]: 'dogg' } },
order: [[trigramDistance(col('name'), 'dogg'), 'ASC']],
});Selecting, ordering and paginating
attributes selects columns (['id', 'code'], { exclude: [...] }, { include: [...] }, or [expression, 'alias'] pairs). order takes [attribute, direction] pairs, expressions, and nested association paths. Directions are allow-listed: ASC, DESC, optionally with NULLS FIRST / NULLS LAST.
const { count, rows } = await Item.findAndCountAll({
attributes: ['id', 'code'],
order: [['id', 'ASC']],
limit: 2,
offset: 1,
});NULL last in ASC and first in DESC order. Add NULLS FIRST or NULLS LAST to the direction to choose where rows with NULL go; any other direction text is rejected.const nullsFirst = await Item.findAll({ order: [['code', 'ASC NULLS FIRST']] });
const nullsLast = await Item.findAll({ order: [['code', 'ASC NULLS LAST']] });findOne, findByPk, findOrCreate, findOrBuild and findAndCountAll behave as in v6. Pass rejectOnEmpty: true to throw EmptyResultError instead of returning null. raw: true returns plain objects, and nest: true turns dotted keys into nested objects.
Aggregates and expressions
const total = await Item.sum('qty');
const maxQty = await Item.max('qty');
const perTag = await Item.findAll({
attributes: [
[fn('unnest', col('tags')), 'tag'],
[fn('count', col('id')), 'n'],
],
group: ['tag'],
order: [['tag', 'ASC']],
raw: true,
});
await Item.increment('qty', { by: 5, where: { code: 'c' } });count, sum, min, max and aggregate accept the same where as finders; aggregate and the helpers convert the result to the type of the attribute (FLOAT for '*'), dataType overrides that, and plain: false returns the raw rows with the driver's strings (like v6); count also takes distinct, col and group. increment and decrement work on the model (with where) and on instances.
Build SQL expressions with fn, col, literal, cast, json and where. Values inside them are bound parameters; identifiers are quoted. Use literal only with trusted SQL text.
Scopes
Scopes are named sets of query options, defined with scopes and defaultScope in the model options or later with addScope:
const onSale = await Item.scope('inStock', { method: ['tagged', 'sale'] }).findAll();As in v6, scope() merges scopes, unscoped() removes the default scope, and function scopes take arguments through { method: [name, ...args] }.
By default, when two merged scopes filter the same attribute, the later one wins (the v6 behaviour). The model option whereMergeStrategy: 'and' combines them with AND instead:
sequelize.define('Person', attributes, {
whereMergeStrategy: 'and',
scopes: {
adults: { where: { age: { [Op.gte]: 18 } } },
young: { where: { age: { [Op.lt]: 30 } } },
},
});
await Person.scope('adults', 'young').findAll(); // 18 <= age < 30Raw SQL
sequelize.query runs SQL with replacements (:name or ?, escaped into the SQL text as in Sequelize v6) or bind parameters ($1, sent separately). type: QueryTypes.SELECT returns the rows only:
const byReplacement = (await sequelize.query('SELECT code FROM "Items" WHERE qty > :min', {
replacements: { min: 1 },
type: QueryTypes.SELECT,
})) as { code: string }[];
const byBind = (await sequelize.query('SELECT code FROM "Items" WHERE code = $1', {
bind: ['a'],
type: QueryTypes.SELECT,
})) as { code: string }[];
// Replacements are escaped into the SQL text (as in Sequelize v6), so one call may hold several statements.
const code = 'a\'; DROP TABLE "Items"; --';
await sequelize.query('UPDATE "Items" SET qty = qty WHERE code = :code; SELECT :code AS code', {
replacements: { code },
});sequelize.query returns Promise<unknown>; cast the result to the row type you expect. The result follows the query type like v6: SELECT rows, INSERT / UPDATE [rows, rowCount], DELETE the statement rows ([] without RETURNING), BULKUPDATE / BULKDELETE the row count, UPSERT [undefined, null]. Other v6 options are supported: plain, raw, nest (nests a.b column names into objects), model / mapToModel, transaction, logging.
Because replacements are written into the SQL text, the query goes to PostgreSQL as one simple query and may hold several ;-separated statements, as in v6 (bind parameters cannot: PostgreSQL rejects several commands in one prepared statement). Strings are quoted (' doubled, E'...' when they contain a backslash), numbers and booleans are written as is, null is NULL, dates are ISO strings, objects are JSON text and arrays in IN (:ids) expand to a list. A string with a NUL character throws (v6 writes \0 and changes the value). Placeholders inside string literals, quoted identifiers, comments, dollar quotes and :: casts are left alone. Never build the SQL text from user input; pass the values as replacements.
The finders take replacements as well, for placeholders inside literal(): await User.findAll({ where: literal('"age" > :min AND "role" IN (:roles)'), replacements: { min: 18, roles: ['admin', 'editor'] } }). Arrays expand to a list, ? placeholders take an array, and every value is written into the SQL text as an escaped literal, exactly as in sequelize.query and Sequelize v6, so the same placeholder used twice (SELECT and GROUP BY) gives identical expressions. Values the finder builds itself (where values, limit, ...) stay bound parameters. A placeholder without a value throws.
Locking
lock: true (or Transaction.LOCK.UPDATE, SHARE, KEY_SHARE, NO_KEY_UPDATE) adds FOR UPDATE and friends; skipLocked: true adds SKIP LOCKED, and noWait: true (a PostgreSQL extension) adds NOWAIT. Locks need a transaction, see Transactions.
API reference
Model— finders and aggregatesFindOptions,WhereOptionsOp,fn,col,literalSequelize.query