1. guides
prorm
  • prorm documentation
  • Known test gaps
  • Architecture
  • Core concepts
  • Database types & coverage
  • Getting started
  • Going further
  • compliance
    • Compliance
    • The security toolkit: `prorm audit`
    • Checklists by regulation
    • Declaring personal data
    • Evidence bundles
    • Evidence
    • Frameworks: `@Security`
    • Jurisdictions
    • Platform policies
    • Protecting data
    • The regulation dataset
    • Residency and cross-border transfers
    • Retention & integrity
    • Status
    • Subject rights
  • decorators
    • prorm with decorators
    • Models with decorators
    • Querying a decorated model
    • Relations with decorators
  • diagrams
    • Diagram generators
    • Chen diagram
    • Class diagram
    • Dependency diagram
    • ER diagram
    • Flow diagram
    • From your models to a diagram
    • Gantt diagram
    • Index diagram
    • Migration diagram
    • Model diagram
    • Package diagram
    • Crow’s-foot diagram
    • Schema documentation
    • Sequence diagram
    • State diagram
    • Tree diagram
  • dialects
    • SQL dialects
    • AlloyDB Dialect
    • AlloyDB Omni Dialect
    • Amazon Athena Dialect
    • Aurora DSQL Dialect
    • Amazon Aurora MySQL Dialect
    • Amazon Aurora PostgreSQL Dialect
    • Azure Database for MySQL Dialect
    • Azure Database for PostgreSQL Dialect
    • Azure SQL Database Dialect
    • Azure SQL Managed Instance Dialect
    • Google BigQuery Dialect
    • Citus Dialect
    • ClickHouse dialect
    • Cloud Authentication (`cloud-auth`)
    • Cloud SQL for SQL Server Dialect
    • Cloud SQL for MySQL Dialect
    • Cloud SQL for PostgreSQL Dialect
    • CockroachDB Dialect
    • Azure Cosmos DB for PostgreSQL Dialect
    • CrateDB Dialect
    • Cloudflare D1 Dialect
    • Databricks dialect
    • IBM Db2 Dialect
    • Dolt Dialect
    • Apache Doris Dialect
    • Druid Dialect
    • DuckDB Dialect
    • Exasol dialect
    • Microsoft Fabric Data Warehouse Dialect
    • Firebird Dialect
    • Greenplum Dialect
    • SAP HANA Dialect
    • MySQL HeatWave Dialect
    • Azure Data Explorer (Kusto) Dialect — T-SQL
    • MariaDB Dialect
    • Materialize Dialect
    • MonetDB Dialect
    • MotherDuck Dialect
    • Microsoft SQL Server Dialect
    • MySQL Dialect
    • Neon Dialect
    • OceanBase Dialect
    • openGauss Dialect
    • Oracle Dialect
    • Oracle Autonomous Database Dialect
    • ParadeDB Dialect
    • PolarDB Dialect
    • PostgreSQL Dialect
    • Presto Dialect
    • QuestDB Dialect
    • Aurora RDS Data API Dialect (`rdsdata`)
    • Amazon RDS for Db2 Dialect
    • Amazon RDS for MariaDB Dialect
    • Amazon RDS for SQL Server Dialect
    • Amazon RDS for MySQL Dialect
    • Amazon RDS for Oracle Dialect
    • Amazon RDS for PostgreSQL Dialect
    • Amazon Redshift
    • Amazon Redshift Data API Dialect
    • RisingWave Dialect
    • rqlite Dialect
    • SingleStore Dialect
    • Snowflake Dialect
    • Google Cloud Spanner Dialect
    • Spanner (PostgreSQL interface) Dialect
    • SQLite Dialect
    • StarRocks Dialect
    • Supabase Dialect
    • Azure Synapse Analytics (dedicated SQL pool)
    • Teradata Dialect
    • TiDB Dialect
    • TimescaleDB Dialect
    • Trino Dialect
    • Turso / libSQL Dialect
    • Vertica dialect
    • Vitess Dialect
    • Yellowbrick Dialect
    • YugabyteDB Dialect
  • guides
    • Access rules and behaviour profiles
    • ArangoDB (AQL)
    • Associations
    • Audit levels and escalation
    • Audit logging
    • In the browser
    • Bulk operations
    • Caching
    • Capabilities, tiers and team roles
    • CLI
    • Cloudflare
    • Compliance & data protection
    • Connection Pooling & Performance
    • Security in the console
    • Couchbase: structured N1QL queries
    • Data types
    • Decorators
    • Eager loading
    • Enums and constants
    • Error handling & error types
    • Extensions
    • External fields
    • Foreign data wrappers
    • Graph databases
    • Hooks & lifecycle events
    • Indexes & constraints
    • InfluxDB: structured Flux pipelines
    • klock-errors
    • klock — the `.klock` file
    • Local databases (`prorm db up`)
    • Structured log search — Splunk, Graylog, Papertrail, Sumo Logic
    • Logging
    • Grafana Loki: structured LogQL queries
    • MCP server
    • Migrate — the data transfer subsystem
    • Migrations & Schema Sync
    • Models from an existing database
    • Defining models
    • Multiple databases
    • OrientDB, Neptune and TigerGraph
    • Passwords
    • Importing a Prisma schema
    • Structured PromQL and MetricsQL
    • Query firewall
    • QueryInterface
    • Query operators reference
    • Query optimization
    • Composing find options with `pipe()` and `Q`
    • Query safety: the fail-closed WHERE guard
    • Querying
    • Raw Queries & Query Building
    • Read replicas
    • Schema diffing & migration generation
    • Views, triggers & other schema objects
    • Scopes & default scopes
    • Seeders
    • SPARQL / RDF triplestores
    • SQL constants
    • SQL features
    • SQL function builders
    • SQLite advanced features
    • StoreKey — a prod-orm database as the storage
    • Streaming results
    • Terraform
    • Transactions & Isolation Levels
    • Type mapping: legacy and modern
    • TypeScript types
    • Database users, roles & privileges
    • Validation & constraints
    • Virtual & Computed Fields
    • Writing docs
  • javascript
    • prorm in JavaScript
    • Models in JavaScript
    • Querying in JavaScript
    • Relations in JavaScript
  • runbooks
    • Operational runbooks
    • Connection failures
    • Credential rotation
    • Failover
    • Incident checklist
    • Deploying klock v2
    • Migration rollback
  • running-databases
    • Running databases in Docker
    • Running prorm under Bun in Docker
    • Running Cassandra in Docker with prorm
    • Running ClickHouse in Docker with prorm
    • Running CockroachDB in Docker with prorm
    • Running prorm under Deno in Docker
    • Running Elasticsearch in Docker with prorm
    • Running MariaDB in Docker with prorm
    • Running MongoDB in Docker with prorm
  • prorm control plane
    • Introduction
    • Authentication
    • Errors
    • Getting started
      • Service
        • Is it up
        • This description
    • Account
      • Sign-up and verification
        • Create an account
        • Exchange credentials for a token
        • Verify with the emailed code
        • Verify by clicking the emailed link
        • Name the parent or guardian
        • What a consent link is about
        • Give consent for a child's account
        • Ask the parent or guardian again
        • Send a new code and link
      • Family
        • Everyone this account is responsible for
        • One child, in detail
        • Turn a limit on or off
      • Profile
        • Who am I
        • Change the account
        • Every address on the account
        • Add an address
        • Confirm an address with the code mailed to it
        • Mail a fresh code to an unconfirmed address
        • Make an address primary
        • Remove an address
        • What this caller may do
    • Security
      • Sessions
        • Everywhere this account is signed in
        • Sign out everywhere else
        • Sign one out
        • A token for the CLI on a named machine
        • A token for the customer console, from the staff one
        • Park a sign-in for the CLI to collect
        • The CLI collecting its sign-in
        • The team's members' live sessions
        • Sign a member's session out
        • Sign an account out everywhere
        • Everywhere the account is signed in
        • Sign an account's session out
      • Single sign-on
        • Begin a single sign-on
        • The provider's return
        • Link the signed-in account to a team's provider
        • Which team an address signs in to
        • The team's single sign-on, as a member sees it
        • Set the team's OpenID Connect provider up, or change it
        • Remove the provider
        • The team's domain claims and the DNS record each needs
        • Prove a claimed domain
      • MFA and passwords
        • Start enrolling a second factor
        • Prove the app has it
        • Remove the second factor
        • Ask for a reset link
        • Set a new password with the emailed token
      • Klock
        • Open a device-bound klock session
        • Check in, for the next grant
        • Step up the session asking
        • Rotate the device key
        • Freeze a session
        • Unfreeze a session
        • A guest grant
        • The revocation feed
        • The published keyset
        • What this control plane supports
      • Devices
        • Your devices, or a team's
        • Approve a new device's pairing code
        • One device
        • Rename a device
        • Revoke a device
        • Suspend a device
        • Reinstate a suspended device
        • Wipe a device
        • Ask a device to rotate its key
        • The team's members' devices
        • Revoke a member's device
        • An account's devices
        • Revoke an account's device
        • Wipe an account's device
        • The device fleet
      • Access rules and behaviour
        • The access rules that bear on you
        • Add an access rule
        • This request, as the rules see it
        • One access rule
        • Remove an access rule
        • The behaviour profiles that bear on you
        • Add or change a behaviour profile
        • The profile presets
        • Your behaviour findings
        • Acknowledge a finding
        • One behaviour profile
        • Remove a behaviour profile
        • The team's access rules
        • Add a team access rule
        • Remove a team access rule
        • The team's behaviour profiles
        • Add or change a team behaviour profile
        • Remove a team behaviour profile
        • What the team's profiles caught
        • Acknowledge a team finding
      • Recovery and lockdown
        • Ask for a recovery link
        • Recover access with the emailed code
        • Is the account locked down
        • Lock the account down
        • Release a lockdown
        • Lock a member down
        • Release a member's lockdown
      • MCP tokens
        • Make a delegated token for one MCP client
        • The account's delegated tokens
        • Revoke a delegated token
        • What a delegated token may do now
        • Run one MCP tool with a delegated token
        • Run a device-signed MCP tool call relayed by the MCP Worker
      • Kerberos
        • Give the team its own Kerberos realm
        • The team's realm
        • Remove the team's realm
    • Logging and monitoring
      • Audit log
        • What has been done to the account
        • What has happened to this account
        • The account's audit trail
      • Operations
        • Everything that has been asked of this database
        • One, with its steps
        • Stop it
        • Put a failed one back in the queue
        • Every operation, across all accounts
      • Metrics and events
        • Every measurement, for a graph
        • Who did what to it
    • Billing
      • Plans and pricing
        • What the plans allow
        • The rate card
        • What one database would cost
        • What this account is paying for, itemised
      • Subscriptions and invoices
        • What this month's invoice will say
        • What this account is on
        • What it has been charged
        • Start a Stripe Checkout session
        • Open the customer portal
        • Stripe's events
        • Buy more connection pools
      • Team billing
        • The team's billing account
        • What the team has been charged
        • What this month's invoice will say
        • The team's cards
        • Add a card, through a Stripe-hosted setup session
        • Make a card the team's default
        • Remove a card
        • Start the team paying
        • Open the Stripe portal on the team's customer
        • Change the team's plan
        • Who receives the team's bills
        • How the team pays for transfers
    • Support
      • Support chat
        • My conversations
        • Start a conversation
        • Every support conversation, open first
        • A ticket for the socket
        • One conversation, with who is in it and who is connected
        • Rename a group; open or close a support conversation
        • The lines, oldest first
        • Say something
        • Add somebody
        • Mark read
    • Administration
      • Users
        • Every account
        • One account, with everything hanging off it
        • Grant or revoke admin
        • Verify an account by hand
        • Lock or unlock sign-in
        • Allow or hold provisioning
        • Send the verification mail again
        • Set the plan by hand
      • Platform
        • Every database and store, across all accounts
        • The counts worth putting on a dashboard
      • Staff and permissions
        • What kind of admin the caller is, and which scopes they hold
        • The admin presets
        • Every admin, and the scopes each resolves to
        • Make an account an admin of a kind
        • Change an admin's kind, or a custom admin's scopes
        • Revoke admin
      • Team administration
        • Every team, with its owner and size
        • One team in full — members with their accounts, and projects
        • Hand the team to another member
        • Put an account in the team, active at once
        • Change a member's role
        • Remove a member
      • Assumed identities
        • Assume an identity — act as a customer account
        • The identities the caller holds open
        • End an assumed identity
      • Support inbox
        • The platform's addresses
        • Add a platform address
        • One address, with its counts
        • Change an address's label, routing, or whether it accepts mail
        • Remove an address that holds no mail
        • Make, adopt or repair the address's routing rule
        • Every admin's personal address, made where missing
        • File a raw message, as if it had arrived
        • The inbox
        • One message, whole
        • Mark a message
        • Hand a message to an admin, or take it back
        • Leave an internal note
        • Reply, from the address the message came to
        • What is waiting
    • Databases
      • Databases
        • Data stores
          • Every data store on the account
          • Provision a data store
          • Change a data store that is already running
          • One data store
          • Deprovision it
          • Report what it is using
          • How to reach a data store
        • Connections and credentials
          • The api keys on a database
          • Issue a key
          • Revoke a key
          • The engine users we created
          • Create a user inside the database
          • Give a user a new password
          • Drop a user
          • How the database is reached
          • Set how it is reached
          • Revoke every api key on it
          • How to connect to it
          • The ssh keys that open its bastion
          • Add a key, or have one made
          • The private half of a generated key, once
          • Revoke an ssh key
        • Schema and objects
          • The SQL objects we put in it
          • Create one, and apply it
          • What is in the database, as the engine reports it
          • One table
          • What it would run, without running it
          • Redefine an object in place
          • Drop it
          • The extensions installed in it
        • Migrations
          • A plan compiled to statements, recording nothing
          • The migrations recorded for it
          • Record one
          • Apply everything recorded and not yet run
          • Apply everything pending, oldest version first
        • Lifecycle
          • Grow or shrink it
          • Stop it accepting connections
          • Start it again
          • Move it to another region
        • Backups and replicas
          • Take a backup
          • The backups it has
          • Restore one into it
          • What has been restored into it, and from where
          • Its read copies
          • Add one
        • Policies
          • The catalog
          • One policy
          • What this database is held to
          • Switch a policy on, or change its knobs
          • Switch it off
          • Mark the policies reviewed
          • Evaluate the periodic policies now
          • Who is behind a credential
        • Passwordless
          • The database's passwordless sessions
          • Issue a passwordless session (v1)
          • Revoke a passwordless session
          • Bind a session to a device key
          • Issue a v2 session for a host to bind
          • Redeem an enrolment ticket on the host
          • Check a passwordless credential
          • Run one described query under a passwordless credential
        • Database roles
          • The database's roles
          • Define a role
          • One role
          • Change what a role permits
          • Delete a role, and revoke every key granted it
          • Grant a role, which mints a key
          • Who holds a role
          • The api keys bound to a role
        • Pools
          • A database's connection pools, and how busy each is
          • Open another pool
          • Rename a pool or change its size
          • Close a pool
        • Data plane
          • Run a query against a database
          • Several statements, in order, over one connection
          • Is this database answering
          • What the proxy itself is holding
        • Transfers
          • The strategies this account's tier may use
          • Price a transfer without creating it
          • The account's transfer jobs, newest first
          • Create a transfer job
          • One job, and whether its certificate holds
          • Cancel an unfinished job
          • Start a created job, confirming its price
          • Report a job's status (the runner, or the owner's side of a local run)
        • Every database on the account
        • Provision a database
        • Change a database that is already running
        • One database
        • Deprovision it
        • Read or write it
        • Report what it is using
        • The engines this API will provision
        • Where a managed database can be put
    • Teams
      • Teams
        • Members
          • Who is on it
          • Invite somebody
          • Accept an invitation
          • Change somebody's role
          • Remove somebody
        • Projects
          • The projects a team runs
          • Start one
          • Rename a project, or move its environment
          • Delete a project
          • One project, and what is in it
          • Put a database or store in it
          • What is in a project
          • Take one out
        • The teams this account is on
        • Start one
        • The twelve roles, and what each may do
        • Rename a team
        • Close a team
        • One team
        • Hand the team to somebody else
        • Leave a team
    • Schemas
      • Error
      • ValidationErrors
      • Token
      • PolicyCategory
      • PolicySeverity
      • PolicyAction
      • PolicyTrigger
      • PolicyParam
      • Policy
      • PolicyCatalog
      • PolicyAssignment
      • PolicyOutcome
      • PolicyFiring
      • CredentialTrace
      • Relation
      • Restrictions
      • ChildSummary
      • SignupRequest
      • SigninRequest
      • UpdateMeRequest
      • User
      • Address
      • GeoPoint
      • D1Region
      • Usage
      • UsageReport
      • Resource
      • Database
      • DataStore
      • NewDatabase
      • NewDataStore
      • QueryRequest
      • DatabasePrivilege
      • ApiKey
      • DbUser
      • Access
      • AccessRequest
      • DatabaseObject
      • NewDatabaseObject
      • NewMigration
      • SchemaOperation
      • Migration
      • Operation
      • Session
      • AdminPowers
      • Admin
      • AuditEntry
      • TeamRole
      • Conversation
      • ChatMessage
      • TeamSso
      • Team
      • TeamMember
      • SshKey
      • ConnectionInfo
      • InboxAddress
      • InboxMailbox
      • InboxMessageSummary
      • InboxMessage
      • InboxNote
      • Page
      • Quote
      • Plan
      • ApiError
      • CapabilityRefusal
      • KlockErrorCode
      • PageWindow
      • SessionView
      • KlockStepUpRequest
      • KlockOpenRequest
      • KlockOpenedSession
      • UpdateMeResult
      • CapabilitiesView
      • SessionLimits
      • Device
      • DeviceListed
      • DeviceTeamRef
      • DeviceCommand
      • DeviceAuditLine
      • DeviceActionRequest
      • StaffActionRequest
      • ManagedSession
      • SessionRevoked
      • AccessRule
      • AccessRuleRequest
      • BehaviourProfile
      • BehaviourProfileRequest
      • BehaviourProfileSaved
      • BehaviourFinding
      • BehaviourFindingAck
      • StepUpProof
      • Removed
      • MemberLockdownRequest
      • McpClient
      • McpDelegatedView
      • McpToolCall
      • McpForwardRequest
      • PasswordlessScope
      • RoleScope
      • PasswordlessSession
      • PasswordlessTlsMaterial
      • PasswordlessKerberosMaterial
      • ServiceDeviceKeys
      • ServiceSession
      • DatabaseRole
      • TransferEndpoint
      • TransferJobRequest
      • TransferQuote
      • TransferStrategy
      • TransferJob
      • TransferJobAccess
      • Pool
      • PoolAllowance
      • BillingSubscription
      • Invoice
      • BillingContact
      • PaymentMethod
      • UpcomingCharges
      • TeamBilling
      • TeamKerberosRealm
      • TeamSsoDomain
      • TeamSsoResponse
      • StoreConnection
      • BatchFailure
      • ProxyStatus
  1. guides

