Skip to content

Databases

Joins

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.

7 min read

Raw

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. You pass them to listRows() in the queries array, next to your filters, ordering, and pagination.

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

Joins and relationships

Relationships and joins both connect tables, but they solve different problems:

RelationshipsJoins
DefinedIn the table schema, as a relationship columnIn each query
Matches onThe relationship columnAny columns you choose, with =, <, >, and other operators
ResultRelated rows nested inside each rowFlat rows, with joined columns named alias.column
WritesCan create, update, and delete related rows togetherRead only
Best forData that belongs together, such as an album and its songsAd 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 IDColumns
customersname (string), country (string)
orderscustomerId (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:

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

Query.join() takes three arguments:

ArgumentDescription
Table IDThe table to join. It must be in the same database
AliasThe name joined columns are returned under, such as customer.name. Optional. Without an alias, the join is named after the table ID
ConditionsOne 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.

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:

Query.join('customers', '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:

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

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

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:

Query.join('customers', 'customer', [Query.on('customerId', '$id')]),
Query.equal('customer.country', ['DE']),
Query.orderDesc('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:

Query.join('orders', 'order', [Query.on('$id', 'customerId')]),
Query.join('payments', 'payment', [Query.on('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.

Pagination

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 as reading each table directly:

  • Tables: You can join a table if you have Read access to it, or if it has row security 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. The result includes the changes the transaction has staged for the table you list.

Limits

LimitValue
Joins per query8
Joined tablesSame database as the table you list, referenced by table ID
AliasUp 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
CachingResults with a join are not cached. A ttl on the request has no effect
Not supportedNatural joins and unions

Common errors:

ErrorCause
general_query_invalidA 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_foundThe joined table does not exist in this database, is disabled, or you cannot read it

Was this page helpful?

Share what worked or what we should fix. Once approved, our agents automatically apply suggested updates to the docs.