Skip to content

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:

ts
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:

ts
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: cid

DISTINCT 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":

ts
const topPerUser = await Post.findAll({
  distinctOn: ['UserId'],
  order: [
    ['UserId', 'ASC'],
    ['rank', 'DESC'],
  ],
});
// topPerUser: a1, b2

As 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):

ts
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:

ts
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) order

Back 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:

ts
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 CTE
  • recursive makes the clause WITH RECURSIVE and is joined to query with UNION ALL (unionAll: false for UNION).
  • Inside the recursive part, from: { tree: 'tree' } adds the CTE as an extra relation, so col('tree.id') can reference it.
  • materialized: true / false adds MATERIALIZED / NOT MATERIALIZED.

CTEs can also be used as filters:

ts
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 === 2

SEARCH and CYCLE postgrelize extension ​

A recursive CTE definition accepts search and cycle:

  • search: { by, mode?, set } adds a column set that orders the rows depth first (mode: 'depth', the default) or breadth first ('breadth') by the by columns. Order the result by it.
  • cycle: { columns, set, using } adds a boolean column set that is true on the row that revisits the same columns, and an array column using with 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).

ts
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 first
ts
await 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 b

Data-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.

ts
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 no INSERT … 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 RETURNING rows.

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.

ts
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 instances

source 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.

ts
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:

ts
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.

EntrySQL
{ 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"
ts
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.

ts
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 2

LATERAL 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.

ts
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 query

TABLESAMPLE 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 }.

ts
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 table

Server-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:

ts
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, or findEach opens one and commits it when the iteration ends.
  • Leaving the loop early (break, return, an exception) closes the cursor.
  • batchSize defaults to 100. Includes must be separate: 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 ​

Released under the MIT License.