---
layout: post
title: "Announcing joins and aggregations in TablesDB"
description: "TablesDB now joins tables and aggregates rows on the server, with a query builder in every Appwrite SDK and request-body queries for long query lists."
date: 2026-12-05
cover: /images/blog/announcing-tablesdb-joins-and-aggregations/cover.avif
timeToRead: 8
author: jake-barnby
category: announcements
featured: false
faqs:
  - question: "Does Appwrite TablesDB support joins?"
    answer: "Yes. TablesDB supports inner, left, right, full outer, and cross joins through `Query.join()`, `Query.leftJoin()`, `Query.rightJoin()`, `Query.fullOuterJoin()`, and `Query.crossJoin()`. You pass them to `listRows()` with your other queries, match rows on any columns with `Query.on()`, and read joined columns as `alias.column`. A query can join up to 8 tables from the same database. See [Joins](/docs/products/databases/tablesdb/joins)."
  - question: "How do I count or sum rows in Appwrite TablesDB?"
    answer: "Pass an aggregation query to `listRows()`, such as `Query.count('*', 'orders')` or `Query.sum('total', 'revenue')`. The second argument is the alias the result comes back under. Add `Query.groupBy()` to get one result per group, and `Query.having()` to filter groups on their results. See [Aggregations](/docs/products/databases/tablesdb/aggregations)."
  - question: "What is the Appwrite query builder?"
    answer: "`Query.builder()` chains queries instead of listing them in an array, for example `Query.builder().equal('status', ['paid']).orderDesc('total').limit(10).build()`. `build()` returns the list of query strings that `listRows()`, `getRow()`, and `createQuery()` take. Every Appwrite SDK has one, named for its conventions, such as `query.NewBuilder()` in Go. See [Query builder](/docs/products/databases/tablesdb/queries#query-builder)."
  - question: "Should I use joins or relationships in TablesDB?"
    answer: "Use [relationships](/docs/products/databases/tablesdb/relationships) for data that belongs together and that you write together, such as an album and its songs, when you want related rows nested in each result. Use [joins](/docs/products/databases/tablesdb/joins) for reads across tables that aren't modeled as relationships, for filtering or sorting by another table, and for reports with aggregations. A project can use both."
  - question: "Do TablesDB joins and aggregations respect permissions?"
    answer: "Yes. You can only join a table you can read, and joined rows you can't read never match. Aggregations only count and sum rows the caller can read, so the same query can return different results for different users. Server SDKs with an API key that has the `rows.read` scope see every row. See [Permissions](/docs/products/databases/tablesdb/permissions)."
  - question: "Which Appwrite databases support joins and aggregations?"
    answer: "Joins and aggregations work in TablesDB on SQL databases, on Appwrite Cloud and on self-hosted Appwrite 2.6.0 and later. They are not available in DocumentsDB, or on self-hosted installations that use MongoDB."
  - question: "How do I send a long list of queries to TablesDB?"
    answer: "Use `createQuery()` instead of `listRows()`. It takes the same queries in the request body rather than the URL, returns the same row list, and accepts the same `transactionId`, `total`, and `ttl` options. A request accepts up to 100 queries. See [Send queries in the request body](/docs/products/databases/tablesdb/queries#create-query)."
---

A list of orders that shows each customer's name. A dashboard with revenue per country. A leaderboard of your biggest spenders. These are some of the most common reads an app makes, and until now TablesDB made you assemble them yourself. You fetched the orders, collected their customer IDs, fetched the customers in a second request, and matched the two in your app. For a total, you paged through every matching row and added the numbers up on the client, downloading thousands of rows to show one figure.

[Relationships](/docs/products/databases/tablesdb/relationships) cover part of this when the link is part of your schema, but not reads across tables you never modeled that way, and nothing in TablesDB counted, summed, or grouped rows on the server.

Today, we are announcing **joins and aggregations in TablesDB**, along with a query builder in every Appwrite SDK.

# What's new in TablesDB queries

