tanstack/db/live-queries
Claude Code and agent skill by tanstack/db
- community
Checking that the SKILL.md file is still in the repository.
Query builder fluent API: from, where, join, leftJoin, rightJoin, innerJoin, fullJoin, select, fn.select, groupBy, having, orderBy, limit, offset, distinct, findOne. Operators: eq, gt, gte, lt, lte, like, ilike, inArray, isNull, isUndefined, and, or, not. Aggregates: count, sum, avg, min, max. String functions: upper, lower, length, concat. Utility: coalesce, caseWhen. Math: add, subtract, multiply, divide. $selected namespace. createLiveQueryCollection. Derived collections. Predicate push-down. Incremental view maintenance via differential dataflow (d2ts). Virtual properties ($hasPendingWrites, $origin, $key, $collectionId). Includes subqueries for hierarchical data. Collection, toArray, materialize, and concat(toArray(...)) include modes. queryOnce for one-shot queries. createEffect for reactive side effects (onEnter, onUpdate, onExit, onBatch).
Install
npx vskill@latest install tanstack/db/live-queriesSKILL.md
The same SKILL.md was published earlier as tanstack/db/live-queries.
Live Queries
This skill builds on db-core.
TanStack DB live queries use a SQL-like fluent query builder to create reactive derived collections that automatically update when underlying data changes. The query engine compiles queries into incremental view maintenance (IVM) pipelines using differential dataflow (d2ts), so only deltas are recomputed.
All operators, string functions, math functions, and aggregates are incrementally maintained. Prefer them over equivalent JS code.
Setup
Minimal example using the core API (no framework hooks):
Core Patterns
1. Filtering with where + operators
Chain .where() calls (ANDed together) using expression operators. Use and(), or(), not() for complex logic.
Boolean column references work directly:
Comparisons follow PostgreSQL semantics. Comparisons involving null or undefined are unknown and do not match; use isNull() or isUndefined(). NaN (and an invalid Date) equals itself and sorts after every other non-null value.
2. Joining two collections
Join conditions accept eq() or a nonempty, possibly nested and() of equalities (equality only -- IVM constraint). Default join type is left. Convenience methods: leftJoin, rightJoin, innerJoin, fullJoin.
Multiple joins:
3. Aggregation with groupBy + having
Use groupBy to group rows, then aggregate in select. Filter groups with having. The $selected namespace lets having and orderBy reference fields defined in select. A groupBy with no aggregate wraps its keys in groupKeys(): .groupBy(groupKeys(({ order }) => order.status)); without it the query throws GroupingOperatorRequiredError. A groupKeys() built outside .groupBy() takes the context as a type argument, groupKeys<ContextFromSource<{ order: typeof ordersCollection }>>(...); without it the callback is untyped.
Without groupBy, aggregates in select treat the entire collection as one group:
4. Standalone derived collection with createLiveQueryCollection
Derived collections are themselves collections. Use one as a source for another query to cache intermediate results:
Create derived collections once at module scope and reuse them. Do not recreate on every render or navigation.
Live query collections default to gcTime: 5_000. An explicit gcTime: 0 is preserved and disables garbage collection for that derived collection -- including the reclamation of a collection that started syncing and never gained a subscriber. Note this is the opposite of gcTime: 0 in TanStack Query, where it collects as soon as the query goes inactive; use a small positive value if you want prompt collection here.
Sync started without subscribers has a minimum 50ms GC grace period. Pending preload() calls retain the collection until they settle; the unused retention period then starts. Preloading an already-ready collection refreshes that period. Explicit cleanup() can still abort a pending preload.
Virtual Properties
Live query results include computed, read-only virtual properties on every row:
$hasPendingWrites:truewhile a pending local optimistic write affects
the row; false otherwise. This is local mutation status, not proof that a backend uploaded, confirmed, or read back the row.
$origin:"local"if the last confirmed change came from this client, otherwise"remote".$key: the row key for the result.$collectionId: the source collection ID.
These props are added automatically and can be used in where, select, and orderBy clauses. Do not persist them back to storage.
Includes (Subqueries in Select)
Embed a correlated subquery inside select() to produce hierarchical (nested) data. The subquery must contain a where with an eq() that correlates a parent field with a child field.
Collection includes with include()
Return a child Collection on each parent row:
Array includes with toArray()
Wrap the subquery in toArray() to get a plain array instead of a Collection:
Plain values with materialize()
Use materialize() when the parent row should hold a plain snapshot rather than a child collection:
For a multi-row subquery, materialize() returns Array<T> like toArray(). For a subquery ending in findOne(), it returns T | undefined. In both cases, the parent row is re-emitted when the child result changes.
Concatenated scalar with concat(toArray())
Wrap toArray() in concat() to join the scalar results into a single string:
Includes rules
- The subquery must have a
whereclause with aneq()correlating a parent alias with a child alias. The library extracts this automatically as the join condition. toArray()works with both scalar selects (e.g.,select(({ c }) => c.text)→string[]) and object selects (e.g.,select(({ c }) => ({ id: c.id, title: c.title }))→Array<{id, title}>).materialize()returns an array, or one value for afindOne()subquery.
Like toArray(), it must be a top-level value in select() and cannot be nested inside coalesce(), eq(), or another expression.
concat(toArray())requires a scalarselectto concatenate into a string.- Collection includes (
include(subquery)) require an objectselect. A bare subquery inselectthrowsIncludeOperatorRequiredError. - Includes subqueries are compiled into the same incremental pipeline as the parent query -- they are not separate live queries.
One-Shot Queries with queryOnce
For non-reactive, one-time snapshots use queryOnce. It creates a live query collection, preloads it, extracts the results, and cleans up automatically.
Use queryOnce for scripts, loaders, data export, tests, or AI/LLM context building. For UI bindings and reactive updates, use live queries instead.
Reactive Effects (createEffect)
Reactive effects respond to query result _changes_ without materializing the full result set. Effects fire callbacks when rows enter, exit, or update within a query result — like a database trigger on an arbitrary live query.
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 93 of 100Pattern checks on the skill's files.
- Model reviewNot runA model review is scheduled for the next rescan.
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingpackages/db/skills/db-core/live-queries/SKILL.md
Popularity
- Repository stars
- 3,880
- Repository forks
- 258
- 7-day trend score
- 41
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/tanstack/db/live-queries)