Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

live-queries.md

1,470 lines38.7 KB

1---
2title: Live Queries
3id: live-queries
4---
5​
6# TanStack DB Live Queries
7​
8TanStack DB provides a powerful, type-safe query system that allows you to fetch, filter, transform, and aggregate data from collections using a SQL-like fluent API. All queries are **live** by default, meaning they automatically update when the underlying data changes.
9​
10The query system is built around an API similar to SQL query builders like Kysely or Drizzle where you chain methods together to compose your query. The query builder doesn't perform operations in the order of method calls - instead, it composes your query into an optimal incremental pipeline that gets compiled and executed efficiently. Each method returns a new query builder, allowing you to chain operations together.
11​
12Live queries resolve to collections that automatically update when their underlying data changes. You can subscribe to changes, iterate over results, and use all the standard collection methods.
13​
14```ts
15import { createCollection, liveQueryCollectionOptions, eq } from '@tanstack/db'
16​
17const activeUsers = createCollection(liveQueryCollectionOptions({
18 query: (q) =>
19 q
20 .from({ user: usersCollection })
21 .where(({ user }) => eq(user.active, true))
22 .select(({ user }) => ({
23 id: user.id,
24 name: user.name,
25 email: user.email,
26 }))
27}))
28```
29​
30The result types are automatically inferred from your query structure, providing full TypeScript support. When you use a `select` clause, the result type matches your projection. Without `select`, you get the full schema with proper join optionality.
31​
32## Table of Contents
33​
34- [Creating Live Query Collections](#creating-live-query-collections)
35- [From Clause](#from-clause)
36- [Where Clauses](#where-clauses)
37- [Select Projections](#select)
38- [Joins](#joins)
39- [Subqueries](#subqueries)
40- [groupBy and Aggregations](#groupby-and-aggregations)
41- [Distinct](#distinct)
42- [Order By, Limit, and Offset](#order-by-limit-and-offset)
43- [Composable Queries](#composable-queries)
44- [Expression Functions Reference](#expression-functions-reference)
45- [Functional Variants](#functional-variants)
46​
47## Creating Live Query Collections
48​
49To create a live query collection, you can use `liveQueryCollectionOptions` with `createCollection`, or use the convenience function `createLiveQueryCollection`.
50​
51### Using liveQueryCollectionOptions
52​
53The fundamental way to create a live query is using `liveQueryCollectionOptions` with `createCollection`:
54​
55```ts
56import { createCollection, liveQueryCollectionOptions, eq } from '@tanstack/db'
57​
58const activeUsers = createCollection(liveQueryCollectionOptions({
59 query: (q) =>
60 q
61 .from({ user: usersCollection })
62 .where(({ user }) => eq(user.active, true))
63 .select(({ user }) => ({
64 id: user.id,
65 name: user.name,
66 }))
67}))
68```
69​
70### Configuration Options
71​
72For more control, you can specify additional options:
73​
74```ts
75const activeUsers = createCollection(liveQueryCollectionOptions({
76 id: 'active-users', // Optional: auto-generated if not provided
77 query: (q) =>
78 q
79 .from({ user: usersCollection })
80 .where(({ user }) => eq(user.active, true))
81 .select(({ user }) => ({
82 id: user.id,
83 name: user.name,
84 })),
85 getKey: (user) => user.id, // Optional: uses stream key if not provided
86 startSync: true, // Optional: starts sync immediately
87}))
88```
89| Option | Type | Description |
90|--------|------|-------------|
91| `id` | `string` (optional) | An optional unique identifier for the live query. If not provided, it will be auto-generated. This is useful for debugging and logging. |
92| `query` | `QueryBuilder` or function | The query definition, this is either a `Query` instance or a function that returns a `Query` instance. |
93| `getKey` | `(item) => string \| number` (optional) | A function that extracts a unique key from each row. If not provided, the stream's internal key will be used. For simple cases this is the key from the parent collection, but in the case of joins, the auto-generated key will be a composite of the parent keys. Using `getKey` is useful when you want to use a specific key from a parent collection for the resulting collection. |
94| `schema` | `Schema` (optional) | Optional schema for validation |
95| `startSync` | `boolean` (optional) | Whether to start syncing immediately. Defaults to `true`. |
96| `gcTime` | `number` (optional) | Garbage collection time in milliseconds. Defaults to `5000` (5 seconds). |
97​
98### Convenience Function
99​
100For simpler cases, you can use `createLiveQueryCollection` as a shortcut:
101​
102```ts
103import { createLiveQueryCollection, eq } from '@tanstack/db'
104​
105const activeUsers = createLiveQueryCollection((q) =>
106 q
107 .from({ user: usersCollection })
108 .where(({ user }) => eq(user.active, true))
109 .select(({ user }) => ({
110 id: user.id,
111 name: user.name,
112 }))
114```
115​
116### Using with Frameworks
117​
118In React, you can use the `useLiveQuery` hook:
119​
120```tsx
121import { useLiveQuery } from '@tanstack/react-db'
122​
123function UserList() {
124 const activeUsers = useLiveQuery((q) =>
125 q
126 .from({ user: usersCollection })
127 .where(({ user }) => eq(user.active, true))
128 )
129​
130 return (
131 <ul>
132 {activeUsers.map(user => (
133 <li key={user.id}>{user.name}</li>
134 ))}
135 </ul>
136 )
138```
139​
140In Angular, you can use the `injectLiveQuery` function:
141​
142```typescript
143import { Component } from '@angular/core'
144import { injectLiveQuery } from '@tanstack/angular-db'
145​
146@Component({
147 selector: 'user-list',
148 template: `
149 @for (user of activeUsers.data(); track user.id) {
150 <li>{{ user.name }}</li>
151 }
152 `
153})
154export class UserListComponent {
155 activeUsers = injectLiveQuery((q) =>
156 q
157 .from({ user: usersCollection })
158 .where(({ user }) => eq(user.active, true))
159 )
161```
162​
163For more details on framework integration, see the [React](../../framework/react/adapter), [Vue](../../framework/vue/adapter), and [Angular](../../framework/angular/adapter) adapter documentation.
164​
165## From Clause
166​
167The foundation of every query is the `from` method, which specifies the source collection or subquery. You can alias the source using object syntax.
168​
169### Method Signature
170​
171```ts
172from({
173 [alias]: Collection | Query,
174}): Query
175```
176​
177**Parameters:**
178- `[alias]` - A Collection or Query instance. Note that only a single aliased collection or subquery is allowed in the `from` clause.
179​
180### Basic Usage
181​
182Start with a basic query that selects all records from a collection:
183​
184```ts
185const allUsers = createCollection(liveQueryCollectionOptions({
186 query: (q) => q.from({ user: usersCollection })
187}))
188```
189​
190The result contains all users with their full schema. You can iterate over the results or access them by key:
191​
192```ts
193// Get all users as an array
194const users = allUsers.toArray
195​
196// Get a specific user by ID
197const user = allUsers.get(1)
198​
199// Check if a user exists
200const hasUser = allUsers.has(1)
201```
202​
203Use aliases to make your queries more readable, especially when working with multiple collections:
204​
205```ts
206const users = createCollection(liveQueryCollectionOptions({
207 query: (q) => q.from({ u: usersCollection })
208}))
209​
210// Access fields using the alias
211const userNames = createCollection(liveQueryCollectionOptions({
212 query: (q) =>
213 q
214 .from({ u: usersCollection })
215 .select(({ u }) => ({
216 name: u.name,
217 email: u.email,
218 }))
219}))
220```
221​
222## Where Clauses
223​
224Use `where` clauses to filter your data based on conditions. You can chain multiple `where` calls - they are combined with `and` logic.
225​
226The `where` method takes a callback function that receives an object containing your table aliases and returns a boolean expression. You build these expressions using comparison functions like `eq()`, `gt()`, and logical operators like `and()` and `or()`. This declarative approach allows the query system to optimize your filters efficiently. These are described in more detail in the [Expression Functions Reference](#expression-functions-reference) section. This is very similar to how you construct queries using Kysely or Drizzle.
227​
228It's important to note that the `where` method is not a function that is executed on each row or the results, its a way to describe the query that will be executed. This declarative approach works well for almost all use cases, but if you need to use a more complex condition, there is the functional variant as `fn.where` which is described in the [Functional Variants](#functional-variants) section.
229​
230### Method Signature
231​
232```ts
233where(
234 condition: (row: TRow) => Expression<boolean>
235): Query
236```
237​
238**Parameters:**
239- `condition` - A callback function that receives the row object with table aliases and returns a boolean expression
240​
241### Basic Filtering
242​
243Filter users by a simple condition:
244​
245```ts
246import { eq } from '@tanstack/db'
247​
248const activeUsers = createCollection(liveQueryCollectionOptions({
249 query: (q) =>
250 q
251 .from({ user: usersCollection })
252 .where(({ user }) => eq(user.active, true))
253}))
254```
255​
256### Multiple Conditions
257​
258Chain multiple `where` calls for AND logic:
259​
260```ts
261import { eq, gt } from '@tanstack/db'
262​
263const adultActiveUsers = createCollection(liveQueryCollectionOptions({
264 query: (q) =>
265 q
266 .from({ user: usersCollection })
267 .where(({ user }) => eq(user.active, true))
268 .where(({ user }) => gt(user.age, 18))
269}))
270```
271​
272### Complex Conditions
273​
274Use logical operators to build complex conditions:
275​
276```ts
277import { eq, gt, or, and } from '@tanstack/db'
278​
279const specialUsers = createLiveQueryCollection((q) =>
280 q
281 .from({ user: usersCollection })
282 .where(({ user }) =>
283 and(
284 eq(user.active, true),
285 or(
286 gt(user.age, 25),
287 eq(user.role, 'admin')
288 )
289 )
290 )
292```
293​
294### Available Operators
295​
296The query system provides several comparison operators:
297​
298```ts
299import { eq, gt, gte, lt, lte, like, ilike, inArray, and, or, not } from '@tanstack/db'
300​
301// Equality
302eq(user.id, 1)
303​
304// Comparisons
305gt(user.age, 18) // greater than
306gte(user.age, 18) // greater than or equal
307lt(user.age, 65) // less than
308lte(user.age, 65) // less than or equal
309​
310// String matching
311like(user.name, 'John%') // case-sensitive pattern matching
312ilike(user.name, 'john%') // case-insensitive pattern matching
313​
314// Array membership
315inArray(user.id, [1, 2, 3])
316​
317// Logical operators
318and(condition1, condition2)
319or(condition1, condition2)
320not(condition)
321```
322​
323For a complete reference of all available functions, see the [Expression Functions Reference](#expression-functions-reference) section.
324​
325## Select
326​
327Use `select` to specify which fields to include in your results and transform your data. Without `select`, you get the full schema.
328​
329Similar to the `where` clause, the `select` method takes a callback function that receives an object containing your table aliases and returns an object with the fields you want to include in your results. These can be combined with functions from the [Expression Functions Reference](#expression-functions-reference) section to create computed fields. You can also use the spread operator to include all fields from a table.
330​
331### Method Signature
332​
333```ts
334select(
335 projection: (row: TRow) => Record<string, Expression>
336): Query
337```
338​
339**Parameters:**
340- `projection` - A callback function that receives the row object with table aliases and returns the selected fields object
341​
342### Basic Selects
343​
344Select specific fields from your data:
345​
346````ts
347const userNames = createLiveQueryCollection((q) =>
348 q
349 .from({ user: usersCollection })
350 .select(({ user }) => ({
351 id: user.id,
352 name: user.name,
353 email: user.email,
354 }))
356​
357/*
358Result type: { id: number, name: string, email: string }
359​
360```ts
361for (const row of userNames) {
362 console.log(row.name)
364```
365*/
366````
367​
368### Field Renaming
369​
370Rename fields in your results:
371​
372```ts
373const userProfiles = createLiveQueryCollection((q) =>
374 q
375 .from({ user: usersCollection })
376 .select(({ user }) => ({
377 userId: user.id,
378 fullName: user.name,
379 contactEmail: user.email,
380 }))
382```
383​
384### Computed Fields
385​
386Create computed fields using expressions:
387​
388```ts
389import { gt, length } from '@tanstack/db'
390​
391const userStats = createLiveQueryCollection((q) =>
392 q
393 .from({ user: usersCollection })
394 .select(({ user }) => ({
395 id: user.id,
396 name: user.name,
397 isAdult: gt(user.age, 18),
398 nameLength: length(user.name),
399 }))
401```
402​
403### Using Functions and Including All Fields
404​
405Transform your data using built-in functions:
406​
407````ts
408import { concat, upper, gt } from '@tanstack/db'
409​
410const formattedUsers = createCollection(liveQueryCollectionOptions({
411 query: (q) =>
412 q
413 .from({ user: usersCollection })
414 .select(({ user }) => ({
415 ...user, // Include all user fields
416 displayName: upper(concat(user.firstName, ' ', user.lastName)),
417 isAdult: gt(user.age, 18),
418 }))
419}))
420​
421/*
422Result type:
424 id: number,
425 name: string,
426 email: string,
427 displayName: string,
428 isAdult: boolean,
430*/
431````
432​
433For a complete list of available functions, see the [Expression Functions Reference](#expression-functions-reference) section.
434​
435## Joins
436​
437Use `join` to combine data from multiple collections. Joins default to `left` join type and only support equality conditions.
438​
439Joins in TanStack DB are a way to combine data from multiple collections, and are conceptually very similar to SQL joins. When two collections are joined, the result is a new collection that contains the combined data as single rows. The new collection is a live query collection, and will automatically update when the underlying data changes.
440​
441A `join` without a `select` will return row objects that are namespaced with the aliases of the joined collections.
442​
443The result type of a join will take into account the join type, with the optionality of the joined fields being determined by the join type.
444​
445> [!NOTE]
446> We are working on an `include` system that will enable joins that project to a hierarchical object. For example an `issue` row could have a `comments` property that is an array of `comment` rows.
447> See [this issue](https://github.com/TanStack/db/issues/288) for more details.
448​
449### Method Signature
450​
451```ts
452join(
453 { [alias]: Collection | Query },
454 condition: (row: TRow) => Expression<boolean>, // Must be an `eq` condition
455 joinType?: 'left' | 'right' | 'inner' | 'full'
456): Query
457```
458​
459**Parameters:**
460- `aliases` - An object where keys are alias names and values are collections or subqueries to join
461- `condition` - A callback function that receives the combined row object and returns an equality condition
462- `joinType` - Optional join type: `'left'` (default), `'right'`, `'inner'`, or `'full'`
463​
464### Basic Joins
465​
466Join users with their posts:
467​
468````ts
469const userPosts = createLiveQueryCollection((q) =>
470 q
471 .from({ user: usersCollection })
472 .join({ post: postsCollection }, ({ user, post }) =>
473 eq(user.id, post.userId)
474 )
476​
477/*
478Result type:
479{
480 user: User,
481 post?: Post, // post is optional because it is a left join
483​
484```ts
485for (const row of userPosts) {
486 console.log(row.user.name, row.post?.title)
488```
489*/
490````
491​
492### Join Types
493​
494Specify the join type as the third parameter:
495​
496```ts
497const activeUserPosts = createLiveQueryCollection((q) =>
498 q
499 .from({ user: usersCollection })
500 .join(
501 { post: postsCollection },
502 ({ user, post }) => eq(user.id, post.userId),
503 'inner', // `inner`, `left`, `right` or `full`
504 )
506```
507​
508Or using the aliases `leftJoin`, `rightJoin`, `innerJoin` and `fullJoin` methods:
509​
510### Left Join
511```ts
512// Left join - all users, even without posts
513const allUsers = createLiveQueryCollection((q) =>
514 q
515 .from({ user: usersCollection })
516 .leftJoin(
517 { post: postsCollection },
518 ({ user, post }) => eq(user.id, post.userId),
519 )
521​
522/*
523Result type:
525 user: User,
526 post?: Post, // post is optional because it is a left join
528*/
529```
530​
531### Right Join
532​
533```ts
534// Right join - all posts, even without users
535const allPosts = createLiveQueryCollection((q) =>
536 q
537 .from({ user: usersCollection })
538 .rightJoin(
539 { post: postsCollection },
540 ({ user, post }) => eq(user.id, post.userId),
541 )
543​
544/*
545Result type:
547 user?: User, // user is optional because it is a right join
548 post: Post,
550*/
551```
552​
553### Inner Join
554​
555```ts
556// Inner join - only matching records
557const activeUserPosts = createLiveQueryCollection((q) =>
558 q
559 .from({ user: usersCollection })
560 .innerJoin(
561 { post: postsCollection },
562 ({ user, post }) => eq(user.id, post.userId),
563 )
565​
566/*
567Result type:
569 user: User,
570 post: Post,
572*/
573```
574​
575### Full Join
576​
577```ts
578// Full join - all users and all posts
579const allUsersAndPosts = createLiveQueryCollection((q) =>
580 q
581 .from({ user: usersCollection })
582 .fullJoin(
583 { post: postsCollection },
584 ({ user, post }) => eq(user.id, post.userId),
585 )
587​
588/*
589Result type:
591 user?: User, // user is optional because it is a full join
592 post?: Post, // post is optional because it is a full join
594*/
595```
596​
597### Multiple Joins
598​
599Chain multiple joins in a single query:
600​
601```ts
602const userPostComments = createLiveQueryCollection((q) =>
603 q
604 .from({ user: usersCollection })
605 .join({ post: postsCollection }, ({ user, post }) =>
606 eq(user.id, post.userId)
607 )
608 .join({ comment: commentsCollection }, ({ post, comment }) =>
609 eq(post.id, comment.postId)
610 )
611 .select(({ user, post, comment }) => ({
612 userName: user.name,
613 postTitle: post.title,
614 commentText: comment.text,
615 }))
617```
618​
619## Subqueries
620​
621Subqueries allow you to use the result of one query as input to another, they are embedded within the query itself and are compile to a single query pipeline. They are very similar to SQL subqueries that are executed as part of a single operation.
622​
623Note that subqueries are not the same as using a live query result in a `from` or `join` clause in a new query. When you do that the intermediate result is fully computed and accessible to you, subqueries are internal to their parent query and not materialised to a collection themselves and so are more efficient.
624​
625See the [Caching Intermediate Results](#caching-intermediate-results) section for more details on using live query results in a `from` or `join` clause in a new query.
626​
627### Subqueries in `from` Clauses
628​
629Use a subquery as the main source:
630​
631```ts
632const activeUserPosts = createCollection(liveQueryCollectionOptions({
633 query: (q) => {
634 // Build the subquery first
635 const activeUsers = q
636 .from({ user: usersCollection })
637 .where(({ user }) => eq(user.active, true))
639 // Use the subquery in the main query
640 return q
641 .from({ activeUser: activeUsers })
642 .join({ post: postsCollection }, ({ activeUser, post }) =>
643 eq(activeUser.id, post.userId)
644 )
645 }
646}))
647```
648​
649### Subqueries in `join` Clauses
650​
651Join with a subquery result:
652​
653```ts
654const userRecentPosts = createCollection(liveQueryCollectionOptions({
655 query: (q) => {
656 // Build the subquery first
657 const recentPosts = q
658 .from({ post: postsCollection })
659 .where(({ post }) => gt(post.createdAt, '2024-01-01'))
660 .orderBy(({ post }) => post.createdAt, 'desc')
661 .limit(1)
663 // Use the subquery in the main query
664 return q
665 .from({ user: usersCollection })
666 .join({ recentPost: recentPosts }, ({ user, recentPost }) =>
667 eq(user.id, recentPost.userId)
668 )
669 }
670}))
671```
672​
673### Subquery deduplication
674​
675When the same subquery is used multiple times within a query, it's automatically deduplicated and executed only once:
676​
677```ts
678const complexQuery = createCollection(liveQueryCollectionOptions({
679 query: (q) => {
680 // Build the subquery once
681 const activeUsers = q
682 .from({ user: usersCollection })
683 .where(({ user }) => eq(user.active, true))
685 // Use the same subquery multiple times
686 return q
687 .from({ activeUser: activeUsers })
688 .join({ post: postsCollection }, ({ activeUser, post }) =>
689 eq(activeUser.id, post.userId)
690 )
691 .join({ comment: commentsCollection }, ({ activeUser, comment }) =>
692 eq(activeUser.id, comment.userId)
693 )
694 }
695}))
696```
697​
698In this example, the `activeUsers` subquery is used twice but executed only once, improving performance.
699​
700### Complex Nested Subqueries
701​
702Build complex queries with multiple levels of nesting:
703​
704```ts
705import { count } from '@tanstack/db'
706​
707const topUsers = createCollection(liveQueryCollectionOptions({
708 query: (q) => {
709 // Build the post count subquery
710 const postCounts = q
711 .from({ post: postsCollection })
712 .groupBy(({ post }) => post.userId)
713 .select(({ post }) => ({
714 userId: post.userId,
715 count: count(post.id),
716 }))
718 // Build the user stats subquery
719 const userStats = q
720 .from({ user: usersCollection })
721 .join({ postCount: postCounts }, ({ user, postCount }) =>
722 eq(user.id, postCount.userId)
723 )
724 .select(({ user, postCount }) => ({
725 id: user.id,
726 name: user.name,
727 postCount: postCount.count,
728 }))
729 .orderBy(({ userStats }) => userStats.postCount, 'desc')
730 .limit(10)
732 // Use the user stats subquery in the main query
733 return q.from({ userStats })
734 }
735}))
736```
737​
738## groupBy and Aggregations
739​
740Use `groupBy` to group your data and apply aggregate functions. When you use aggregates in `select` without `groupBy`, the entire result set is treated as a single group.
741​
742### Method Signature
743​
744```ts
745groupBy(
746 grouper: (row: TRow) => Expression | Expression[]
747): Query
748```
749​
750**Parameters:**
751- `grouper` - A callback function that receives the row object and returns the grouping key(s). Can return a single value or an array for multi-column grouping
752​
753### Basic Grouping
754​
755Group users by their department and count them:
756​
757```ts
758import { count, avg } from '@tanstack/db'
759​
760const departmentStats = createCollection(liveQueryCollectionOptions({
761 query: (q) =>
762 q
763 .from({ user: usersCollection })
764 .groupBy(({ user }) => user.departmentId)
765 .select(({ user }) => ({
766 departmentId: user.departmentId,
767 userCount: count(user.id),
768 avgAge: avg(user.age),
769 }))
770}))
771```
772​
773> [!NOTE]
774> In `groupBy` queries, the properties in your `select` clause must either be:
775> - An aggregate function (like `count`, `sum`, `avg`)
776> - A property that was used in the `groupBy` clause
777>
778> You cannot select properties that are neither aggregated nor grouped.
779​
780### Multiple Column Grouping
781​
782Group by multiple columns by returning an array from the callback:
783​
784```ts
785const userStats = createCollection(liveQueryCollectionOptions({
786 query: (q) =>
787 q
788 .from({ user: usersCollection })
789 .groupBy(({ user }) => [user.departmentId, user.role])
790 .select(({ user }) => ({
791 departmentId: user.departmentId,
792 role: user.role,
793 count: count(user.id),
794 avgSalary: avg(user.salary),
795 }))
796}))
797```
798​
799### Aggregate Functions
800​
801Use various aggregate functions to summarize your data:
802​
803```ts
804import { count, sum, avg, min, max } from '@tanstack/db'
805​
806const orderStats = createCollection(liveQueryCollectionOptions({
807 query: (q) =>
808 q
809 .from({ order: ordersCollection })
810 .groupBy(({ order }) => order.customerId)
811 .select(({ order }) => ({
812 customerId: order.customerId,
813 totalOrders: count(order.id),
814 totalAmount: sum(order.amount),
815 avgOrderValue: avg(order.amount),
816 minOrder: min(order.amount),
817 maxOrder: max(order.amount),
818 }))
819}))
820```
821​
822See the [Aggregate Functions](#aggregate-functions) section for a complete list of available aggregate functions.
823​
824### Having Clauses
825​
826Filter aggregated results using `having` - this is similar to the `where` clause, but is applied after the aggregation has been performed.
827​
828#### Method Signature
829​
830```ts
831having(
832 condition: (row: TRow) => Expression<boolean>
833): Query
834```
835​
836**Parameters:**
837- `condition` - A callback function that receives the aggregated row object and returns a boolean expression
838​
839```ts
840const highValueCustomers = createLiveQueryCollection((q) =>
841 q
842 .from({ order: ordersCollection })
843 .groupBy(({ order }) => order.customerId)
844 .select(({ order }) => ({
845 customerId: order.customerId,
846 totalSpent: sum(order.amount),
847 orderCount: count(order.id),
848 }))
849 .having(({ order }) => gt(sum(order.amount), 1000))
851```
852​
853### Implicit Single-Group Aggregation
854​
855When you use aggregates without `groupBy`, the entire result set is grouped:
856​
857```ts
858const overallStats = createLiveQueryCollection((q) =>
859 q
860 .from({ user: usersCollection })
861 .select(({ user }) => ({
862 totalUsers: count(user.id),
863 avgAge: avg(user.age),
864 maxSalary: max(user.salary),
865 }))
867```
868​
869This is equivalent to grouping the entire collection into a single group.
870​
871### Accessing Grouped Data
872​
873Grouped results can be accessed by the group key:
874​
875```ts
876const deptStats = createCollection(liveQueryCollectionOptions({
877 query: (q) =>
878 q
879 .from({ user: usersCollection })
880 .groupBy(({ user }) => user.departmentId)
881 .select(({ user }) => ({
882 departmentId: user.departmentId,
883 count: count(user.id),
884 }))
885}))
886​
887// Access by department ID
888const engineeringStats = deptStats.get(1)
889```
890​
891> **Note**: Grouped results are keyed differently based on the grouping:
892> - **Single column grouping**: Keyed by the actual value (e.g., `deptStats.get(1)`)
893> - **Multiple column grouping**: Keyed by a JSON string of the grouped values (e.g., `userStats.get('[1,"admin"]')`)
894​
895## Distinct
896​
897Use `distinct` to remove duplicate rows from your query results based on the selected columns. The `distinct` operator ensures that each unique combination of selected values appears only once in the result set.
898​
899> [!IMPORTANT]
900> The `distinct` operator requires a `select` clause. You cannot use `distinct` without specifying which columns to select.
901​
902### Method Signature
903​
904```ts
905distinct(): Query
906```
907​
908### Basic Usage
909​
910Get unique values from a single column:
911​
912```ts
913const uniqueCountries = createLiveQueryCollection((q) =>
914 q
915 .from({ user: usersCollection })
916 .select(({ user }) => ({ country: user.country }))
917 .distinct()
919​
920// Result contains only unique countries
921// If you have users from USA, Canada, and UK, the result will have 3 items
922```
923​
924### Multiple Column Distinct
925​
926Get unique combinations of multiple columns:
927​
928```ts
929const uniqueRoleSalaryPairs = createLiveQueryCollection((q) =>
930 q
931 .from({ user: usersCollection })
932 .select(({ user }) => ({
933 role: user.role,
934 salary: user.salary,
935 }))
936 .distinct()
938​
939// Result contains only unique role-salary combinations
940// e.g., Developer-75000, Developer-80000, Manager-90000
941```
942​
943### Edge Cases
944​
945#### Null Values
946​
947Null values are treated as distinct values:
948​
949```ts
950const uniqueValues = createLiveQueryCollection((q) =>
951 q
952 .from({ user: usersCollection })
953 .select(({ user }) => ({ department: user.department }))
954 .distinct()
956​
957// If some users have null departments, null will appear as a distinct value
958// Result might be: ['Engineering', 'Marketing', null]
959```
960​
961## Order By, Limit, and Offset
962​
963Use `orderBy`, `limit`, and `offset` to control the order and pagination of your results. Ordering is performed incrementally for optimal performance.
964​
965### Method Signatures
966​
967```ts
968orderBy(
969 selector: (row: TRow) => Expression,
970 direction?: 'asc' | 'desc'
971): Query
972​
973limit(count: number): Query
974​
975offset(count: number): Query
976```
977​
978**Parameters:**
979- `selector` - A callback function that receives the row object and returns the value to sort by
980- `direction` - Sort direction: `'asc'` (default) or `'desc'`
981- `count` - Number of rows to limit or skip
982​
983### Basic Ordering
984​
985Sort results by a single column:
986​
987```ts
988const sortedUsers = createLiveQueryCollection((q) =>
989 q
990 .from({ user: usersCollection })
991 .orderBy(({ user }) => user.name)
992 .select(({ user }) => ({
993 id: user.id,
994 name: user.name,
995 }))
997```
998​
999### Multiple Column Ordering
1000​
1001Order by multiple columns:
1002​
1003```ts
1004const sortedUsers = createLiveQueryCollection((q) =>
1006 .from({ user: usersCollection })
1007 .orderBy(({ user }) => user.departmentId, 'asc')
1008 .orderBy(({ user }) => user.name, 'asc')
1009 .select(({ user }) => ({
1010 id: user.id,
1011 name: user.name,
1012 departmentId: user.departmentId,
1013 }))
1015```
1016​
1017### Descending Order
1018​
1019Use `desc` for descending order:
1020​
1021```ts
1022const recentPosts = createLiveQueryCollection((q) =>
1024 .from({ post: postsCollection })
1025 .orderBy(({ post }) => post.createdAt, 'desc')
1026 .select(({ post }) => ({
1027 id: post.id,
1028 title: post.title,
1029 createdAt: post.createdAt,
1030 }))
1032```
1033​
1034### Pagination with `limit` and `offset`
1035​
1036Skip results using `offset`:
1037​
1038```ts
1039const page2Users = createLiveQueryCollection((q) =>
1041 .from({ user: usersCollection })
1042 .orderBy(({ user }) => user.name, 'asc')
1043 .limit(20)
1044 .offset(20) // Skip first 20 results
1045 .select(({ user }) => ({
1046 id: user.id,
1047 name: user.name,
1048 }))
1050```
1051​
1052## Composable Queries
1053​
1054Build complex queries by composing smaller, reusable parts. This approach makes your queries more maintainable and allows for better performance through caching.
1055​
1056### Conditional Query Building
1057​
1058Build queries based on runtime conditions:
1059​
1060```ts
1061import { Query, eq } from '@tanstack/db'
1062​
1063function buildUserQuery(options: { activeOnly?: boolean; limit?: number }) {
1064 let query = new Query().from({ user: usersCollection })
1066 if (options.activeOnly) {
1067 query = query.where(({ user }) => eq(user.active, true))
1070 if (options.limit) {
1071 query = query.limit(options.limit)
1074 return query.select(({ user }) => ({
1075 id: user.id,
1076 name: user.name,
1077 }))
1079​
1080const activeUsers = createLiveQueryCollection(buildUserQuery({ activeOnly: true, limit: 10 }))
1081```
1082​
1083### Caching Intermediate Results
1084​
1085The result of a live query collection is a collection itself, and will automatically update when the underlying data changes. This means that you can use the result of a live query collection as a source in another live query collection. This pattern is useful for building complex queries where you want to cache intermediate results to make further queries faster.
1086​
1087```ts
1088// Base query for active users
1089const activeUsers = createLiveQueryCollection((q) =>
1091 .from({ user: usersCollection })
1092 .where(({ user }) => eq(user.active, true))
1094​
1095// Query that depends on active users
1096const activeUserPosts = createLiveQueryCollection((q) =>
1098 .from({ user: activeUsers })
1099 .join({ post: postsCollection }, ({ user, post }) =>
1100 eq(user.id, post.userId)
1102 .select(({ user, post }) => ({
1103 userName: user.name,
1104 postTitle: post.title,
1105 }))
1107```
1108​
1109### Reusable Query Definitions
1110​
1111You can use the `Query` class to create reusable query definitions. This is useful for building complex queries where you want to reuse the same query builder instance multiple times throughout your application.
1112​
1113```ts
1114import { Query, eq } from '@tanstack/db'
1115​
1116// Create a reusable query builder
1117const userQuery = new Query()
1118 .from({ user: usersCollection })
1119 .where(({ user }) => eq(user.active, true))
1120​
1121// Use it in different contexts
1122const activeUsers = createLiveQueryCollection({
1123 query: userQuery.select(({ user }) => ({
1124 id: user.id,
1125 name: user.name,
1126 }))
1128​
1129// Or as a subquery
1130const userPosts = createLiveQueryCollection((q) =>
1132 .from({ activeUser: userQuery })
1133 .join({ post: postsCollection }, ({ activeUser, post }) =>
1134 eq(activeUser.id, post.userId)
1137```
1138​
1139### Reusable Callback Functions
1140​
1141Use `Ref<MyType>` to create reusable callback functions:
1142​
1143```ts
1144import { Ref, eq, gt, and } from '@tanstack/db'
1145​
1146// Create reusable callbacks
1147const isActiveUser = (user: Ref<User>) => eq(user.active, true)
1148const isAdultUser = (user: Ref<User>) => gt(user.age, 18)
1149​
1150// Use them in queries
1151const activeAdults = createCollection(liveQueryCollectionOptions({
1152 query: (q) =>
1154 .from({ user: usersCollection })
1155 .where(({ user }) => and(isActiveUser(user), isAdultUser(user)))
1156 .select(({ user }) => ({
1157 id: user.id,
1158 name: user.name,
1159 age: user.age,
1160 }))
1161}))
1162```
1163​
1164You can also create callbacks that take the whole row and pass them directly to `where`:
1165​
1166```ts
1167// Callback that takes the whole row
1168const isHighValueCustomer = (row: { user: User; order: Order }) =>
1169 row.user.active && row.order.amount > 1000
1170​
1171// Use directly in where clause
1172const highValueCustomers = createCollection(liveQueryCollectionOptions({
1173 query: (q) =>
1175 .from({ user: usersCollection })
1176 .join({ order: ordersCollection }, ({ user, order }) =>
1177 eq(user.id, order.userId)
1179 .where(isHighValueCustomer)
1180 .select(({ user, order }) => ({
1181 userName: user.name,
1182 orderAmount: order.amount,
1183 }))
1184}))
1185```
1186​
1187This approach makes your query logic more modular and testable.
1188​
1189## Expression Functions Reference
1190​
1191The query system provides a comprehensive set of functions for filtering, transforming, and aggregating data.
1192​
1193### Comparison Operators
1194​
1195#### `eq(left, right)`
1196Equality comparison:
1197```ts
1198eq(user.id, 1)
1199eq(user.name, 'John')
1200```
1201​
1202#### `gt(left, right)`, `gte(left, right)`, `lt(left, right)`, `lte(left, right)`
1203Numeric, string and date comparisons:
1204```ts
1205gt(user.age, 18)
1206gte(user.salary, 50000)
1207lt(user.createdAt, new Date('2024-01-01'))
1208lte(user.rating, 5)
1209```
1210​
1211#### `inArray(value, array)`
1212Check if a value is in an array:
1213```ts
1214inArray(user.id, [1, 2, 3])
1215inArray(user.role, ['admin', 'moderator'])
1216```
1217​
1218#### `like(value, pattern)`, `ilike(value, pattern)`
1219String pattern matching:
1220```ts
1221like(user.name, 'John%') // Case-sensitive
1222ilike(user.email, '%@gmail.com') // Case-insensitive
1223```
1224​
1225### Logical Operators
1226​
1227#### `and(...conditions)`
1228Combine conditions with AND logic:
1229```ts
1230and(
1231 eq(user.active, true),
1232 gt(user.age, 18),
1233 eq(user.role, 'user')
1235```
1236​
1237#### `or(...conditions)`
1238Combine conditions with OR logic:
1239```ts
1240or(
1241 eq(user.role, 'admin'),
1242 eq(user.role, 'moderator')
1244```
1245​
1246#### `not(condition)`
1247Negate a condition:
1248```ts
1249not(eq(user.active, false))
1250```
1251​
1252### String Functions
1253​
1254#### `upper(value)`, `lower(value)`
1255Convert case:
1256```ts
1257upper(user.name) // 'JOHN'
1258lower(user.email) // 'john@example.com'
1259```
1260​
1261#### `length(value)`
1262Get string or array length:
1263```ts
1264length(user.name) // String length
1265length(user.tags) // Array length
1266```
1267​
1268#### `concat(...values)`
1269Concatenate strings:
1270```ts
1271concat(user.firstName, ' ', user.lastName)
1272concat('User: ', user.name, ' (', user.id, ')')
1273```
1274​
1275### Mathematical Functions
1276​
1277#### `add(left, right)`
1278Add two numbers:
1279```ts
1280add(user.salary, user.bonus)
1281```
1282​
1283#### `coalesce(...values)`
1284Return the first non-null value:
1285```ts
1286coalesce(user.displayName, user.name, 'Unknown')
1287```
1288​
1289### Aggregate Functions
1290​
1291#### `count(value)`
1292Count non-null values:
1293```ts
1294count(user.id) // Count all users
1295count(user.postId) // Count users with posts
1296```
1297​
1298#### `sum(value)`
1299Sum numeric values:
1300```ts
1301sum(order.amount)
1302sum(user.salary)
1303```
1304​
1305#### `avg(value)`
1306Calculate average:
1307```ts
1308avg(user.salary)
1309avg(order.amount)
1310```
1311​
1312#### `min(value)`, `max(value)`
1313Find minimum and maximum values:
1314```ts
1315min(user.salary)
1316max(order.amount)
1317```
1318​
1319### Function Composition
1320​
1321Functions can be composed and chained:
1322​
1323```ts
1324// Complex condition
1325and(
1326 eq(user.active, true),
1327 or(
1328 gt(user.age, 25),
1329 eq(user.role, 'admin')
1330 ),
1331 not(inArray(user.id, bannedUserIds))
1333​
1334// Complex transformation
1335concat(
1336 upper(user.firstName),
1337 ' ',
1338 upper(user.lastName),
1339 ' (',
1340 user.id,
1341 ')'
1343​
1344// Complex aggregation
1345avg(add(user.salary, coalesce(user.bonus, 0)))
1346```
1347​
1348## Functional Variants
1349​
1350The functional variant API provides an alternative to the standard API, offering more flexibility for complex transformations. With functional variants, the callback functions contain actual code that gets executed to perform the operation, giving you the full power of JavaScript at your disposal.
1351​
1352> [!WARNING]
1353> The functional variant API cannot be optimized by the query optimizer or use collection indexes. It is intended for use in rare cases where the standard API is not sufficient.
1354​
1355### Functional Select
1356​
1357Use `fn.select()` for complex transformations with JavaScript logic:
1358​
1359```ts
1360const userProfiles = createLiveQueryCollection((q) =>
1362 .from({ user: usersCollection })
1363 .fn.select((row) => ({
1364 id: row.user.id,
1365 displayName: `${row.user.firstName} ${row.user.lastName}`,
1366 salaryTier: row.user.salary > 100000 ? 'senior' : 'junior',
1367 emailDomain: row.user.email.split('@')[1],
1368 isHighEarner: row.user.salary > 75000,
1369 }))
1371```
1372​
1373### Functional Where
1374​
1375Use `fn.where()` for complex filtering logic:
1376​
1377```ts
1378const specialUsers = createLiveQueryCollection((q) =>
1380 .from({ user: usersCollection })
1381 .fn.where((row) => {
1382 const user = row.user
1383 return user.active &&
1384 (user.age > 25 || user.role === 'admin') &&
1385 user.email.includes('@company.com')
1386 })
1388```
1389​
1390### Functional Having
1391​
1392Use `fn.having()` for complex aggregation filtering:
1393​
1394```ts
1395const highValueCustomers = createLiveQueryCollection((q) =>
1397 .from({ order: ordersCollection })
1398 .groupBy(({ order }) => order.customerId)
1399 .select(({ order }) => ({
1400 customerId: order.customerId,
1401 totalSpent: sum(order.amount),
1402 orderCount: count(order.id),
1403 }))
1404 .fn.having((row) => {
1405 return row.totalSpent > 1000 && row.orderCount >= 3
1406 })
1408```
1409​
1410### Complex Transformations
1411​
1412Functional variants excel at complex data transformations:
1413​
1414```ts
1415const userProfiles = createLiveQueryCollection((q) =>
1417 .from({ user: usersCollection })
1418 .fn.select((row) => {
1419 const user = row.user
1420 const fullName = `${user.firstName} ${user.lastName}`.trim()
1421 const emailDomain = user.email.split('@')[1]
1422 const ageGroup = user.age < 25 ? 'young' : user.age < 50 ? 'adult' : 'senior'
1424 return {
1425 userId: user.id,
1426 displayName: fullName || user.name,
1427 contactInfo: {
1428 email: user.email,
1429 domain: emailDomain,
1430 isCompanyEmail: emailDomain === 'company.com'
1431 },
1432 demographics: {
1433 age: user.age,
1434 ageGroup: ageGroup,
1435 isAdult: user.age >= 18
1436 },
1437 status: user.active ? 'active' : 'inactive',
1438 profileStrength: fullName && user.email && user.age ? 'complete' : 'incomplete'
1440 })
1442```
1443​
1444### Type Inference
1445​
1446Functional variants maintain full TypeScript support:
1447​
1448```ts
1449const processedUsers = createLiveQueryCollection((q) =>
1451 .from({ user: usersCollection })
1452 .fn.select((row): ProcessedUser => ({
1453 id: row.user.id,
1454 name: row.user.name.toUpperCase(),
1455 age: row.user.age,
1456 ageGroup: row.user.age < 25 ? 'young' : row.user.age < 50 ? 'adult' : 'senior',
1457 }))
1459```
1460​
1461### When to Use Functional Variants
1462​
1463Use functional variants when you need:
1464- Complex JavaScript logic that can't be expressed with built-in functions
1465- Integration with external libraries or utilities
1466- Full JavaScript power for custom operations
1467​
1468The callbacks in functional variants are actual JavaScript functions that get executed, unlike the standard API which uses declarative expressions. This gives you complete control over the logic but comes with the trade-off of reduced optimization opportunities.
1469​
1470However, prefer the standard API when possible, as it provides better performance and optimization opportunities.