- **Joins.** `Query.join()`, `Query.leftJoin()`, `Query.rightJoin()`, `Query.fullOuterJoin()`, and `Query.crossJoin()` read rows from up to 8 more tables in the same request, matched on any columns with `=`, `<`, `>`, and other operators.
- **Aggregations.** `Query.count()`, `Query.countDistinct()`, `Query.sum()`, `Query.avg()`, `Query.min()`, and `Query.max()`, plus standard deviation, variance, and bitwise functions, all computed by the database.
- **Grouping.** `Query.groupBy()` runs each aggregation once per group, and `Query.having()` filters groups on their results.
- **Distinct values.** `Query.distinct()` returns each combination of the selected columns once.
- **A query builder in every SDK.** `Query.builder()` chains queries, and `build()` returns the list that `listRows()` takes.
- **Page numbers.** `Query.page()` turns a page number into the matching limit and offset.
- **Queries in the request body.** `createQuery()` takes the same queries as `listRows()` in the request body, for lists too long for a URL.

All of these are regular [queries](/docs/products/databases/tablesdb/queries). They go in the same `queries` list as your filters, ordering, and pagination, and they follow the permissions you already set.

# Join tables in one request

The examples in this post use two tables: `customers`, with `name` and `country` columns, and `orders`, with `customerId`, `total`, and `status`. To list orders with the name of the customer who placed each one, list the `orders` table and join `customers` on the order's `customerId`. These snippets assume a `tablesDB` client set up as in the [Joins documentation](/docs/products/databases/tablesdb/joins#join-two-tables):

```client-web
const result = await tablesDB.listRows({
    databaseId: '<DATABASE_ID>',
    tableId: 'orders',
    queries: [
        Query.join('customers', 'customer', [
            Query.on('customerId', '$id')
        ]),
        Query.select(['$id', 'total', 'customer.name'])
    ]
});
```
```server-nodejs
const result = await tablesDB.listRows({
    databaseId: '<DATABASE_ID>',
    tableId: 'orders',
    queries: [
        sdk.Query.join('customers', 'customer', [
            sdk.Query.on('customerId', '$id')
        ]),
        sdk.Query.select(['$id', 'total', 'customer.name'])
    ]
});
```
```client-flutter
final result = await tablesDB.listRows(
    databaseId: '<DATABASE_ID>',
    tableId: 'orders',
    queries: [
        Query.join('customers', 'customer', [
            Query.on('customerId', '\$id'),
        ]),
        Query.select(['\$id', 'total', 'customer.name']),
    ],
);
```
```client-apple
let result = try await tablesDB.listRows(
    databaseId: "<DATABASE_ID>",
    tableId: "orders",
    queries: [
        Query.join("customers", alias: "customer", on: [
            Query.on("customerId", "$id")
        ]),
        Query.select(["$id", "total", "customer.name"])
    ]
)
```
```client-android-kotlin
val result = tablesDB.listRows(
    databaseId = "<DATABASE_ID>",
    tableId = "orders",
    queries = listOf(
        Query.join("customers", "customer", listOf(
            Query.on("customerId", "\$id")
        )),
        Query.select(listOf("\$id", "total", "customer.name"))
    )
)
```
```server-python
result = tables_db.list_rows(
    database_id='<DATABASE_ID>',
    table_id='orders',
    queries=[
        Query.join('customers', 'customer', [
            Query.on('customerId', '$id')
        ]),
        Query.select(['$id', 'total', 'customer.name'])
    ]
)
```
```server-php
$result = $tablesDB->listRows(
    databaseId: '<DATABASE_ID>',
    tableId: 'orders',
    queries: [
        Query::join('customers', 'customer', [
            Query::on('customerId', '$id')
        ]),
        Query::select(['$id', 'total', 'customer.name'])
    ]
);
```
```server-ruby
result = tables_db.list_rows(
    database_id: '<DATABASE_ID>',
    table_id: 'orders',
    queries: [
        Query.join('customers', 'customer', [
            Query.on('customerId', '$id')
        ]),
        Query.select(['$id', 'total', 'customer.name'])
    ]
)
```
```server-go
result, err := tablesDB.ListRows(
    "<DATABASE_ID>",
    "orders",
    tablesDB.WithListRowsQueries([]string{
        query.JoinOn("customers", "customer", []string{
            query.On("customerId", "$id", "="),
        }),
        query.Select([]interface{}{"$id", "total", "customer.name"}),
    }),
)
```
```server-dotnet
RowList result = await tablesDB.ListRows(
    databaseId: "<DATABASE_ID>",
    tableId: "orders",
    queries: new List<string>
    {
        Query.Join("customers", "customer", new List<string>
        {
            Query.On("customerId", "$id")
        }),
        Query.Select(new List<string> { "$id", "total", "customer.name" })
    }
);
```
```server-rust
let result = tables_db
    .list_rows(
        "<DATABASE_ID>",
        "orders",
        Some(vec![
            Query::join_on("customers", "customer", vec![
                Query::on("customerId", "$id", "=").to_string(),
            ])
            .to_string(),
            Query::select(vec!["$id", "total", "customer.name"]).to_string(),
        ]),
        None,
        None,
        None,
    )
    .await?;
```

