Query, sort and live updates
What you will do
You will choose which records to show with where, sort them with orderBy, cap how many you get with limit, and keep a list on screen up to date with subscribe. You will also learn what a query cannot do, and how to get the same result another way.
A few words used on this page:
- An app is the web app you build. A user is the person who uses it and whose records it shows.
- A collection is one kind of data, such as notes, and each saved item in it is a record. The collection's schema lists its fields and their types.
- The SDK (
@phibac/sdk) is the JavaScript library your page uses. It keeps a copy of the user's records in the browser. - Live updates are how the SDK tells your page that records changed, including changes made in another tab or on another device.
- An rkey (record key) is the ID of a record within its collection.
Before you start
You need the notes app from Build your first app, with the local server running and a page that signs in (see Sign users in). Define your data explains each field type and option used below, and Read and write records explains create, get and list.
Steps
1. Mark the fields you will query as indexed
A query can filter and sort only on fields marked indexed: true in the schema (indexed fields), and on createdAt and updatedAt, which every record has. Replace pb.config.ts with this file, keeping your own app value. It has the fields this page queries, including textLower, a lower-case copy of the text used for searching, and a comments collection that links to notes:
import { defineApp, collection, string, integer, boolean, datetime, enumOf, json, fileRef, recordRef } from "phibac";
export default defineApp({
app: "app_...",
collections: {
"com.example.notes.note": collection({
version: 1,
description: "A note written by the user",
fields: {
text: string({ description: "Note text", maxLength: 20000, required: true }),
pinned: boolean({ description: "Whether the note is pinned", indexed: true }),
color: enumOf(["yellow", "blue", "green"], { description: "The colour the note is shown in", indexed: true }),
priority: integer({ description: "Priority from 1 (low) to 3 (high)", min: 1, max: 3, indexed: true }),
remindAt: datetime({ description: "When to remind the user of the note", indexed: true }),
place: string({ description: "Where the user was when they wrote the note", maxLength: 200, sensitive: true }),
photo: fileRef({ description: "A photo attached to the note" }),
textLower: string({ description: "The note text in lower case, to search by the start of the text", maxLength: 20000, indexed: true }),
checklist: json({ description: "A checklist in the note: a list of items, each with a text and whether it is done" }),
},
}),
"com.example.notes.comment": collection({
version: 1,
description: "A comment the user wrote on a note",
fields: {
note: recordRef({ description: "The note this comment is about", indexed: true, required: true }),
text: string({ description: "Comment text", maxLength: 2000, required: true }),
},
}),
},
});
Publish it and generate the types:
npx phibac deploy
npx phibac generate
The new fields are optional, so npx phibac deploy publishes them as a new minor version of the same major version. src/pb-types.ts is now:
// Generated from published collection schemas. Do not edit by hand.
/** A comment the user wrote on a note */
export interface ComExampleNotesCommentV1 {
/** The note this comment is about */
note: string;
/** Comment text */
text: string;
}
/** A note written by the user */
export interface ComExampleNotesNoteV1 {
/** A checklist in the note: a list of items, each with a text and whether it is done */
checklist?: unknown;
/** The colour the note is shown in */
color?: "yellow" | "blue" | "green";
/** A photo attached to the note */
photo?: string;
/** Whether the note is pinned */
pinned?: boolean;
/** Where the user was when they wrote the note */
place?: string;
/** Priority from 1 (low) to 3 (high) */
priority?: number;
/** When to remind the user of the note */
remindAt?: string;
/** Note text */
text: string;
/** The note text in lower case, to search by the start of the text */
textLower?: string;
}
export const SCHEMA_MAJORS = {
"com.example.notes.comment": 1,
"com.example.notes.note": 1,
} as const;
2. Write the page
Create index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Notes</title>
</head>
<body>
<button type="button" id="sign-in">Sign in</button>
<p id="message" role="alert"></p>
<h2>Urgent blue notes</h2>
<ul id="urgent"></ul>
<h2>Latest notes</h2>
<ul id="latest"></ul>
<button type="button" id="more" hidden>Show more</button>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
3. Write the queries
Create src/main.ts, with your app ID in place of app_...:
import { connect, PbError, type Collection, type PbRecord } from "@phibac/sdk";
import { SCHEMA_MAJORS, type ComExampleNotesNoteV1 as Note } from "./pb-types";
const signIn = document.querySelector<HTMLButtonElement>("#sign-in")!;
const message = document.querySelector<HTMLParagraphElement>("#message")!;
const urgentList = document.querySelector<HTMLUListElement>("#urgent")!;
const latestList = document.querySelector<HTMLUListElement>("#latest")!;
const more = document.querySelector<HTMLButtonElement>("#more")!;
const PAGE = 20;
let shown = PAGE;
let notes: Collection<Note> | null = null;
// textContent shows text as typed: it never runs it as HTML.
function show(list: HTMLUListElement, records: PbRecord<Note>[]): void {
list.replaceChildren(
...records.map((r) => {
const item = document.createElement("li");
item.textContent = `${r.data.text} (priority ${r.data.priority ?? "none"}, ${r.status})`;
return item;
}),
);
}
// get() runs the query once. Each call to limit() asks for more records.
async function showLatest(): Promise<void> {
if (notes === null) return;
const latest = await notes.orderBy("createdAt", "desc").limit(shown).get();
show(latestList, latest);
more.hidden = latest.length < shown;
}
signIn.addEventListener("click", async () => {
try {
const backend = await connect({ app: "app_...", baseUrl: "http://localhost:8787", schemaMajors: SCHEMA_MAJORS });
notes = backend.collection<Note>("com.example.notes.note");
// Live updates: blue notes of priority 2 or more, highest first, at most 10.
// show() runs now and again whenever a matching note changes.
notes
.where("color", "==", "blue")
.where("priority", ">=", 2)
.orderBy("priority", "desc")
.limit(10)
.subscribe((records) => show(urgentList, records));
await showLatest();
signIn.hidden = true;
} catch (e) {
message.textContent = e instanceof PbError ? `${e.code}: ${e.message}` : String(e);
}
});
more.addEventListener("click", () => {
shown += PAGE;
showLatest().catch((e: unknown) => (message.textContent = String(e)));
});
The parts of a query:
where(field, op, value)keeps the records whose field matches.opis one of"==","!=","<","<=",">",">="and"in"(the field equals one of a list of values). Eachwherenarrows the result further. A record that lacks the field never matches, not even with"!=".orderBy(field, "asc" | "desc")sorts by one field,"asc"(smallest first) if you leave the direction out. Records that lack the field come last in both directions, and records with equal values are put in rkey order. WithoutorderBy, records are sorted bycreatedAt, oldest first.limit(n)returns at mostnrecords. Without it, a query returns at most 500 records.get()runs the query once and returns the records.subscribe(fn)callsfnwith the matching records now, and again every time they change: your own writes, the server confirming them, and changes from other tabs and devices. The function you pass is called a subscription. It returns a function that stops the calls; call it when the list leaves the screen. A subscribed query also returns at most 500 records unless you setlimit(n). Callingsubscribeon the collection itself, as innotes.subscribe(fn), follows every record with no cap. SDK reference lists every method of a query.
Values are compared by the field's type: numbers as numbers, booleans as true and false, and text, enum and date-and-time values as text, letter by letter, in character-code order (so "B" comes before "a"). For createdAt and updatedAt, pass a date-and-time string such as "2026-11-14T00:00:00.000Z", or a Date; these two are compared as moments in time. Your own datetime fields, such as remindAt, are compared as text, so filters and sorting on them are right only when every value has the same form: write them all with new Date().toISOString(), which always gives UTC with milliseconds.
4. Show more records
There is no page number or offset. To show more records, run the query again with a larger limit(n), as Show more does. The SDK fetches as many pages from the server as it needs; one request returns at most 500 records.
5. Know what happens offline
When the device is online, get() sends the query to the server, so it sees every record the user has, and then adds the changes this device has not sent yet. When the device is offline, or the server cannot be reached, get() runs the same query on the browser's copy, with the same rules. That copy holds only the records this browser has seen, so offline results can miss records saved on other devices.
subscribe() always works on the browser's copy, online and offline. While a subscription is open, the SDK keeps that copy up to date through live updates, so the function is called again when records arrive from the server.
What you should see
- After Sign in, Latest notes shows your 20 newest notes, newest first, and Show more appears if there are more.
- Create a blue note of priority 3, for example by adding
await notes.create({ text: "Call the bank", color: "blue", priority: 3 });at the end of the click handler. It appears under Urgent blue notes at once, above notes of priority 2, without reloading. - Change its colour to yellow, for example with
await notes.update(note.rkey, { color: "yellow" });wherenoteis the recordcreatereturned. It leaves the urgent list. - Press Show more and the next 20 notes appear.
Query limits and workarounds
Queries are simple on purpose. Here is what they cannot do and what to do instead. Each example below is a file you can add next to src/main.ts; it uses the types from step 1.
Filters combine with AND only
Every where narrows the result: a record must match all of them. There is no OR and no grouping. Two where calls on the same field both apply, which gives a range: where("priority", ">=", 2).where("priority", "<", 3).
Workarounds:
- One field equal to A or B: use
"in"with a list of values, at most 500 of them. Values must not contain a comma, because the list is sent as comma-separated text. - An OR across different fields: run one query per condition and merge the results by rkey in your code.
- An OR you need often: store the answer in its own indexed field, updated whenever the record changes, and filter on that.
import type { Collection, PbRecord } from "@phibac/sdk";
import type { ComExampleNotesNoteV1 as Note } from "./pb-types";
// Notes that are yellow or blue: one field, several values.
export function yellowOrBlue(notes: Collection<Note>): Promise<PbRecord<Note>[]> {
return notes.where("color", "in", ["yellow", "blue"]).get();
}
// Notes that are pinned OR of priority 3: one query per condition, merged by rkey.
export async function pinnedOrUrgent(notes: Collection<Note>): Promise<PbRecord<Note>[]> {
const [pinned, urgent] = await Promise.all([
notes.where("pinned", "==", true).get(),
notes.where("priority", "==", 3).get(),
]);
const byKey = new Map<string, PbRecord<Note>>();
for (const r of [...pinned, ...urgent]) byKey.set(r.rkey, r);
return [...byKey.values()].sort((a, b) => a.createdAt.localeCompare(b.createdAt));
}
Results are sorted by one sort field only
A query sorts by one sort field. Calling orderBy a second time replaces the first, without an error. Only indexed fields, createdAt and updatedAt can be sorted.
Workarounds:
- Sort by the main field in the query, then sort the records again in your code by both fields. JavaScript's sort keeps the order of records it sees as equal.
- Or store one combined value that sorts the way you want in an indexed string field, and sort by that. Pad numbers with zeros and write every date with
new Date().toISOString()so all of them have one form and sort as text:"3#2026-11-14T09:30:00.000Z".
import type { Collection, PbRecord } from "@phibac/sdk";
import type { ComExampleNotesNoteV1 as Note } from "./pb-types";
// Highest priority first; within one priority, the next reminder first.
export async function byPriorityThenReminder(notes: Collection<Note>): Promise<PbRecord<Note>[]> {
const records = await notes.orderBy("priority", "desc").get();
return records.sort((a, b) => {
const p = (b.data.priority ?? 0) - (a.data.priority ?? 0);
if (p !== 0) return p;
// Notes without a reminder go last.
return (a.data.remindAt ?? "\uffff").localeCompare(b.data.remindAt ?? "\uffff");
});
}
There is no text search
There is no text search: no "contains", no match that ignores upper and lower case, and no ranking by relevance.
Workarounds:
- Starts with: store a lower-case copy of the text in an indexed string field (here
textLower), and ask for the range from the prefix up to the prefix with its last character moved up by one. A note saved withouttextLowernever matches, because a record that lacks a field never matches a filter on it: set it on every write. - Contains, on a small collection: read the records and filter them in your code. A
limit(n)query asks the server while the device is online; offline, it reads this browser's copy, likelist()always does, and that copy can miss records saved on other devices or right after signing in on a new device. - Contains, on a large collection: keep a second collection with one record per word, holding the word in an indexed field and a
recordRefto the record, and query it with"==".
import type { Collection, PbRecord } from "@phibac/sdk";
import type { ComExampleNotesNoteV1 as Note } from "./pb-types";
// Save the lower-case copy every time the text is written.
export function addNote(notes: Collection<Note>, text: string): Promise<PbRecord<Note>> {
return notes.create({ text, textLower: text.toLowerCase() });
}
// Notes whose text starts with prefix, ignoring case: "buy" finds "Buy milk".
export function startsWith(notes: Collection<Note>, prefix: string): Promise<PbRecord<Note>[]> {
const from = prefix.toLowerCase();
if (from === "") return notes.list();
const to = from.slice(0, -1) + String.fromCharCode(from.charCodeAt(from.length - 1) + 1);
return notes.where("textLower", ">=", from).where("textLower", "<", to).orderBy("textLower").get();
}
// Notes whose text contains word anywhere: fine for a few hundred notes. Offline, it sees only this browser's copy.
export async function contains(notes: Collection<Note>, word: string): Promise<PbRecord<Note>[]> {
const w = word.toLowerCase();
return (await notes.orderBy("createdAt").limit(1_000_000).get()).filter((r) => r.data.text.toLowerCase().includes(w));
}
There are no counts or totals
There are no counts or totals: no count, sum, average or grouping, on the server or in the SDK.
Workarounds:
- Read the records and compute in your code. Without
limit(n)a query stops at 500 records, so a count of its results is wrong above that. Pass alimit(n)larger than the collection can ever get; the SDK fetches every page for you. This downloads every matching record, so narrow it withwherefirst. - Or use
list(), which counts what is in the browser's copy. That copy may not have every record yet right after signing in on a new device. - Do not keep a running counter or total in a record. When two devices change it offline, the server applies the changes in the order it receives them and the last one wins, so increments are lost. If you keep one, recompute it from the records when it must be right.
import type { Collection } from "@phibac/sdk";
import type { ComExampleNotesNoteV1 as Note } from "./pb-types";
// Far more notes than one user will ever have, so nothing is cut off.
const ALL = 1_000_000;
export async function countPinned(notes: Collection<Note>): Promise<number> {
return (await notes.where("pinned", "==", true).limit(ALL).get()).length;
}
// The average priority of the notes that have one, or null if none do.
export async function averagePriority(notes: Collection<Note>): Promise<number | null> {
const records = await notes.where("priority", ">=", 1).limit(ALL).get();
if (records.length === 0) return null;
const sum = records.reduce((total, r) => total + (r.data.priority ?? 0), 0);
return sum / records.length;
}
Linked records are not fetched for you
A recordRef field holds another record's global ID, pb://<userId>/<collection>/<rkey>. Reading a record never returns the linked records it points to.
Workarounds:
- From a record to the record it links to: take the last part of the ID, the rkey, and call
get(rkey)on the other collection. It reads the browser's copy and returnsnullwhen the record is missing, deleted or not copied yet, so handlenull. - Many links at once: read the other collection once with
list()and look the records up in aMapby rkey.list()reads this browser's copy, so a linked record that is deleted or not copied yet is simply not found. - From a record to the records that link to it: mark the linking field
indexed(asnoteis in step 1) and query it with"=="and the record'sid.
Deleting a record does not change the records that point to it. To read another app's collection, your app needs the user's permission first, with requestAccess(), and the collection handle must list the major versions your code understands, as in backend.collection(name, { versions: [1] }); without them the server refuses the query with invalid_request. Read another app's data shows how.
import type { Collection, PbRecord } from "@phibac/sdk";
import type { ComExampleNotesCommentV1 as Comment, ComExampleNotesNoteV1 as Note } from "./pb-types";
// The rkey is the last part of a global ID.
function rkeyOf(id: string): string {
return id.slice(id.lastIndexOf("/") + 1);
}
// From a comment to its note. null: the note is deleted, or not in this browser yet.
export function noteOf(notes: Collection<Note>, comment: PbRecord<Comment>): Promise<PbRecord<Note> | null> {
return notes.get(rkeyOf(comment.data.note));
}
// From a note to its comments: note is an indexed recordRef field.
export function commentsOf(comments: Collection<Comment>, note: PbRecord<Note>): Promise<PbRecord<Comment>[]> {
return comments.where("note", "==", note.id).get();
}
// Every comment with its note's text, reading this browser's copy of the notes once.
export async function commentsWithNotes(notes: Collection<Note>, comments: Collection<Comment>): Promise<string[]> {
const byKey = new Map((await notes.list()).map((n) => [n.rkey, n]));
return (await comments.list()).map((c) => `${byKey.get(rkeyOf(c.data.note))?.data.text ?? "(note not found)"}: ${c.data.text}`);
}
Common problems
invalid_requestsaying a field "cannot be used to filter or order". The field is not indexed. Mark itindexed: trueinpb.config.ts, runnpx phibac deployandnpx phibac generate. Addingindexedis not a breaking change.- A query works in
subscribe(), or inget()while offline, butget()fails withinvalid_requestonline.subscribe()and an offlineget()run on the browser's copy, while an onlineget()asks the server, which checks that every filtered and sorted field is indexed. Index the field. invalid_requestsaying a filter value "is not a number" (or not a boolean, or not an RFC 3339 time). The value does not fit the field's type. Pass a number fornumberandintegerfields,trueorfalseforbooleanfields, and a date-and-time string forcreatedAtandupdatedAt.invalid_requestsaying the in filter has too many values. An"in"list holds at most 500 values. Split it over several queries and merge the results.- A query returns fewer records than you expected. Without
limit(n)it stops at 500 records. Pass a larger limit. Offline, it also sees only the records in the browser's copy. - A list is empty right after signing in, then fills. The browser's copy is catching up with the server. A subscribed function is called again when it has; show a loading message until then.
- The results ignore the first of two
orderBycalls. Only one sort field applies: the lastorderBywins. Sort by the second field in your code. consent_required. The collection belongs to another app and the user has not allowed yours to read it. CallrequestAccess()on it from a click, then query again withversionsset on the collection handle.
Next step
Upload and show files adds photos to the notes app: how to upload a file, keep its ID in a record and show it.