Advanced queries
postgrelize extensions
Sections marked postgrelize extension describe options, methods and statements that Sequelize v6 does not have. Everything else here behaves as in v6. All extensions are listed on the extensions page.
In Sequelize v6, subqueries, CTEs and window functions need literal() SQL strings. postgrelize builds them from the same find options you already use, with bound parameters and quoted identifiers, and returns model instances where that makes sense.
The examples use User (name), Post (title, rank, published, UserId; User.hasMany(Post)) and Category (name, parentId), a tree.
Subqueries postgrelize extension
Model.subquery(findOptions) builds a SELECT that can be embedded in another query instead of running it. It accepts the find options (attributes, where, order, limit, include, scopes) plus as for the table alias, which defaults to the model name. The default scope and the paranoid filter apply.
Use it with Op.in / Op.notIn, as a scalar value in attributes, as a from / using source, and as the source of insertFrom and merge:
const authors = await User.findAll({
where: {
id: { [Op.in]: Post.subquery({ attributes: ['UserId'], where: { published: true } }) },
},
order: [['id', 'ASC']],
});
const counted = await User.findAll({
attributes: [
'name',
[
Post.subquery({
attributes: [[fn('count', col('Post.id')), 'n']],
where: { UserId: col('User.id') },
}),
'postCount',
],
],
order: [['id', 'ASC']],
raw: true,
});
// counted: [{ name: 'ann', postCount: '2' }, { name: 'bob', postCount: '2' }, { name: 'cid', postCount: '0' }]A subquery can reference the outer query with col('User.id') (a correlated subquery). Its parameters are numbered together with the outer statement.
EXISTS postgrelize extension
exists(subquery) and notExists(subquery) produce EXISTS (...) conditions. Use them as the where value or inside Op.and / Op.or:
const postsOf = (extra: object) =>
Post.subquery({ attributes: ['id'], where: { UserId: col('User.id'), ...extra } });
const highRanked = await User.findAll({ where: exists(postsOf({ rank: { [Op.gte]: 5 } })) });
const silent = await User.findAll({ where: notExists(postsOf({})) });
// highRanked: bob; silent: cidDISTINCT ON postgrelize extension
distinctOn keeps the first row of each group, as defined by order. It is the idiomatic PostgreSQL way to get "the latest / best row per key":
const topPerUser = await Post.findAll({
distinctOn: ['UserId'],
order: [
['UserId', 'ASC'],
['rank', 'DESC'],
],
});
// topPerUser: a1, b2As PostgreSQL requires, the order must start with the distinctOn expressions.
Window functions postgrelize extension
over(fn, { partitionBy, orderBy }) adds an OVER (...) clause to a function call. Use it in attributes (and, through a subquery or CTE, in filters):
const ranked = await Post.findAll({
attributes: [
'title',
[
over(fn('row_number'), { partitionBy: ['UserId'], orderBy: [['rank', 'DESC']] }),
'position',
],
],
order: [['title', 'ASC']],
raw: true,
});
// ranked: a1 → '1', a2 → '2', b1 → '2', b2 → '1'orderBy uses the same format and the same direction allow-list as order.
Row comparison and keyset pagination postgrelize extension
tuple(...) builds a row value (a, b). Combined with where(left, operator, right), it expresses keyset ("seek") pagination, which stays fast on deep pages where OFFSET does not:
const nextPage = await Post.findAll({
where: where(tuple(col('rank'), col('id')), Op.lt, tuple(3, 1)),
order: [
['rank', 'DESC'],
['id', 'DESC'],
],
limit: 10,
});
// nextPage: b1, a2 — rows after (rank 3, id 1) in (rank DESC, id DESC) orderBack the comparison with an index on the same columns in the same order, e.g. indexes: [{ fields: ['rank', 'id'] }].
Common table expressions postgrelize extension
The with option adds WITH clauses to findAll, findOne, count, aggregates and copyTo. Each CTE is a subquery, or { query, recursive?, unionAll?, materialized? }.
source reads the model rows from a CTE instead of the table, and the result is still model instances. A recursive CTE walks a tree in one query:
const subtree = await Category.findAll({
with: {
tree: {
query: Category.subquery({ where: { name: 'a' } }),
recursive: Category.subquery({
where: { parentId: col('tree.id') },
from: { tree: 'tree' },
}),
},
},
source: 'tree',
order: [['id', 'ASC']],
});
// subtree: a, a1, a1x — Category instances read from the CTErecursivemakes the clauseWITH RECURSIVEand is joined toquerywithUNION ALL(unionAll: falseforUNION).- Inside the recursive part,
from: { tree: 'tree' }adds the CTE as an extra relation, socol('tree.id')can reference it. materialized: true/falseaddsMATERIALIZED/NOT MATERIALIZED.
CTEs can also be used as filters:
const rootChildren = await Category.count({
with: {
roots: {
query: Category.subquery({ attributes: ['id'], where: { parentId: null } }),
materialized: true,
},
},
where: {
parentId: { [Op.in]: Category.subquery({ attributes: ['id'], source: 'roots' }) },
},
});
// rootChildren === 2SEARCH and CYCLE postgrelize extension
A recursive CTE definition accepts search and cycle:
search: { by, mode?, set }adds a columnsetthat orders the rows depth first (mode: 'depth', the default) or breadth first ('breadth') by thebycolumns. Order the result by it.cycle: { columns, set, using }adds a boolean columnsetthat is true on the row that revisits the samecolumns, and an array columnusingwith the path. The recursion stops at such a row, so cyclic data cannot loop forever.
Both need recursive. The added columns are not model attributes: select them with [col('walk'), 'walk'] (or read raw rows).
const depthFirst = await Category.findAll({
with: {
tree: {
query: Category.subquery({ where: { name: 'root' } }),
recursive: Category.subquery({
where: { parentId: col('tree.id') },
from: { tree: 'tree' },
}),
search: { by: ['id'], mode: 'depth', set: 'walk' },
},
},
source: 'tree',
attributes: ['name'],
order: [[col('walk'), 'ASC']],
raw: true,
});
// depthFirst: root, a, a1, a1x, b — `walk` orders the rows depth firstawait Category.update({ parentId: 5 }, { where: { name: 'root' } }); // root → a → a1 → a1x → root
const cyclic = await Category.findAll({
with: {
tree: {
query: Category.subquery({ where: { name: 'root' } }),
recursive: Category.subquery({
where: { parentId: col('tree.id') },
from: { tree: 'tree' },
}),
cycle: { columns: ['id'], set: 'looped', using: 'trail' },
},
},
source: 'tree',
attributes: ['name', [col('looped'), 'looped']],
order: [[col('trail'), 'ASC']],
raw: true,
});
// cyclic: root, a, a1, a1x, then root again with looped = true (the recursion stops there), then bData-modifying CTEs postgrelize extension
Model.updateStatement(values, { where, returning }), Model.deleteStatement({ where, returning }) and Model.insertStatement(rows, { returning }) build a statement for the with option. The statement runs as part of the finder's query. With returning: true, read its rows through source: '<cte name>', or filter with them. No hooks or validation run; updatedAt is set (not with silent: true), defaults and timestamps are filled for inserts, and deleteStatement is a real delete, also for paranoid models.
const removed = await Post.findAll({
with: { gone: Post.deleteStatement({ where: { published: false }, returning: true }) },
source: 'gone',
});
// removed: a2 — deleted and returned by one statement- The query is sent to the writer, never to a read replica.
- A data-modifying statement cannot be
recursive, and cannot be the main statement of a finder: only the CTE body is supported (for example, there is noINSERT … SELECT FROM cte). - All CTEs of one statement see the same snapshot: the main query does not see the changes of a data-modifying CTE in the tables, only in its
RETURNINGrows.
Set operations postgrelize extension
Subquery has union(), intersect() and except() (pass { all: true } for the ALL forms). The result is another subquery, so it works wherever a subquery does: in Op.in, in with, as a source of insertFrom or merge. Both sides must select the same columns.
const published = Post.subquery({ attributes: [['UserId', 'id']], where: { published: true } });
const withoutPosts = await User.findAll({
where: { id: { [Op.in]: User.subquery({ attributes: ['id'] }).except(published) } },
});
// withoutPosts: cid
const pair = await User.findAll({
source: User.subquery({ where: { name: 'ann' } }).union(
User.subquery({ where: { name: 'cid' } }),
),
order: [['name', 'DESC']],
});
// pair: cid, ann — rows of the UNION, read as User instancessource also accepts a subquery: the finder then reads model rows from (… UNION …) AS "User", and its own order, limit and offset apply to the combined result. Select all attributes in the operands for that (no attributes option), because the finder selects every attribute of the model.
FETCH FIRST … WITH TIES postgrelize extension
withTies: true with limit and order returns the first limit rows plus every row that ties with the last one on the order columns (FETCH FIRST $1 ROWS WITH TIES). PostgreSQL rejects it without ORDER BY; postgrelize throws withTies requires a limit when limit is missing.
const topPublished = await Post.findAll({
order: [['published', 'DESC']],
limit: 1,
withTies: true,
});
// topPublished: a1, b1, b2 — every row that ties with the first on `published`Extra relations with from postgrelize extension
from on finders adds relations to the FROM clause, keyed by alias, without an association. Correlate them in where:
const parents = await Category.findAll({
attributes: ['name', [fn('count', col('child.id')), 'children']],
from: { child: Category },
where: { id: col('child.parentId') },
group: ['Category.id', 'Category.name'],
raw: true,
});VALUES, set-returning functions and JSON_TABLE postgrelize extension
A from entry can also be an object that produces rows. Every value is a bound parameter; names are quoted identifiers.
| Entry | SQL |
|---|---|
{ values: { columns, rows } } | (VALUES (…), …) AS "alias"("col", …) |
{ function, args?, columns?, ordinality? } | fn(args) [WITH ORDINALITY] AS "alias"("col", …); ordinality names the extra column |
{ lateral: subquery } | LATERAL (subquery) AS "alias" |
{ model, sample } | the model table with TABLESAMPLE |
{ jsonTable: { doc, path, columns } } (PostgreSQL 17) | JSON_TABLE(doc, path COLUMNS (…)) AS "alias" |
const ordered = await User.findAll({
from: {
v: {
values: {
columns: ['id', 'rank'],
rows: [
[cast(3, 'integer'), 1],
[cast(1, 'integer'), 2],
],
},
},
},
where: { id: col('v.id') },
order: [[col('v.rank'), 'ASC']],
});
// ordered: cid, ann — joined to an inline VALUES list
const numbered = await User.findAll({
attributes: ['name', [col('n.pos'), 'pos']],
from: {
n: {
function: 'unnest',
args: [cast([3, 1], 'integer[]')],
columns: ['id'],
ordinality: 'pos',
},
},
where: { id: col('n.id') },
order: [[col('n.pos'), 'ASC']],
raw: true,
});
// numbered: cid at position 1, ann at position 2 (WITH ORDINALITY)PostgreSQL cannot always infer the type of a bound parameter in a function call or VALUES cell (generate_series($1, $2) is ambiguous). Wrap such values in cast(value, 'integer').
JSON_TABLE turns a JSON document, given as a value or an expression such as col('Order.data'), into rows. The path and each column path are jsonpath strings, which PostgreSQL only accepts as constants, so they are rendered as escaped string literals. Column type is checked against the same list as 'attr::type' casts. It needs PostgreSQL 17; older servers reject the query. Nested paths (NESTED PATH) are not supported.
const rows = await Product.findAll({
attributes: ['sku', [col('item.qty'), 'qty'], [col('item.position'), 'position']],
from: {
item: {
jsonTable: {
doc: {
items: [
{ sku: 'a', qty: 5 },
{ sku: 'b', qty: 9 },
],
},
path: '$.items[*]',
columns: [
{ name: 'position', ordinality: true },
{ name: 'sku', type: 'text' },
{ name: 'qty', type: 'integer' },
],
},
},
},
where: { sku: col('item.sku') },
order: [['sku', 'ASC']],
raw: true,
});
// rows: a → qty 5, position 1; b → qty 9, position 2LATERAL joins and top-N per parent postgrelize extension
A LATERAL subquery may reference relations that come before it in FROM, so it runs once per row. Use it for "latest N per parent" queries. A lateral entry in from behaves like an inner join: rows without a match disappear.
For includes, lateral: true on a separate include with limit makes the database return only the first limit rows per parent (unnest(keys) joined with a LATERAL subquery), instead of loading every child and trimming in memory. order applies per parent. It cannot have nested includes.
const latest = await User.findAll({
attributes: ['name', [col('latest.title'), 'title']],
from: {
latest: {
lateral: Post.subquery({
attributes: ['title'],
where: { UserId: col('User.id') },
order: [['id', 'DESC']],
limit: 1,
}),
},
},
order: [['id', 'ASC']],
raw: true,
});
// latest: ann → a2, bob → b2 (cid has no posts, so the join drops it)
const withLatestPost = await User.findAll({
include: [
{ association: 'Posts', separate: true, lateral: true, limit: 1, order: [['id', 'DESC']] },
],
order: [['id', 'ASC']],
});
// each user's Posts holds at most one row, read with one LATERAL queryTABLESAMPLE postgrelize extension
sample: { method, percent, seed? } on findAll and count reads a random part of the table: BERNOULLI samples row by row, SYSTEM block by block (faster, clustered). percent is from 0 to 100; the same seed gives the same sample while the data is unchanged (REPEATABLE). The same option works on a from entry: { model, sample }.
const sampled = await Post.findAll({ sample: { method: 'BERNOULLI', percent: 100, seed: 1 } });
// sampled: every row at 100 percent; use a smaller percent to read a random part of a big tableServer-side cursors with findEach postgrelize extension
Model.findEach(findOptions, { batchSize }) streams rows with a server-side cursor (DECLARE ... CURSOR and FETCH n), so a large result is never loaded at once:
const seen: string[] = [];
for await (const post of Post.findEach({ order: [['id', 'ASC']] }, { batchSize: 2 })) {
seen.push(String(post.get('title')));
}
// seen: a1, a2, b1, b2 — fetched two rows at a time through a server-side cursor- The cursor needs a transaction. Pass
transaction, orfindEachopens one and commits it when the iteration ends. - Leaving the loop early (
break,return, an exception) closes the cursor. batchSizedefaults to 100. Includes must beseparate: true; they are loaded with one extra query per batch. Joined includes are rejected.
For exporting rows as text, copyTo is faster still.
API reference
Model—subquery,findEachexists,notExists,over,tuple,whereCteDefinition,CteFindOptions,WindowOptions