Skip to content

Querying, Scopes, Pagination & Aggregates ​

Calling orm.users.query() (or orm.users.where(...) shorthand) creates a typed ModelQueryBuilder. Every column name you pass to .where(), .orderBy(), .pluck(), or aggregate methods is checked against your model's TypeScript properties and automatically mapped through .column("db_name") and column codecs (Date, boolean, enum, col.custom).


1. Filtering Rows (WHERE) ​

Standard, Object & Grouped Predicates ​

typescript
// 1. Standard 3-argument comparison (`=`, `!=`, `<>`, `>`, `>=`, `<`, `<=`, `like`, `not like`, `starts_with`, `ends_with`, `contains`)
const recent = await orm.users
  .query()
  .where("createdAt", ">=", new Date("2026-01-01"))
  .where("isActive", "=", true)
  .get();

// 2. Object shorthand (`null` values emit `IS NULL` automatically)
const unverifiedAdmins = await orm.users
  .query()
  .where({ role: "admin", deletedAt: null })
  .get();

// 3. Parenthetical grouping with callback
const targetUsers = await orm.users
  .query()
  .where("isActive", "=", true)
  .where((sub) => {
    sub.where("role", "=", "admin").orWhere("email", "ends_with", "@webdb.dev");
  })
  .get();

// 4. Negation helpers
const nonMembers = await orm.users
  .query()
  .whereNot("role", "=", "member")
  .get();

const filtered = await orm.users
  .query()
  .where("role", "=", "admin")
  .orWhereNot((sub) => {
    sub.where("isActive", "=", false);
  })
  .get();

NOTE

Soft-delete filters (deleted_at IS NULL) live in an isolated base filter slot, so chaining .orWhere(...) or .orWhereNot(...) never leaks soft-deleted records.

Set, Range, Null & String Predicates ​

typescript
// Set membership (`whereIn`, `whereNotIn`, `orWhereIn`, `orWhereNotIn`)
// Automatically chunks past 5,000 items & handles empty arrays natively without throwing
const team = await orm.users
  .query()
  .whereIn("id", [alice.id, bob.id])
  .whereNotIn("role", ["banned"])
  .get();

// Inclusive range (`whereBetween`)
const q1Posts = await orm.posts
  .query()
  .whereBetween("createdAt", [new Date("2026-01-01"), new Date("2026-03-31")])
  .get();

// Null checks (`whereNull`, `whereNotNull`, `orWhereNull`, `orWhereNotNull`)
const activeBios = await orm.users.query().whereNotNull("meta").get();

// Typed string predicates (restricted to string columns at compile time)
const search = await orm.users
  .query()
  .whereStartsWith("name", "Al")
  .whereEndsWith("email", "@webdb.dev")
  .whereContains("email", "alice")
  .get();

// SQL LIKE pattern matching
const patternMatch = await orm.posts
  .query()
  .whereLike("title", "%Local-First%")
  .whereNotLike("title", "%Draft%")
  .get();

2. Ordering, Limits & Pagination ​

Sorting (orderBy, latest, oldest) ​

typescript
// Explicit column + direction
const sorted = await orm.posts
  .query()
  .orderBy("published", "desc")
  .orderBy("createdAt", "desc")
  .get();

// Shorthand: defaults to `timestamps.createdAt`, or falls back to the primary key
const newestFirst = await orm.posts.query().latest().limit(10).get();
const oldestFirst = await orm.posts.query().oldest().limit(10).get();

Page-Based Pagination (.paginate) ​

.paginate({ page, perPage }) executes a matching count query and page slice query, returning a PaginationResult:

typescript
const page2 = await orm.posts
  .query()
  .where("published", "=", true)
  .latest()
  .with({ author: true })
  .paginate({ page: 2, perPage: 15 });

console.log(page2.data);     // Array of Post instances with `.relations.author`
console.log(page2.total);    // Total matching rows
console.log(page2.page);     // 2
console.log(page2.perPage);  // 15
console.log(page2.lastPage); // Math.max(1, Math.ceil(total / perPage))
console.log(page2.hasMore);  // boolean

Streaming Large Datasets (lazyById, chunksById, lazy, chunks) ​

When iterating over thousands of records, avoid loading every row into memory at once. The ORM gives you two streaming styles, both supporting .with(...) and .withCount(...) per batch:

  1. Keyset Streaming (Recommended): lazyById(), chunksById(), chunkById() Uses keyset pagination (WHERE id > lastId ORDER BY id LIMIT chunkSize) over the B+Tree index—especially fast with monotonic ULID or integer primary keys. Unlike OFFSET, keyset streaming stays constant-time on deep pages and never skips or duplicates rows if you update or delete records while iterating.
