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