---
name: record-queries
description: >-
  Fetch records with defineQuery, ds.list, ds.get and ds.export: where and
  orderBy, field names of your own choosing, pagination and its limits, and the
  filter that keeps each visitor to their own records, with one query per role
  for the fields that role may see. Use to put records on a page, fill a
  dropdown or export them to a file, to write any server function that reads a
  table, or when a read comes back empty, unsorted or missing a field. Writes
  are record-mutations; totals and chart rows are charts-and-metrics.
metadata:
  type: sub-skill
  library: softr-sdk
  library_version: 1.19.0
---

**Boundary.** `ds` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. A route `loader` also runs in the browser, so it calls a server function, never `ds`. A helper that calls `ds` outside a handler, in this file or in another one, goes in `createServerOnlyFn` from `@tanstack/react-start`, or inside the handler. An exported helper without it keeps the server-only import in the browser bundle, and every page stops loading until it moves. Do not make such a helper a server function when it takes an id: any visitor can call a server function with any id. `defineQuery` and every type come from `@softr/sdk` and can be imported anywhere.

# Reading records

`ds` reads records out of a Softr datasource, from the server only.

## Setup

```ts
import { createServerFn } from '@tanstack/react-start'
import { defineQuery } from '@softr/sdk'
import { ds } from '@softr/sdk/server'
```

`ds` is server-only. `defineQuery` only declares a read, so it ships on the root entrypoint and the declaration can sit anywhere.

## Declare the read

Every read takes a query: which datasource, which fields, who it is for.

```ts
const publishedPosts = defineQuery({
  id: 'publishedPosts',
  datasourceId: '00000000-0000-0000-0000-000000000000',
  fields: {
    title: 'fZk3Qm9pLw2Xa1',      // SINGLE_LINE_TEXT
    published: 'Ru7bVx2cNq0Ed9',  // CHECKBOX
    publishedAt: 'Xp2dLh6vKz9Fa3',// DATETIME
    views: 'mB4kQ8yTn1sWc7',      // NUMBER
  },
  permissions: { userGroupTypes: ['NON_LOGGED_IN_USERS', 'LOGGED_IN_USERS'] },
})
```

- `id` is the name the person building the app sees, so `publishedPosts`, not `q1`. It must be unique across the app: no two declarations may share one, queries and mutations counted together.
- `datasourceId` is the opaque UUID from the table's registration on the application (Softr Studio's Data tab, or the `application_register_data_source` tool when an agent does it). It is not the table id and is never derived from the table's name.
- The keys of `fields` are names you choose. The values are field ids, opaque strings the table's schema gives you: `database_get_table` returns them for a Softr table, `integration_list_table_fields` for a table on a connected database. Everything downstream speaks your names: the returned records, `where`, `orderBy`.
- `permissions` declares who may run the query, and the SDK enforces it:
  - `{ userGroupTypes: ['NON_LOGGED_IN_USERS', 'LOGGED_IN_USERS'] }`: everyone, signed out included. `customGroups` narrows only the signed-in half.
  - `{ userGroupTypes: ['NON_LOGGED_IN_USERS'] }`: signed-out visitors only.
  - `{ userGroupTypes: ['LOGGED_IN_USERS'] }`: any signed-in visitor, narrowed to particular groups with `customGroups: ['00000000-0000-0000-0000-00000000000a']`. `customGroups` is added to `userGroupTypes`, never written in place of it.
- Write each group id as a literal in `permissions`. An id taken from a `const` is a lint error.
- Write the object inline in the `defineQuery` call. Passing the declaration or its `fields` through a variable, or spreading one in, widens the field ids to `string` and the types stop checking.