typescript
// Stream one record at a time with eager-loaded author (keyset-paginated in batches of 500)
for await (const post of orm.posts.query().with({ author: true }).lazyById(500)) {
  await syncPostToServer(post);
  if (shouldStop) break; // stops immediately without fetching remaining chunks
}

// Or iterate batch-by-batch as arrays (e.g., for bulk sync uploads)
for await (const batch of orm.posts.where("published", "=", false).chunksById(250)) {
  for (const post of batch) {
    await post.update({ published: true }); // Safe: keyset won't skip subsequent rows!
  }
}

// Callback style (`return false` stops early; optional column & direction args)
await orm.posts.query().chunkById(
  250,
  async (batch, page) => {
    console.log(`Batch ${page}: ${batch.length} posts`);
  },
  "id",
  "desc",
);
  1. Ordered Offset Streaming: lazy(), chunks(), chunk() When you need a custom .orderBy(...) column that isn't unique (such as latest() or sorting by a secondary score), use lazy(), chunks(), or chunk():
typescript
for await (const post of orm.posts.query().latest().lazy(250)) {
  console.log(post.title);
}

for await (const batch of orm.posts.query().latest().chunks(250)) {
  console.log(batch.length);
}

await orm.posts.query().latest().chunk(250, async (batch, pageNumber) => {
  if (pageNumber >= 5) return false; // optional early stop
});

3. Terminal Methods & Aggregates ​

typescript
const all = await orm.users.query().get();
const one = await orm.users.query().where("email", "=", "[email protected]").first();
const mustExist = await orm.users.query().where("id", "=", userId).firstOrFail();

const total = await orm.users.query().where("isActive", "=", true).count();
const any = await orm.users.query().where("role", "=", "admin").exists();

// Pluck decodes values through the column's codec (e.g. Date[], string[], boolean[])
const createdDates = await orm.posts.query().pluck("createdAt"); // Date[]

// Numeric & Date aggregates (return `null` on empty result sets)
const sumViews = await orm.posts.query().sum("views");        // bigint | number | null
const avgScore = await orm.posts.query().avg("score");        // number | null
const earliest = await orm.posts.query().min("createdAt");    // Date | null
const latest   = await orm.posts.query().max("createdAt");    // Date | null

4. Reusable Scopes & Helpers ​

Define typed scopes on static readonly scopes (with or without extra parameters) and invoke them cleanly with .scope(...):

typescript
export class Post extends Model.define({
  table: "posts",
  columns: {
    id: col.ulid().primaryKey().autoUlid(),
    authorId: col.ulid().column("author_id").notNull(),
    title: col.text().notNull(),
    published: col.boolean().default(false),
    createdAt: col.timestamp().column("created_at"),
  },
}) {
  static readonly scopes: {
    published: (q: ModelQueryBuilder<typeof Post>) => void;
    createdAfter: (q: ModelQueryBuilder<typeof Post>, date: Date) => void;
  } = {
    published: (q) => q.where("published", "=", true),
    createdAfter: (q, date) => q.where("createdAt", ">=", date),
  };
}

// Type-checked scope names and parameter types:
const recentPublished = await orm.posts
  .query()
  .scope("published")
  .scope("createdAfter", new Date("2026-01-01"))
  .latest("createdAt")
  .get();

Use .apply(fn) for ad-hoc reusable query helpers and .clone() to branch a base query without mutating it:

typescript
const baseQuery = orm.posts.query().scope("published").clone();

const top5 = await baseQuery.clone().latest().limit(5).get();
const totalPublished = await baseQuery.clone().count();

5. Bulk Mutations & Raw Query Access ​

Update, soft-delete, restore, or hard-delete directly via ModelQueryBuilder:

typescript
// Bulk update (rejects `.readonly()` fields & automatically updates `updatedAt`)
const updatedCount = await orm.posts
  .where("published", "=", false)
  .update({ published: true });

// Bulk soft-delete (or hard-delete when softDeletes is not configured)
const deletedCount = await orm.users
  .where("isActive", "=", false)
  .delete();

// Drop down to the underlying WebDB QueryBuilder whenever you need raw SQL joins or CTEs:
const stats = await orm.db
  .from("posts")
  .select(["author_id", "COUNT(*) as total"])
  .groupBy("author_id")
  .toArray();

Next Steps ​

Released under the MIT License.