Querying

Every read goes through a finder on the model, and every finder compiles the
same FindOptions object into SQL for the active dialect. This guide covers
the finders, each option that shapes the statement, and the SQL that comes out
the other end.
The examples use one small shop schema throughout — users, orders and
products — and every SQL string on this page is what the dialect's builder
produced for that call, captured with the driver stubbed out. Where the engines
differ, the SQL sits in dialect tabs; where they only differ in identifier
quoting ("col" vs `col` vs [col]), one engine is shown.
Models built with prorm.define() send the statement with the bound values
already escaped into it (through the dialect's own escape()), so that is the
form you see here and in the query log. A dialect called directly —
dialect.buildSelectQuery() — returns placeholders plus a separate values
array instead; pipe() shows that form.
import { Prorm, DataTypes } from 'ts-prorm-orm';

export const prorm = new Prorm({ dialect: 'postgres', host: 'localhost', database: 'shop' });

export const User = prorm.define('User', {
  id:          { type: DataTypes.INTEGER(), primaryKey: true, autoIncrement: true },
  name:        { type: DataTypes.STRING(100) },
  email:       { type: DataTypes.STRING(255) },
  age:         { type: DataTypes.INTEGER() },
  status:      { type: DataTypes.STRING(20) },
  preferences: { type: DataTypes.JSON() },
}, { tableName: 'users', timestamps: false });

export const Order = prorm.define('Order', {
  id:        { type: DataTypes.INTEGER(), primaryKey: true, autoIncrement: true },
  userId:    { type: DataTypes.INTEGER() },
  status:    { type: DataTypes.STRING(20) },
  total:     { type: DataTypes.DECIMAL(10, 2) },
  createdAt: { type: DataTypes.DATE() },
}, { tableName: 'orders', timestamps: false });

export const Product = prorm.define('Product', {
  id:    { type: DataTypes.INTEGER(), primaryKey: true, autoIncrement: true },
  sku:   { type: DataTypes.STRING(32) },
  name:  { type: DataTypes.STRING(200) },
  price: { type: DataTypes.DECIMAL(10, 2) },
  stock: { type: DataTypes.INTEGER() },
}, { tableName: 'products', timestamps: false });

How a read becomes SQL#

Every finder funnels into the same pipeline, which is why where, include,
order and the rest behave identically whichever one you call.
The dialect is the only stage that differs per engine: identifier quoting,
pagination syntax, and which clauses are legal all resolve there. That is why
the same FindOptions produces LIMIT ... OFFSET on PostgreSQL and
OFFSET ... FETCH NEXT on MSSQL without your code changing:
import { Op } from 'ts-prorm-orm';

const page = await Order.findAll({
  where: { status: 'paid', total: { [Op.gte]: 100 } },
  order: [['createdAt', 'DESC']],
  limit: 20,
  offset: 40,
});
In order, one findAll call does this:
The sequence shows where the fail-closed WHERE guard
sits — before the builder, so a condition the dialect cannot render throws
instead of being dropped — and that the connection is the transaction's own
when one is passed (or ambient under transactionContext: true), the pool's
otherwise. To build the options object from optional parts rather than by
hand, see pipe() and Q.

The finders#

MethodReturnsNotes
findAll(options)Model[]The workhorse. Everything else is built on it.
findOne(options)Model | nullAdds LIMIT 1.
findByPk(pk, options)Model | nullLooks up by primary key.
findOneOrFail(options)ModelThrows EmptyResultError instead of returning null.
findByPkOrFail(pk, options)ModelSame, by primary key.
findLast(options)Model | nullOrders by primary key descending, LIMIT 1.
findAndCountAll(options){ rows, count }Rows for the page, count for the whole set.
findOrCreate(options)[Model, created]Finds by where, inserts defaults if missing.
findOrBuild(options)[Model, built]Same, but does not insert.
count(options)numberSELECT COUNT(*).
exists(where)booleanA count under the hood.
min / max / sum / avgnumberReal SQL aggregates.
findInBatches(options, handler, { batchSize })numberKeyset pagination over the whole table.
findEach(options, handler, { batchSize })numberSame, one row at a time.
The single-row finders are where engines first diverge — SQL Server has no
LIMIT, so "one row" becomes TOP(1):
const ada   = await User.findOne({ where: { email: 'ada@example.com' } });
const byKey = await User.findByPk(42);

where#

Conditions are plain objects. Keys at the same level are AND-ed; operators
live under the column as symbol keys.
import { Op } from 'ts-prorm-orm';

await User.findAll({
  where: {
    name:  { [Op.in]: ['a', 'b'] },
    age:   { [Op.between]: [10, 50] },
    email: { [Op.like]: '%@example.com' },
  },
});
Op.or / Op.and nest:
await User.findAll({
  where: { [Op.or]: [{ age: { [Op.lt]: 25 } }, { status: 'off' }] },
});
A realistic filter mixes both — "paid or shipped orders between 50 and 500":
await Order.findAll({
  where: {
    status: { [Op.in]: ['paid', 'shipped'] },
    total:  { [Op.between]: [50, 500] },
  },
});
The complete operator set — comparison, pattern, range, array, JSON, spatial,
full-text — is in Query operators. A condition the
active dialect's builder cannot render throws UnsupportedWhereError before
the statement is sent, rather than running without it; what is refused, and
why, is in Query safety.

Filtering on an included table#

$alias.column$ inside where refers to a column on an eagerly-loaded
association. It is rewritten onto that include so it restricts the parent
rows, before LIMIT is applied:
await User.findAll({
  include: [{ model: Post, as: 'posts' }],
  where: { '$posts.status$': 'published' },
});
Referring to an alias you did not include raises an AssociationError rather
than silently dropping the condition. See Eager loading.

attributes#

Select a subset of columns, or exclude a few:
await User.findAll({ attributes: ['id', 'name'] });
await User.findAll({ attributes: { exclude: ['email'] } });
exclude is expanded into an explicit list rather than emitted as
SELECT * EXCEPT(...), because most dialects have no such syntax.
Aliased expressions use the [expression, alias] form together with
prorm.fn() / prorm.col():
await User.findAll({
  attributes: ['status', [prorm.fn('COUNT', prorm.col('id')), 'total']],
  group: ['status'],
});

order#

await User.findAll({ order: [['age', 'DESC'], ['name', 'ASC']] });
order must be an array. The accepted entry shapes, all verified against
findAll:
FormResult
[['name','DESC'], ['id','ASC']]ORDER BY "name" DESC, "id" ASC — the form to prefer
['name DESC']ORDER BY name DESC — raw, passed through unquoted
[asc('a'), desc('b')], random()see the helpers below
prorm.fn(...) expressionsrendered as the function call
Two shapes that look reasonable and are not supported:
FormWhat actually happens
order: 'name DESC' (a bare string, not in an array)silently ignored — no ORDER BY is emitted at all and rows come back unordered
order: ['name', 'DESC'] (a flat pair)read as two column names, so it fails with no such column: DESC
order: [{ name: 'DESC' }] (map form)throws itemArr is not iterable on most dialects; only MSSQL, Snowflake and Oracle accept it
[!WARNING] A bare string is silently ignored
order: 'name DESC' compiles to no ORDER BY at all, and nothing throws.
Always wrap in an array, and prefer the nested-array form.
The asc() / desc() / random() helpers are exported at the package root:
import { asc, desc, random } from 'ts-prorm-orm';

await User.findAll({ order: [desc('name')] });        // ORDER BY "name" DESC
await User.findAll({ order: [asc('a'), desc('b')] }); // ORDER BY "a" ASC, "b" DESC
await User.findAll({ order: random() });              // see below
"Three random products" shows both the quoting and the sort key changing per
engine:
await Product.findAll({ order: [desc('price'), asc('name')] });
await Product.findAll({ order: random(), limit: 3 });
Field names are quoted with the dialect's own identifier rules ("a",
`a`, [a]). random() resolves to whatever each engine actually uses for
a shuffling sort key:
SQLDialects
RANDOM()SQLite, Turso, PostgreSQL, TimescaleDB, Greenplum, YugabyteDB, CrateDB, CockroachDB, Redshift, Vertica, Exasol, DuckDB, Snowflake, Trino
RAND()MySQL, MariaDB, TiDB, SingleStore, Databricks, Firebird, SAP HANA, Db2, Spanner
rand()ClickHouse
NEWID()SQL Server
DBMS_RANDOM.VALUEOracle
SQL Server is the one worth knowing: T-SQL's RAND() is evaluated once per
query, so ordering by it does not shuffle at all — NEWID() is the correct
idiom and is what you get. A dialect with no usable random sort key (QuestDB)
throws a message naming the dialect rather than guessing.