`Query.join()` takes the table to join, an alias, and one or more `Query.on()` conditions. Each condition compares a column of the table you list with a column of the joined table, and system columns such as `$id` work on either side. Each order comes back as one flat row, with the customer's columns next to the order's own and named after the alias, such as `customer.name`.

Joined columns behave like any other column in the query. Filter on them with `Query.equal('customer.country', ['DE'])`, sort on them with `Query.orderDesc()`, and select only the ones you need. A later join can match on an earlier one by its alias, so orders, their customers, and their payments come back in one request. When a join has a single condition, you can also pass its columns straight to the join method, as in `Query.join('customers', 'customerId', '$id', '=', 'customer')`.

## Pick a join type

The join type decides what happens to rows without a match:

- **`Query.join()`** returns only rows that have a match in both tables.
- **`Query.leftJoin()`** keeps every row of the table you list, with `null` joined columns where nothing matched. List customers with a left join on orders, and customers who haven't ordered yet still appear.
- **`Query.rightJoin()`** keeps every row of the joined table.
- **`Query.fullOuterJoin()`** keeps every row of both tables, matched where possible.
- **`Query.crossJoin()`** returns every combination of rows from both tables, and takes no conditions.

Joins also work with `getRow()`, to read one row together with its related data, and inside [transactions](/docs/products/databases/tablesdb/transactions), where the result includes the changes the transaction has staged.

## Joins follow your permissions

A join can't show a user anything that a direct `listRows()` call would hide. You can only join a table you have read access to, or one with row security enabled. Joined rows you can't read never match: an inner join leaves out a row whose only matches are hidden, and a left join keeps it with `null` joined columns. A server SDK with an API key that has the `rows.read` scope can join every table and read every row.

# Aggregate rows on the server

Aggregations compute values over many rows and return only the result. To get the number of orders and the revenue for each status, group the `orders` table by `status` and add two aggregations:

```client-web
Query.groupBy(['status']),
Query.count('*', 'orders'),
Query.sum('total', 'revenue')
```

The second argument of each aggregation is its alias, the key the result comes back under. Each result row holds the grouped columns and the aggregations for that group, and `total` is the number of groups:

```json
{
    "total": 3,
    "rows": [
        { "status": "paid", "orders": 120, "revenue": 4830.5 },
        { "status": "pending", "orders": 14, "revenue": 512 },
        { "status": "refunded", "orders": 3, "revenue": 96.75 }
    ]
}
```

