---
layout: article
title: Joins
description: Combine rows from several tables in one TablesDB query with inner, left, right, full outer, and cross joins, then select, filter, and sort the joined columns.
---

A **join** reads rows from two or more tables in a single request, matching rows on columns you choose. List orders with their customers' names, or customers with each of their orders, without fetching related rows one request at a time.

Joins are [queries](/docs/products/databases/tablesdb/queries). You pass them to `listRows()` in the `queries` array, next to your filters, ordering, and pagination.

**Availability**

Joins work in TablesDB on SQL databases. They are not available in DocumentsDB, or on self-hosted installations that use MongoDB. On self-hosted Appwrite, joins need version 2.6.0 or later.

# Use cases

- **Show related data in lists**: Orders with the customer's name, posts with the author's avatar
- **Filter by another table**: Orders from customers in one country, tasks assigned to members of one team
- **Sort by another table**: Products ordered by their supplier's rating
- **Report across tables**: Revenue per customer, when combined with [aggregations](/docs/products/databases/tablesdb/aggregations)

# Joins and relationships

[Relationships](/docs/products/databases/tablesdb/relationships) and joins both connect tables, but they solve different problems:

| | Relationships | Joins |
|---|---|---|
| Defined | In the table schema, as a relationship column | In each query |
| Matches on | The relationship column | Any columns you choose, with `=`, `<`, `>`, and other operators |
| Result | Related rows nested inside each row | Flat rows, with joined columns named `alias.column` |
| Writes | Can create, update, and delete related rows together | Read only |
| Best for | Data that belongs together, such as an album and its songs | Ad hoc reads, filters, sorting, and reports across tables |

You can use both in one project.

# Example tables

The examples on this page use two tables:

| Table ID | Columns |
|----------|---------|
| `customers` | `name` (string), `country` (string) |
| `orders` | `customerId` (string, the `$id` of a customer), `total` (float), `status` (string) |

# Join two tables

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`:

```client-web
import { Client, Query, TablesDB } from "appwrite";

const client = new Client()
    .setEndpoint('https://<REGION>.cloud.appwrite.io/v1')
    .setProject('<PROJECT_ID>');

const tablesDB = new TablesDB(client);

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'])
    ]
});

for (const order of result.rows) {
    console.log(order.$id, order.total, order['customer.name']);
}
```
```server-nodejs
const sdk = require('node-appwrite');

const client = new sdk.Client()
    .setEndpoint('https://<REGION>.cloud.appwrite.io/v1')
    .setProject('<PROJECT_ID>')
    .setKey('<API_KEY>');

const tablesDB = new sdk.TablesDB(client);

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'])
    ]
});

for (const order of result.rows) {
    console.log(order.$id, order.total, order['customer.name']);
}
```
```client-flutter
import 'package:appwrite/appwrite.dart';

final client = Client()
    .setEndpoint('https://<REGION>.cloud.appwrite.io/v1')
    .setProject('<PROJECT_ID>');

final tablesDB = TablesDB(client);

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
import Appwrite

let client = Client()
    .setEndpoint("https://<REGION>.cloud.appwrite.io/v1")
    .setProject("<PROJECT_ID>")

let tablesDB = TablesDB(client)

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
import io.appwrite.Client
import io.appwrite.Query
import io.appwrite.services.TablesDB

val client = Client(context)
    .setEndpoint("https://<REGION>.cloud.appwrite.io/v1")
    .setProject("<PROJECT_ID>")

val tablesDB = TablesDB(client)

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
from appwrite.client import Client
from appwrite.query import Query
from appwrite.services.tables_db import TablesDB

client = Client()
client.set_endpoint('https://<REGION>.cloud.appwrite.io/v1')
client.set_project('<PROJECT_ID>')
client.set_key('<API_KEY>')

tables_db = TablesDB(client)

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
<?php

use Appwrite\Client;
use Appwrite\Query;
use Appwrite\Services\TablesDB;

$client = (new Client())
    ->setEndpoint('https://<REGION>.cloud.appwrite.io/v1')
    ->setProject('<PROJECT_ID>')
    ->setKey('<API_KEY>');

$tablesDB = new TablesDB($client);

$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
require 'appwrite'

include Appwrite

client = Client.new
    .set_endpoint('https://<REGION>.cloud.appwrite.io/v1')
    .set_project('<PROJECT_ID>')
    .set_key('<API_KEY>')