limit, offset and pagination#

const page = 3, perPage = 20;
const { rows, count } = await Order.findAndCountAll({
  where: { status: 'paid' },
  order: [['id', 'ASC']],
  limit: perPage,
  offset: (page - 1) * perPage,
});
const pages = Math.ceil(count / perPage);
[!TIP]
SQL Server's OFFSET … FETCH is only legal after an ORDER BY, so give every
paged query an explicit order — which you want anyway, since without one
no engine promises a stable page.
findAndCountAll drops limit/offset from the count query but keeps
everything else that narrows the set, so count describes the full result and
rows describes the page.
For walking a large table, prefer keyset iteration over OFFSET:
await Order.findInBatches({ where: { status: 'paid' } }, async (batch) => {
  await ship(batch);
}, { batchSize: 500 });
The first round is
(SELECT TOP(500) … ORDER BY [id] ASC on SQL Server), and each later round
adds "id" > <last seen>, so the cost does not grow as you get deeper into the
table. findEach is the same loop with a per-row handler.
[!TIP]
OFFSET 100000 still reads and discards 100,000 rows. Keyset iteration seeks
straight to id > last, so use findInBatches for exports and backfills and
keep offset for user-facing page numbers.

group and having#

const byStatus = await Order.findAll({
  attributes: [
    'status',
    [prorm.fn('COUNT', prorm.col('id')), 'orders'],
    [prorm.fn('SUM', prorm.col('total')), 'revenue'],
  ],
  group: ['status'],
  having: { status: { [Op.ne]: 'cancelled' } },
  raw: true,
});
// [{ status: 'paid', orders: 42, revenue: 5120.5 }, …]
having accepts the same operators as where, including Op.* symbol keys.
groupType: 'rollup' | 'cube' | 'grouping' and groupingSets emit
ROLLUP(...), CUBE(...) and GROUPING SETS (...) on dialects that have them
(PostgreSQL, SQL Server; MySQL has WITH ROLLUP only). The same goes for
distinctOn and sample (TABLESAMPLE, PostgreSQL). A dialect that cannot
render one of these refuses the query rather than running it without it.