A query fixes the table and the columns. A `filter` also fixes the rows a role may read, for a privacy rule that never changes: see [Keep each visitor to their own records](#keep-each-visitor-to-their-own-records). The filters the user picks, sorting and paging stay at the call site, because a list screen changes them as the user types. Declare as many queries over one datasource as the app needs, each carrying the fields its own screen touches.

## Core Patterns

### List records

```ts
const listPublishedPosts = createServerFn().handler(async () => {
  return await ds
    .list(publishedPosts)
    .where((q) => q.published.is(true))
    .orderBy((q) => q.publishedAt.desc)
    .limit(50)
})
```

Returns `{ records, total, nextOffset }`. Each record is `{ id, fields }`, with `fields` keyed by the query's own names: every declared field is present, `null` when empty, and a field the query does not declare is not returned. `ds.list(publishedPosts)` with no calls chained returns the first 20 records. `limit` is clamped to 100, so more than a hundred records means paginating.

### Filter with the `where` callback

`q` is the argument the callback is handed, not an import. It carries one handle per declared field, offering only the operators that field's type supports, plus `$and` and `$or`:

```ts
await ds.list(publishedPosts).where((q) =>
  q.$and(
    q.published.is(true),
    q.views.gte(100),
    q.$or(q.title.contains('cafe'), q.title.startsWith('The')),
  ),
)
```

Calling `.where` more than once ands the filters together, and the query's `filter` too, so a `where` only narrows the rows. Only the query's own fields can be filtered or sorted on, so a field you need in a `where` belongs in `fields` even when the page never displays it. Load [references/filters-and-sorting.md](./references/filters-and-sorting.md) when you need an operator this page does not show, or when a filter is rejected.

### Sort

```ts
.orderBy((q) => q.publishedAt.desc)
.orderBy((q) => [q.views.desc, q.title.asc])   // array for tie-breakers
```

### One builder, one read

`where` and `orderBy` add to the builder they are called on and return that same builder. A builder kept in a variable carries its filters and sorts into every later read, with no error. Start each read from its own `ds.list`, `ds.get` or `ds.export`:

```ts
// Wrong: the second read asks for open AND closed, and returns no records.
const list = ds.list(orders)
const open = await list.where((q) => q.status.is('open'))
const closed = await list.where((q) => q.status.is('closed'))

// Right: one builder for each read.
const open = await ds.list(orders).where((q) => q.status.is('open'))
const closed = await ds.list(orders).where((q) => q.status.is('closed'))
```

- A loop with one filter per pass, such as one count per tab, starts a new builder on each pass.
- A second `orderBy` on the same builder only breaks the ties of the first.
- A reused `ds.export` builder writes a file with only the records that match every filter it collected.
- To add a filter only when an input is set, reassign the builder before its one read: `if (search) list = list.where(...)`, as in [Keep a large table on the server](#keep-a-large-table-on-the-server).

### Get one record

```ts
const post = await ds.get(publishedPosts, { id: postId })
if (post === null) throw notFound()
```

A record that does not exist comes back as `null`, not an error. A chained `.where` narrows which record the id may resolve to, and a record that does not match reads as `null` too:

```ts
const post = await ds
  .get(publishedPosts, { id: postId })
  .where((q) => q.published.is(true))
```

There is no `orderBy`, `limit` or `offset` on a get. To find a record by a field instead of its id, use `ds.list` with a `limit` of 1.

### Paginate

```ts
const first = await ds.list(publishedPosts).limit(50)
if (first.nextOffset !== null) {
  const second = await ds.list(publishedPosts).limit(50).offset(first.nextOffset)
}
```

`nextOffset` is `null` when there are no more pages. `total` is the count of all matching records, not the count returned.

To read every matching record, use `ds.export` (see [Export records](#export-records)), not a loop over `ds.list` pages.

Pass `nextOffset` back unchanged, and type whatever carries it (a validator, a state, a search param) as `number | string | null`. Most datasources answer a number, the row position, and for those a page can also be reached directly, `.offset((page - 1) * PAGE_SIZE)`. Some datasources (BigQuery is one) answer a string, their own cursor: it reads only the page after the one that answered it, with the same `where` and `orderBy`, and a read with a computed number fails. For those, build "Load more" or next-page paging from `nextOffset`, never numbered pages.

### Keep a large table on the server

A read returns at most 100 records, and a cursor datasource reads a page only after the one before it. A loop over every page makes one request per 100 records, one after another, and the page shows nothing until the last one answers. On a table of thousands of records, that is a long wait each time the page opens.

So a list or table page reads one page at a time:

- Search, filters and sort go into `where` and `orderBy`, and the server function takes them as input. A change reads the first page again.
- "Load more" or a next-page button reads the next page from `nextOffset`.
- Counts, totals, averages, group tables and summary strips come from `ds.metric` and `ds.chart` with the same `where` (see [charts-and-metrics](../charts-and-metrics/SKILL.md)), never from math over loaded records.
- Every matching record is for a download the visitor starts, and comes from `ds.export` (see [Export records](#export-records)). Never read every record to show a page, unless the user asks for it again (see below).

```ts
// Wrong: every page before anything shows, then filters and figures in the browser.
let offset: number | string | null = null
do {
  const page = await ds.list(customers).limit(100).offset(offset)
  rows.push(...page.records)
  offset = page.nextOffset
} while (offset !== null)

// Right: one page of the records that match the visitor's filters.
const listCustomers = createServerFn()
  .validator(z.object({ search: z.string().optional(), offset: z.union([z.number(), z.string()]).nullable() }))
  .handler(async ({ data }) => {
    const { search, offset } = data
    let list = ds.list(customers).orderBy((q) => q.signedUpAt.desc).limit(50).offset(offset)
    if (search) list = list.where((q) => q.name.contains(search))
    return await list
  })
```

A request to load the whole table into the browser, so that filters feel instant, asks for a fast page. Build it as above, and tell the user in your reply why the reads stay on the server. When they ask for it again after that reply, build it as they ask: the page reads its records with `ds.export`. Say in your reply what it costs: the page reads every record each time it opens, so it opens more slowly as the table grows.

### Export records

`ds.export` reads every record that matches, for a file the visitor downloads or copies: a CSV, a JSON file, a spreadsheet. It takes the same `where` and `orderBy` as `ds.list`, and no `limit` or `offset`. Give it the list's filters, so the file holds what the visitor sees:

```ts
const exportCustomers = createServerFn()
  .validator(z.object({ search: z.string().optional() }))
  .handler(async ({ data }) => {
    const { search } = data
    let rows = ds.export(customers).orderBy((q) => q.signedUpAt.desc)
    if (search) rows = rows.where((q) => q.name.contains(search))
    return await rows
  })
```

- It returns `{ records }`, every matching record. Each record has the same shape as a `ds.list` record.
- A large table takes seconds. Call it from the button that starts the download, and show that the file is being prepared. Never call it from a loader or when a page opens, unless the user asks again for the whole table in the browser (see above).
- Each call to the datasource reads 1,000 records. When the datasource's API refuses pages that big, or the user names a page size, set it with `.pageSize(200)`, from 1 to 1,000.
- Build the file from `records`, in the format the user asked for.
- Every exported record reaches the visitor, so the query reads through the same `filter` as the list, and declares only the fields the visitor may download.

### Populate a control from a linked table

A `LINKED_RECORD` field on a record answers with `{ id, label }` — the label is the linked record's primary field, and the id is what a write or a `where` filter takes. To fill a filter dropdown or form select with **all** options from the linked table (not just the values already referenced by existing records), query the linked table's own datasource:

```ts
// "status" on the products table is a LINKED_RECORD pointing to the Product Statuses table
const productStatuses = defineQuery({
  id: 'productStatuses',
  datasourceId: '00000000-0000-0000-0000-000000000001', // the linked table's datasource id
  fields: { name: 'fZk3Qm9pLw2Xa1' },
  permissions: { userGroupTypes: ['NON_LOGGED_IN_USERS', 'LOGGED_IN_USERS'] },
})

const listProductStatuses = createServerFn().handler(async () => {
  return await ds.list(productStatuses).limit(100)
})
```

Each returned record is one option: `record.id` is the value a `where` filter and a mutation payload take; `record.fields.name` is what you display.

```tsx
// Filter dropdown
{statuses.map((s) => (
  <option key={s.id} value={s.id}>{s.fields.name}</option>
))}

// Filtering the main table by the selected linked record
ds.list(products).where((q) => q.status.is(selectedStatusId))
```

For a picker that searches and pages, `ds.options` answers the shape a linked-record picker's `load` takes, `{ options: [{ id, label }], nextOffset }`, searched on the label field when a term is given:

```ts
const loadProductStatuses = createServerFn()
  .validator(z.object({ term: z.string(), offset: z.number().nullable() }))
  .handler(({ data }) => ds.options(productStatuses, { label: 'name', ...data }))
```

`ds.options` takes no `where`, but it reads through the query's `filter`. A picker over a filtered table takes the filtered query.

Skip this request when the options are predefined and fixed — hardcode them instead.

A `SELECT` field's options are its choices, and the builder can add and rename them in Studio after the app is built. When a dropdown should follow those changes, read them with `ds.choices`. When the app means a fixed choice, such as a "Done" tab, use its id directly. A mistyped id is not caught at compile time, and a write with an id the field lacks adds it as a new choice. `ds.choices` takes any query or mutation that declares the field and answers `[{ id, label, color }]` as the field holds them now. Each `id` is what a `where` and a write take, for a filter dropdown and a form select alike:

```ts
// `products` declares `category`, a SELECT field
const loadCategories = createServerFn().handler(() => ds.choices(products, 'category'))
```

A read the datasource turns down throws rather than coming back empty, and it throws a plain `Error` carrying the status, followed by the reason the datasource gives when it sends one. There is no typed predicate to narrow it with. Handle it where you would handle any other failed fetch: an `errorComponent` on the route, or a check in the handler.

## Keep each visitor to their own records

`permissions` decides who may run a query. `filter` decides which rows it reads. A visitor can call every server function with any arguments, so a privacy rule from the builder's prompt, such as "clients see only their own bookings", goes into the `filter` of the table's queries, never into the code of one server function. `ds` applies the filter on every `ds.list`, `ds.get`, `ds.options`, `ds.chart` and `ds.metric` of the query, and a `where` cannot widen it. Keep `where` for the filters the visitor picks at runtime: a search, a tab, a dropdown.

The examples below use `bookings`, a table where staff read every booking and a client reads only their own.

### Declare the filter

```ts
// `client` links to Users. 'Rk2mVx9pQa4Lz7' is the Record ID field of the users table,
// declared in softr.json under user.properties.
const myBookings = defineQuery({
  id: 'myBookings',
  datasourceId: '00000000-0000-0000-0000-000000000002',
  fields: { title: 'Lb7yQe3vXa9Ns1', date: 'Xp2dLh6vKz9Fa3', status: 'Ru7bVx2cNq0Ed9' },
  filterFields: { client: 'Pc8vNm3kTq6Wz2' },
  filter: { client: { isOneOf: ['USER:::Rk2mVx9pQa4Lz7'] } },
  permissions: { userGroupTypes: ['LOGGED_IN_USERS'], customGroups: ['00000000-0000-0000-0000-00000000000c'] },
})

const getMyBooking = createServerFn()
  .validator(z.object({ id: z.string() }))
  .handler(({ data }) => ds.get(myBookings, { id: data.id }))
```

- The keys of `filter` are aliases of `filterFields`, with the same operators as `where`. Declare the two together. A read returns only `fields`, so a field that only the filter needs, such as the owner, never reaches the browser. A field that the page shows and the filter reads goes in both. A `where` names aliases of `fields` only.
- The keys of one object combine with AND. `$and` and `$or` take a list of filters. A filter has at most 4 group levels.
- A get of an id that the filter excludes reads as `null`, the same as a missing record.
- Write the filter inline, as literals, like the rest of the declaration.

Write a token in the form the Studio condition builder stores:

| Token | Value |
| --- | --- |
| `{USER:::EMAIL}`, `{USER:::EMAIL_DOMAIN}` | The visitor's email, and its domain. With braces |
| `USER:::<field id>` | A field of the visitor's row in the users table, declared in `user.properties`. No braces |
| `PREDEFINED:TODAY`, `PREDEFINED:YESTERDAY`, `PREDEFINED:TOMORROW` | That day |
| `FIXED_DATE:DAYS_AGO:<n>`, `FIXED_DATE:DAYS_FROM_NOW:<n>` | A day relative to today |

There are no other tokens: a value from the URL, the page or a form goes into a `where`. A filter can only compare a field of this table: it cannot follow a link to the owner of another table (see [A table that belongs to the visitor through its parent](#a-table-that-belongs-to-the-visitor-through-its-parent)).

### A link to Users

A link to the users table holds the id of the visitor's row in that table, not `context.user.id`. Compare it with a Record ID field of the users table:

1. Find a `RECORD_ID` field in the users table's datasource doc. When the table has none, add a field of type `RECORD_ID` to it.
2. Declare that field in `softr.json` under `user.properties`. The key is an alias you choose, and the value is the field id:

   ```json
   "user": { "properties": { "recordId": "Rk2mVx9pQa4Lz7" } }
   ```

3. Compare the link with `USER:::<that field id>`, here `USER:::Rk2mVx9pQa4Lz7`.

A token on a field that `user.properties` does not declare throws. An email field that holds the owner's email compares with `{USER:::EMAIL}` and needs no declaration. See [current-user](../current-user/SKILL.md#fields-of-the-visitors-row-userproperties) for `user.properties`.

### A field that holds several values

Compare a field of the visitor that can hold several values, such as a link to their teams, with `isOneOf`. With `is`, a visitor in two teams reads no rows.

```ts
// 'Tm6cBq1wZe8Ys4' is the teams link of the users table, declared in user.properties.
filter: { team: { isOneOf: ['USER:::Tm6cBq1wZe8Ys4'] } }
```

A field of the record that holds several values takes `isOneOf` too: `members: { isOneOf: ['USER:::Rk2mVx9pQa4Lz7'] }` keeps the projects the visitor is a member of.

### Signed out, or no value

A condition on a user token matches no rows for a visitor who is signed out, or for a user whose field is empty, such as a user in no team. The read answers an empty list, and a get answers `null`. In an `$or`, the other branches still match:

```ts
// `ownerEmail` is in filterFields only, so public rows do not show it.
filter: { $or: [{ ownerEmail: { is: '{USER:::EMAIL}' } }, { visibility: { is: 'public' } }] }
```

### Every query over the table takes the filter

A privacy rule belongs to the table, not to the page where it came up. Every query that a role reads the table with carries the same `filter`: the list, the detail, a search, a picker, a count and a chart. This includes a query you add later for a new page or widget. A query without the filter is a second path to the same rows. Reuse the table's queries where you can. A new query with other fields copies `filter` and `filterFields`:

```ts
// Wrong: no filter. Every client reads every booking through this query.
const nextBookings = defineQuery({
  id: 'nextBookings',
  datasourceId: '00000000-0000-0000-0000-000000000002',
  fields: { date: 'Xp2dLh6vKz9Fa3' },
  permissions: { userGroupTypes: ['LOGGED_IN_USERS'], customGroups: ['00000000-0000-0000-0000-00000000000c'] },
})

// Right: the same filter as every other query of bookings for clients.
const nextBookings = defineQuery({
  id: 'nextBookings',
  datasourceId: '00000000-0000-0000-0000-000000000002',
  fields: { date: 'Xp2dLh6vKz9Fa3' },
  filterFields: { client: 'Pc8vNm3kTq6Wz2' },
  filter: { client: { isOneOf: ['USER:::Rk2mVx9pQa4Lz7'] } },
  permissions: { userGroupTypes: ['LOGGED_IN_USERS'], customGroups: ['00000000-0000-0000-0000-00000000000c'] },
})

const loadNext = createServerFn().handler(() =>
  ds.list(nextBookings).where((q) => q.date.gte(new Date().toISOString())).orderBy((q) => q.date.asc).limit(3),
)
```

The update and the delete of these records take the same filter: see [record-mutations](../record-mutations/SKILL.md#change-only-the-records-the-visitor-may-read). A count or a chart reads through the filter of its query: see [charts-and-metrics](../charts-and-metrics/SKILL.md).

### One query per role

When roles read a table by different rules, or see different fields of it, declare one query per role. Each one has its own `customGroups`, `fields` and `filter`. A filtered query names the groups of its role in `customGroups`, never every signed-in user. Only when one rule holds for every signed-in user, keep `LOGGED_IN_USERS` with no groups. Pick the query on the server by the visitor's groups, never by an argument:

```ts
const bookingsForStaff = defineQuery({
  id: 'bookingsForStaff',
  datasourceId: '00000000-0000-0000-0000-000000000002',
  fields: { title: 'Lb7yQe3vXa9Ns1', date: 'Xp2dLh6vKz9Fa3', status: 'Ru7bVx2cNq0Ed9', client: 'Pc8vNm3kTq6Wz2' },
  permissions: { userGroupTypes: ['LOGGED_IN_USERS'], customGroups: ['00000000-0000-0000-0000-00000000000a'] },
})

const listBookings = createServerFn().handler(async ({ context }) => {
  if (!context.user) throw new Error('Not signed in')
  if (context.user.userGroupIds.includes('00000000-0000-0000-0000-00000000000a')) {
    return await ds.list(bookingsForStaff).limit(50)
  }
  return await ds.list(myBookings).limit(50)
})
```

`bookingsForStaff` has no filter: staff read every booking. Its `customGroups` names staff only, so a client cannot run it.

A list of other people, such as a directory or the members of a chat, declares only the fields its role needs: no email or phone unless the role needs them. Everything a server function returns reaches the browser, also when the page does not show it. A `USER` field reads back with the person's email, so a list that must not show emails does not declare one either. Here members see names and job titles, and staff see emails too:

```ts
const peopleForMembers = defineQuery({
  id: 'peopleForMembers',
  datasourceId: '00000000-0000-0000-0000-000000000003',
  fields: { name: 'Hn4tRw8kPz2Mc5', jobTitle: 'Lb7yQe3vXa9Ns1' },
  permissions: { userGroupTypes: ['LOGGED_IN_USERS'], customGroups: ['00000000-0000-0000-0000-00000000000c'] },
})

const peopleForStaff = defineQuery({
  id: 'peopleForStaff',
  datasourceId: '00000000-0000-0000-0000-000000000003',
  fields: { name: 'Hn4tRw8kPz2Mc5', jobTitle: 'Lb7yQe3vXa9Ns1', email: 'Td2kWm6pFs8Jq4' },
  permissions: { userGroupTypes: ['LOGGED_IN_USERS'], customGroups: ['00000000-0000-0000-0000-00000000000a'] },
})
```

### A table that belongs to the visitor through its parent

Some tables have no field to compare with the visitor. Chat messages belong to a chat, and only the chat links to its members. A filter on messages cannot say "the messages of my chats", because it cannot follow the link to the chat's members. The same goes for the players of a game room. Only for such a table, read the parent first through its filtered query. Read or post the children only when that read answers, and filter them on the parent that it answered. Here `myChats` filters chats with `members: { isOneOf: ['USER:::Rk2mVx9pQa4Lz7'] }`, and `messages` has a `chat` link to chats:

```ts
const listMessages = createServerFn()
  .validator(z.object({ chatId: z.string() }))
  .handler(async ({ data }) => {
    const chat = await ds.get(myChats, { id: data.chatId })
    if (chat === null) throw new Error('Chat not found')
    return await ds
      .list(messages)
      .where((q) => q.chat.isOneOf([chat.id]))
      .orderBy((q) => q.sentAt.desc)
      .limit(100)
  })
```

Every server function that reads or posts messages reads the chat this way first. The read sorts newest first, so the limit keeps the newest 100 messages. Reverse them in the page to show the oldest on top.

Use this step only when the rule is about the parent. When it is about the row's own owner, such as "a user sees only the requests they sent", the table filters its own link to Users.

## Typing

Queries you write are type safe and a type error is shown when there's a mistake. The records a read returns are typed the same way, so never validate them again with a zod schema of your own. A schema guesses each field's shape, and one value it misses, such as a person with no email, throws for the whole read and the page stops loading. Show each field with a fallback instead: `record.fields.owner?.name ?? '—'`. For an in depth reference on what fields every datasource has, read `docs/datasources/README.md` first — it lists every registered datasource with a link to its file. Follow those links to get field ids, types, and constraints. Do not guess filenames from table names.

## References

- [references/filters-and-sorting.md](./references/filters-and-sorting.md): every filter operator by field type, group nesting and the sort handles. Load it when the operator you want is not in this file, or when a filter is rejected.
- [references/field-types.md](./references/field-types.md): the value shape every Softr field type reads back as. Load it when rendering a field whose shape you are unsure of, or when a value is not the string you expected.
- [current-user/SKILL.md](../current-user/SKILL.md): reading the visitor off `context`, and the `user.properties` a filter compares with
- [routes-and-visibility/SKILL.md](../routes-and-visibility/SKILL.md): deciding who sees the page the records land on
- [charts-and-metrics/SKILL.md](../charts-and-metrics/SKILL.md): aggregating records instead of listing them
- [record-mutations/SKILL.md](../record-mutations/SKILL.md): creating, updating and deleting them