tables_db = TablesDB.new(client)

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
package main

import (
    "fmt"
    "log"

    "github.com/appwrite/sdk-for-go/v7/appwrite"
    "github.com/appwrite/sdk-for-go/v7/query"
)

func main() {
    client := appwrite.NewClient(
        appwrite.WithEndpoint("https://<REGION>.cloud.appwrite.io/v1"),
        appwrite.WithProject("<PROJECT_ID>"),
        appwrite.WithKey("<API_KEY>"),
    )

    tablesDB := appwrite.NewTablesDB(client)

    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"}),
        }),
    )
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(result.Total)
}
```
```server-dotnet
using Appwrite;
using Appwrite.Models;
using Appwrite.Services;

Client client = new Client()
    .SetEndpoint("https://<REGION>.cloud.appwrite.io/v1")
    .SetProject("<PROJECT_ID>")
    .SetKey("<API_KEY>");

TablesDB tablesDB = new TablesDB(client);

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
use appwrite::query::Query;
use appwrite::services::TablesDB;
use appwrite::Client;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new()
        .set_endpoint("https://<REGION>.cloud.appwrite.io/v1")
        .set_project("<PROJECT_ID>")
        .set_key("<API_KEY>");

    let tables_db = TablesDB::new(&client);

    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?;

    println!("{:?}", result);
    Ok(())
}
```
```http
{"method":"join","attribute":"customers","values":["customer",{"method":"on","values":["customerId","=","$id"]}]}
{"method":"select","values":["$id","total","customer.name"]}
```

`Query.join()` takes three arguments:

| Argument | Description |
|----------|-------------|
| Table ID | The table to join. It must be in the same database |
| Alias | The name joined columns are returned under, such as `customer.name`. Optional. Without an alias, the join is named after the table ID |
| Conditions | One or more `Query.on()` conditions that decide which rows match |

`Query.on(left, right, operator)` compares a column of the table you list, on the left, with a column of the joined table, on the right. The operator defaults to `=`, and can also be `!=`, `<>`, `<`, `>`, `<=`, or `>=`. The system columns `$id`, `$sequence`, `$createdAt`, and `$updatedAt` work on either side. Pass several conditions to match on all of them.

Pass an alias when the table ID can't be used as one, for example when it contains a `.`, and when you join the same table more than once. Without one, the request fails with `general_query_invalid`.

**Index the columns you join on**

Add an [index](/docs/products/databases/tablesdb/tables#indexes) to columns you join on often, such as `customerId`, so the database can find matching rows without scanning the whole table.

## Join on one condition

When a join has a single condition, you can pass its columns to the join method directly instead of a list of `Query.on()` conditions. The arguments are the table ID, the left column, the right column, the operator, and the alias. This query is the same join as the one above:

```client-web
Query.join('customers', 'customerId', '$id', '=', 'customer')
```
```server-nodejs
sdk.Query.join('customers', 'customerId', '$id', '=', 'customer')
```
```client-flutter
Query.join('customers', 'customerId', '\$id', '=', 'customer')
```
```client-apple
Query.join("customers", left: "customerId", right: "$id", alias: "customer")
```
```client-android-kotlin
Query.join("customers", left = "customerId", right = "\$id", alias = "customer")
```
```server-python
Query.join('customers', left='customerId', right='$id', alias='customer')
```
```server-php
Query::join('customers', 'customerId', '$id', alias: 'customer')
```
```server-ruby
Query.join('customers', 'customerId', '$id', '=', 'customer')
```
```server-go
query.Join("customers", "customerId", "$id", "=", "customer")
```
```server-dotnet
Query.Join("customers", left: "customerId", right: "$id", alias: "customer")
```
```server-rust
Query::join("customers", "customerId", "$id", "=", "customer").to_string()
```
```http
{"method":"join","attribute":"customers","values":["customerId","=","$id","customer"]}
```

The operator and alias are optional, except in Go and Rust, where you pass every argument. Use an empty string for no alias. The same form works for `leftJoin()`, `rightJoin()`, and `fullOuterJoin()`. In Go and Rust, the join methods that take a list of `Query.on()` conditions end in `On`, such as `query.JoinOn()` and `Query::join_on()`.

# Join types

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

| Method | Returns |
|--------|---------|
| `Query.join()` | Only rows that have a match in both tables |
| `Query.leftJoin()` | Every row of the table you list. Joined columns are `null` when nothing matches |
| `Query.rightJoin()` | Every row of the joined table. Columns of the table you list are empty when nothing matches |
| `Query.fullOuterJoin()` | Every row of both tables, matched where possible |
| `Query.crossJoin()` | Every combination of rows from both tables. Takes no conditions |

For example, to list every customer with their orders, including customers who have not ordered yet:

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

A customer with three orders appears in three rows, one per order. A customer with no orders appears once, with `order.$id` and `order.total` set to `null`. The list's `total` counts the joined rows, not the customers.

# Select, filter, and sort joined columns

Joined columns are always named `alias.column`, both in queries and in the rows you get back.

- **Select**: Without `Query.select()`, each row has every column of the table you list, plus `alias.$id` and every column of each joined table. Select `alias.column` to pick specific columns, or `alias.*` for the whole joined row including its system columns. Selecting a joined column without its alias returns an error.
- **Filter**: Use `alias.column` in any filter, including inside `Query.and()` and `Query.or()`.
- **Sort**: Use `alias.column` in `Query.orderAsc()` and `Query.orderDesc()`.

For example, to list orders from customers in Germany, largest first:

```client-web
Query.join('customers', 'customer', [Query.on('customerId', '$id')]),
Query.equal('customer.country', ['DE']),
Query.orderDesc('total')
```
```server-nodejs
sdk.Query.join('customers', 'customer', [sdk.Query.on('customerId', '$id')]),
sdk.Query.equal('customer.country', ['DE']),
sdk.Query.orderDesc('total')
```
```client-flutter
Query.join('customers', 'customer', [Query.on('customerId', '\$id')]),
Query.equal('customer.country', ['DE']),
Query.orderDesc('total'),
```
```client-apple
Query.join("customers", alias: "customer", on: [Query.on("customerId", "$id")]),
Query.equal("customer.country", value: ["DE"]),
Query.orderDesc("total")
```
```client-android-kotlin
Query.join("customers", "customer", listOf(Query.on("customerId", "\$id"))),
Query.equal("customer.country", listOf("DE")),
Query.orderDesc("total")
```
```server-python
Query.join('customers', 'customer', [Query.on('customerId', '$id')]),
Query.equal('customer.country', ['DE']),
Query.order_desc('total')
```
```server-php
Query::join('customers', 'customer', [Query::on('customerId', '$id')]),
Query::equal('customer.country', ['DE']),
Query::orderDesc('total')
```
```server-ruby
Query.join('customers', 'customer', [Query.on('customerId', '$id')]),
Query.equal('customer.country', ['DE']),
Query.order_desc('total')
```
```server-go
query.JoinOn("customers", "customer", []string{query.On("customerId", "$id", "=")}),
query.Equal("customer.country", []interface{}{"DE"}),
query.OrderDesc("total"),
```
```server-dotnet
Query.Join("customers", "customer", new List<string> { Query.On("customerId", "$id") }),
Query.Equal("customer.country", new List<string> { "DE" }),
Query.OrderDesc("total")
```
```server-rust
Query::join_on("customers", "customer", vec![Query::on("customerId", "$id", "=").to_string()]).to_string(),
Query::equal("customer.country", vec!["DE"]).to_string(),
Query::order_desc("total").to_string(),
```
```http
{"method":"join","attribute":"customers","values":["customer",{"method":"on","values":["customerId","=","$id"]}]}
{"method":"equal","attribute":"customer.country","values":["DE"]}
{"method":"orderDesc","attribute":"total"}
```

# Join more than two tables

Add one join per table, up to 8 in a query. A later join can match on an earlier one by its alias. For example, with a `payments` table whose `orderId` column holds an order's `$id`:

```client-web
Query.join('orders', 'order', [Query.on('$id', 'customerId')]),
Query.join('payments', 'payment', [Query.on('order.$id', 'orderId')])
```
```server-nodejs
sdk.Query.join('orders', 'order', [sdk.Query.on('$id', 'customerId')]),
sdk.Query.join('payments', 'payment', [sdk.Query.on('order.$id', 'orderId')])
```
```client-flutter
Query.join('orders', 'order', [Query.on('\$id', 'customerId')]),
Query.join('payments', 'payment', [Query.on('order.\$id', 'orderId')]),
```
```client-apple
Query.join("orders", alias: "order", on: [Query.on("$id", "customerId")]),
Query.join("payments", alias: "payment", on: [Query.on("order.$id", "orderId")])
```
```client-android-kotlin
Query.join("orders", "order", listOf(Query.on("\$id", "customerId"))),
Query.join("payments", "payment", listOf(Query.on("order.\$id", "orderId")))
```
```server-python
Query.join('orders', 'order', [Query.on('$id', 'customerId')]),
Query.join('payments', 'payment', [Query.on('order.$id', 'orderId')])
```
```server-php
Query::join('orders', 'order', [Query::on('$id', 'customerId')]),
Query::join('payments', 'payment', [Query::on('order.$id', 'orderId')])
```
```server-ruby
Query.join('orders', 'order', [Query.on('$id', 'customerId')]),
Query.join('payments', 'payment', [Query.on('order.$id', 'orderId')])
```
```server-go
query.JoinOn("orders", "order", []string{query.On("$id", "customerId", "=")}),
query.JoinOn("payments", "payment", []string{query.On("order.$id", "orderId", "=")}),
```
```server-dotnet
Query.Join("orders", "order", new List<string> { Query.On("$id", "customerId") }),
Query.Join("payments", "payment", new List<string> { Query.On("order.$id", "orderId") })
```
```server-rust
Query::join_on("orders", "order", vec![Query::on("$id", "customerId", "=").to_string()]).to_string(),
Query::join_on("payments", "payment", vec![Query::on("order.$id", "orderId", "=").to_string()]).to_string(),
```
```http
{"method":"join","attribute":"orders","values":["order",{"method":"on","values":["$id","=","customerId"]}]}
{"method":"join","attribute":"payments","values":["payment",{"method":"on","values":["order.$id","=","orderId"]}]}
```

You can join the same table more than once under different aliases, and join a table to itself, for example to match each employee with their manager in one `employees` table.

**Build joins with the query builder**

Every join method is also on the [query builder](/docs/products/databases/tablesdb/queries#query-builder), so you can chain a join with the rest of a query: `Query.builder().join(...).equal(...).build()`. When a query list gets too long for a URL, send it in the request body with [`createQuery()`](/docs/products/databases/tablesdb/queries#create-query), which accepts joins too.

# Pagination

[Pagination](/docs/products/databases/tablesdb/pagination) works with joins. Use `Query.limit()` and `Query.offset()`, or cursor pagination with the `$id` of a row from the table you list. Results are limited to 25 rows unless you set a limit.

# Get one row

`getRow()` also accepts joins, to read one row together with its related data. With an inner or right join, the request returns a `404` error when the row has no match. When several joined rows match, you get the first.

# Permissions

Joins follow the same [permissions](/docs/products/databases/tablesdb/permissions) as reading each table directly:

- **Tables**: You can join a table if you have **Read** access to it, or if it has [row security](/docs/products/databases/tablesdb/permissions#row-level) enabled. Otherwise, the request fails with `table_not_found`, the same error as for a table that does not exist.
- **Rows**: Joined rows you cannot read never match. With `Query.join()`, a row whose only matches are hidden from you is left out. With `Query.leftJoin()`, it is kept, with `null` joined columns. With right, full outer, and cross joins, rows you cannot read are left out.

API keys with the `rows.read` scope can join every table and read every row.

# Transactions

You can read with joins inside a [transaction](/docs/products/databases/tablesdb/transactions). The result includes the changes the transaction has staged for the table you list.

# Limits

| Limit | Value |
|-------|-------|
| Joins per query | 8 |
| Joined tables | Same database as the table you list, referenced by table ID |
| Alias | Up to 63 letters, digits, `_`, and `-`, starting with a letter, digit, or `_`, and unique in the query. Cannot be `table_main`, the name of a relationship column, or the ID of the table you list, unless you join that table to itself |
| Caching | Results with a join are not cached. A `ttl` on the request has no effect |
| Not supported | Natural joins and unions |

Common errors:

| Error | Cause |
|-------|-------|
| `general_query_invalid` | A join is malformed: an unsupported operator, a joined column selected without its alias, more than 8 joins, an invalid alias, or a missing alias where the table ID can't be used |
| `table_not_found` | The joined table does not exist in this database, is disabled, or you cannot read it |