distinct#

await User.findAll({ attributes: ['status'], distinct: true });

Aggregates#

const paidOrders = await Order.count({ where: { status: 'paid' } });
const revenue    = await Order.sum('total', { where: { status: 'paid' } });
const biggest    = await Order.max('total');
const smallest   = await Order.min('total');
const average    = await Order.avg('total');
They are real SQL aggregates — nothing is loaded into memory to be summed — and
they honour where, scopes and the paranoid deletedAt IS NULL filter.

Writes#

MethodSQL
create(values)INSERT INTO … VALUES (…)
bulkCreate(rows)one INSERT per row (a loop, not a multi-row VALUES list); individualHooks: true routes each row through create() so per-row hooks fire
update(values, { where })UPDATE … SET … WHERE …
destroy({ where })DELETE FROM … WHERE … (or a deletedAt update on a paranoid model)
truncate()TRUNCATE / DELETE FROM
upsert(values)insert with the dialect's conflict clause
increment / decrementarithmetic in SQL
bulkUpdate(rows, { key })one UPDATE … CASE statement for many rows
update and destroy need a where that selects rows: with no where, or
an empty one (where: {}), they throw Missing where option in update /
… in destroy before anything is sent. Pass all: true to write the whole
table on purpose (Order.destroy({ all: true })). Before 4.9.2, update
without a where and destroy({ where: {} }) changed every row. See
Bulk operations.