Your app downloads three rows instead of every order. Without `Query.groupBy()`, you get a single row with one value per aggregation, which is what a counter or a dashboard total needs. The [Aggregations documentation](/docs/products/databases/tablesdb/aggregations#group-rows) shows this query in every SDK.

Filters such as `Query.equal()` run before grouping, so they decide which rows are counted. To filter on the results themselves, wrap the conditions in `Query.having()`, which runs after grouping. `Query.having([Query.greaterThan('revenue', 1000)])` keeps only the statuses with more than $1,000 in revenue. Sort groups by an alias with `Query.orderDesc('revenue')`, and page through them with `Query.limit()` and `Query.offset()`.

To list the values present in a column, such as the countries your customers are in for a filter dropdown, select the column and add `Query.distinct()`.

# Chain queries with the query builder

A report across tables can take half a dozen queries, and an array of them gets hard to read. Every Appwrite SDK now has a query builder. Start with `Query.builder()`, call one method per query, and finish with `build()`, which returns the same list of query strings that `listRows()` takes.

This query finds the customers who spent more than $1,000, biggest spenders first. It lists the `customers` table, joins their orders, sums the order totals per customer, and keeps the customers above the threshold:

```client-web
const result = await tablesDB.listRows({
    databaseId: '<DATABASE_ID>',
    tableId: 'customers',
    queries: Query.builder()
        .join('orders', 'order', [Query.on('$id', 'customerId')])
        .groupBy(['$id', 'name'])
        .sum('order.total', 'spent')
        .having([Query.greaterThan('spent', 1000)])
        .orderDesc('spent')
        .limit(10)
        .build()
});
```
```server-nodejs
const result = await tablesDB.listRows({
    databaseId: '<DATABASE_ID>',
    tableId: 'customers',
    queries: sdk.Query.builder()
        .join('orders', 'order', [sdk.Query.on('$id', 'customerId')])
        .groupBy(['$id', 'name'])
        .sum('order.total', 'spent')
        .having([sdk.Query.greaterThan('spent', 1000)])
        .orderDesc('spent')
        .limit(10)
        .build()
});
```
```client-flutter
final result = await tablesDB.listRows(
    databaseId: '<DATABASE_ID>',
    tableId: 'customers',
    queries: Query.builder()
        .join('orders', 'order', [Query.on('\$id', 'customerId')])
        .groupBy(['\$id', 'name'])
        .sum('order.total', 'spent')
        .having([Query.greaterThan('spent', 1000)])
        .orderDesc('spent')
        .limit(10)
        .build(),
);
```
```client-apple
let result = try await tablesDB.listRows(
    databaseId: "<DATABASE_ID>",
    tableId: "customers",
    queries: Query.builder()
        .join("orders", alias: "order", on: [Query.on("$id", "customerId")])
        .groupBy(["$id", "name"])
        .sum("order.total", alias: "spent")
        .having([Query.greaterThan("spent", value: 1000)])
        .orderDesc("spent")
        .limit(10)
        .build()
)
```
```client-android-kotlin
val result = tablesDB.listRows(
    databaseId = "<DATABASE_ID>",
    tableId = "customers",
    queries = Query.builder()
        .join("orders", "order", listOf(Query.on("\$id", "customerId")))
        .groupBy(listOf("\$id", "name"))
        .sum("order.total", "spent")
        .having(listOf(Query.greaterThan("spent", 1000)))
        .orderDesc("spent")
        .limit(10)
        .build()
)
```
```server-python
result = tables_db.list_rows(
    database_id='<DATABASE_ID>',
    table_id='customers',
    queries=(
        Query.builder()
        .join('orders', 'order', [Query.on('$id', 'customerId')])
        .group_by(['$id', 'name'])
        .sum('order.total', 'spent')
        .having([Query.greater_than('spent', 1000)])
        .order_desc('spent')
        .limit(10)
        .build()
    )
)
```
```server-php
$result = $tablesDB->listRows(
    databaseId: '<DATABASE_ID>',
    tableId: 'customers',
    queries: Query::builder()
        ->join('orders', 'order', [Query::on('$id', 'customerId')])
        ->groupBy(['$id', 'name'])
        ->sum('order.total', 'spent')
        ->having([Query::greaterThan('spent', 1000)])
        ->orderDesc('spent')
        ->limit(10)
        ->build()
);
```
```server-ruby
result = tables_db.list_rows(
    database_id: '<DATABASE_ID>',
    table_id: 'customers',
    queries: Query.builder
        .join('orders', 'order', [Query.on('$id', 'customerId')])
        .group_by(['$id', 'name'])
        .sum('order.total', 'spent')
        .having([Query.greater_than('spent', 1000)])
        .order_desc('spent')
        .limit(10)
        .build
)
```
```server-go
result, err := tablesDB.ListRows(
    "<DATABASE_ID>",
    "customers",
    tablesDB.WithListRowsQueries(
        query.NewBuilder().
            JoinOn("orders", "order", []string{query.On("$id", "customerId", "=")}).
            GroupBy([]interface{}{"$id", "name"}).
            Sum("order.total", "spent").
            Having([]string{query.GreaterThan("spent", 1000)}).
            OrderDesc("spent").
            Limit(10).
            Build(),
    ),
)
```
```server-dotnet
RowList result = await tablesDB.ListRows(
    databaseId: "<DATABASE_ID>",
    tableId: "customers",
    queries: new Query.Builder()
        .Join("orders", "order", new List<string> { Query.On("$id", "customerId") })
        .GroupBy(new List<string> { "$id", "name" })
        .Sum("order.total", "spent")
        .Having(new List<string> { Query.GreaterThan("spent", 1000) })
        .OrderDesc("spent")
        .Limit(10)
        .Build()
);
```
```server-rust
let result = tables_db
    .list_rows(
        "<DATABASE_ID>",
        "customers",
        Some(
            Query::builder()
                .join_on("orders", "order", vec![Query::on("$id", "customerId", "=").to_string()])
                .group_by(vec!["$id", "name"])
                .sum("order.total", "spent")
                .having(vec![Query::greater_than("spent", 1000).to_string()])
                .order_desc("spent")
                .limit(10)
                .build(),
        ),
        None,
        None,
        None,
    )
    .await?;
```

Grouping by `$id` as well as `name` keeps two customers with the same name apart. One request returns at most ten rows, each with a customer's ID, name, and total spend, however many orders sit behind them.

The builder has a method for every `Query` method, with the same name and arguments, so nothing you know about queries changes. It's named for each language: `Query::builder()` in PHP and Rust, `query.NewBuilder()` in Go, and `new Query.Builder()` in .NET. Because each call adds one query, it also fits queries you assemble in code, such as adding a country filter only when a user picks one. In the Web and React Native SDKs, [Realtime subscriptions](/docs/apis/realtime/queries) accept a builder for their queries directly.

For pagination by page number, call `.page(3, 25)` on the builder, or spread `Query.page(3, 25)` into a query list. Both produce the limit and offset for the third page of 25 rows.

# Send long query lists in the request body

`listRows()` sends queries in the URL. Joins, aggregations, and long value lists, such as `Query.equal('$id', [...])` with hundreds of row IDs, can make that URL longer than the server accepts. `createQuery()` takes the same queries in the request body instead:

```client-web
const result = await tablesDB.createQuery({
    databaseId: '<DATABASE_ID>',
    tableId: 'orders',
    queries: Query.builder()
        .equal('$id', orderIds)
        .build()
});
```

It returns the same row list as `listRows()`, accepts the same `transactionId`, `total`, and `ttl` options, and follows the same read permissions. A request still accepts up to 100 queries. The [Queries documentation](/docs/products/databases/tablesdb/queries#create-query) has the call in every SDK.

# When to reach for joins and aggregations

Joins and aggregations don't replace the rest of TablesDB. They fill the gaps where you used to make several requests or do the database's work in your app:

- **Use a join** when a list needs columns from another table, or when you filter or sort by another table. Add an [index](/docs/products/databases/tablesdb/tables#indexes) to the columns you join on often, such as `customerId`.
- **Keep relationships** for data you create and update together, such as an album and its songs, when you want related rows nested in each result. A project can use both.
- **Use aggregations** wherever you download rows only to count or add them up: unread counters, dashboard totals, leaderboards, and filter options from `Query.distinct()`.
- **Use the query builder** when a query has more than a few parts, or when you assemble it from user input.
- **Run aggregations outside transactions.** Joins read a transaction's staged changes, but aggregations and grouping can't run inside a transaction. Run them after you commit.

A few limits apply. A query can have up to 8 joins, all to tables in the same database. `total` counts up to 5,000 groups or rows, and cursor pagination isn't available with aggregations, so page through groups with limit and offset. The [Joins](/docs/products/databases/tablesdb/joins#limits) and [Aggregations](/docs/products/databases/tablesdb/aggregations#limits) pages list the rest.

# Availability

Joins and aggregations work in TablesDB on SQL databases. They are available on Appwrite Cloud today, and on self-hosted Appwrite 2.6.0 and later, except on installations that use MongoDB. They are not available in DocumentsDB.

# Get started with joins and aggregations in TablesDB

Start with one list that makes two requests today, such as orders with their customers' names, and turn it into a single join. Then find the screen that downloads rows only to count them, and replace it with an aggregation.

- [Joins](/docs/products/databases/tablesdb/joins)
- [Aggregations](/docs/products/databases/tablesdb/aggregations)
- [Query builder and request-body queries](/docs/products/databases/tablesdb/queries#query-builder)
- [Sign up for Appwrite Cloud](/sign-in)