increment / decrement#

The arithmetic happens in the database, so two concurrent increments do not
lose each other:
await Product.increment('stock', { where: { id: 7 }, by: 5 });
await Product.decrement({ stock: 2 }, { where: { id: 7 } });
decrement is increment by the negated amount, which is why it renders as
+ -2.

bulkUpdate#

Different values for many rows in a single round trip:
await User.bulkUpdate([{ id: 1, status: 'x' }, { id: 2, status: 'y' }], { key: 'id' });
Rows the WHERE does not match are untouched, and the ELSE keeps columns
that a given row did not supply. See Bulk operations.

upsert#

await Product.upsert({ id: 1, sku: 'KB-01', name: 'Keyboard', price: 49 });
The conflict clause is per dialect — ON CONFLICT … DO UPDATE on
SQLite/PostgreSQL, ON DUPLICATE KEY UPDATE on MySQL/MariaDB, MERGE on
SQL Server and Oracle:
The MERGE statement
On a define() model the upsert is bracketed by a primary-key SELECT before
and after it (SELECT * FROM "products" WHERE "id" = 1 LIMIT 1), which is how
it reports whether the row was created and returns the stored row.

findOrCreate#

const [user, created] = await User.findOrCreate({
  where: { email: 'ada@example.com' },
  defaults: { name: 'Ada', age: 36 },
});
[!CAUTION]
The select and the insert are two statements. Two requests racing on the same
where can both see "missing" and both insert — back the where columns with
a unique index, and run the call in a transaction, so
the loser fails instead of duplicating.

Common table expressions#

await Order.findAll({
  cte: [{ name: 'big_orders', query: 'SELECT * FROM orders WHERE total >= 500' }],
  tableName: 'big_orders',
  order: [['total', 'DESC']],
});
tableName overrides the FROM target so the query reads from the CTE instead
of the model's own table. Recursive CTEs are built the same way with
recursive: true on the CTE entry.

Related-row counts without loading rows#

const users = await User.findAll({ withCount: ['posts'] });
users[0].postsCount; // number
This issues one extra query per association (not per parent row) —
SELECT * FROM "posts" WHERE "userId" IN (…) — and tallies the rows in memory.
It avoids the N+1 problem, but it does still transfer the child rows, so for
very large children prefer an explicit grouped count().

Raw rows#

raw: true skips instance construction and hands back plain objects. Use it
for grouped aggregates that map to no model row, and for hot read paths.
const rows = await User.findAll({ raw: true });
rows[0].save; // undefined — these are plain objects

Logging and benchmarking a single query#

await User.findAll({
  where: { status: 'active' },
  logging: (sql, ms) => console.log(sql, ms),
  benchmark: true,
});
logging: false silences one query on an otherwise-logging connection. See
Logging.

Choosing a connection#

using: 'analytics' routes one query to another connection registered on the
same ConnectionManager,
leaving the model's other queries where they are.

Things to know#

Row locking. Every documented lock shape compiles — true, a level
string, { of: Model }, and the { level, nowait, skipLocked } object form.
A job queue that claims one unlocked row at a time:
await prorm.transaction(async (t) => {
  const [next] = await Product.findAll({
    where: { id: 7 },
    lock: { level: 'UPDATE', skipLocked: true },
    transaction: t,
  });
});
The full matrix:
lockPostgreSQLMySQLOracleSQL Server
true / 'UPDATE'FOR UPDATEFOR UPDATEFOR UPDATEWITH (UPDLOCK, ROWLOCK)
'SHARE'FOR SHARELOCK IN SHARE MODEthrowsWITH (HOLDLOCK, ROWLOCK)
'KEY SHARE' / 'NO KEY UPDATE'FOR KEY SHARE / FOR NO KEY UPDATEthrowsthrowsthrows
{ level: 'UPDATE', nowait: true }FOR UPDATE NOWAITFOR UPDATE NOWAITFOR UPDATE NOWAITWITH (UPDLOCK, ROWLOCK, NOWAIT)
{ level: 'UPDATE', skipLocked: true }FOR UPDATE SKIP LOCKEDFOR UPDATE SKIP LOCKEDFOR UPDATE SKIP LOCKEDWITH (UPDLOCK, ROWLOCK, READPAST)
{ skipLocked: true } (no level)FOR UPDATE SKIP LOCKEDFOR UPDATE SKIP LOCKEDFOR UPDATE SKIP LOCKEDWITH (UPDLOCK, ROWLOCK, READPAST)
{ of: Model }FOR UPDATE OF "users"FOR UPDATE OF `users` FOR UPDATEWITH (UPDLOCK, ROWLOCK)
SQL Server expresses locking as a table hint, not a trailing clause, which
is why it looks different — and why scoping a lock to a different table
throws there rather than silently locking the wrong one. A level a dialect
lacks throws naming the supported levels; nowait and skipLocked together
throw as mutually exclusive.
Lock-less dialects (SQLite) drop lock silently — the transaction it would
protect is already serialised by the engine.
union. Forwarded, with the branch values bound correctly:
await Active.findAll({ where: { status: 'a' }, unionType: 'UNION ALL',
                       union: [{ model: Archived, where: { status: 'x' } }] });
EXCEPT and INTERSECT work the same way, and findAndCountAll /count() /
exists() count over the combined query, so count and rows.length agree:
Because the set operator dedupes inside the derived table, UNION and
UNION ALL count correctly without special-casing. The outer limit/offset
and order are excluded from the count — none can change it, and several
dialects reject ORDER BY in a derived table.
[!WARNING]
Combining union with a top-level limit is broken on SQLite — the
dialect emits LIMIT before the UNION keyword and SQLite rejects it
(LIMIT clause should come after UNION ALL not before). Put the limit on
each branch, or use prorm.query().
transaction. Thread transaction: t through every call that should be
part of the transaction — see Transactions.

Next: Query operators — comparisons, ranges, pattern matching and JSON access.

Related reading#

Query operators — every Op.*
Eager loading — include, nested and filtering includes
Scopes — reusable FindOptions fragments
Raw queries — prorm.query(), replacements, query types
Bulk operations
Query optimization — explain plans, hints, caching
Modified at 2026-10-04 00:40:16
Previous
Query safety: the fail-closed WHERE guard
Next
Raw Queries & Query Building
Built with