Skip to content

Databases

Aggregations

Count, sum, average, and group TablesDB rows on the server, filter groups with having, list distinct values, and aggregate across joined tables.

6 min read

Raw

Aggregations compute values over many rows on the server and return only the result: how many orders were paid, the revenue per country, the average rating of a product. Your app downloads a handful of numbers instead of every row.

Aggregations are queries. You pass them to listRows() in the queries array, and combine them with filters, grouping, and joins.

Use cases

  • Counters: Unread messages, open tickets, items in a cart
  • Dashboards: Revenue this month, orders per status, sign-ups per country
  • Leaderboards: Top customers by spend, top posts by votes
  • Filter options: The distinct countries or categories present in a table

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)

Aggregate a table

To count paid orders and add up their totals, list the orders table with a filter and two aggregations:

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.equal('status', ['paid']),
Query.count('*', 'orders'),
Query.sum('total', 'revenue')
]
});
const { orders, revenue } = result.rows[0];

Without grouping, the result is a single row holding one value per aggregation, and total is 1:

JSON
{
"total": 1,
"rows": [
{ "orders": 120, "revenue": 4830.5 }
]
}

Filters run before the aggregation, so only paid orders are counted and summed.

Aggregate functions

MethodReturns
Query.count(column, alias)The number of rows. Pass '*' to count every row, or a column to count rows where it is not null
Query.countDistinct(column, alias)The number of different values in a column
Query.sum(column, alias)The sum of a numeric column. An integer for integer columns, otherwise a float
Query.avg(column, alias)The average of a numeric column, as a float
Query.min(column, alias)The smallest value, with the column's type. Works on numbers, strings, and datetimes
Query.max(column, alias)The largest value, with the column's type. Works on numbers, strings, and datetimes

For statistics and bit flags, there are also Query.stddev(), Query.stddevPop(), Query.stddevSamp(), Query.variance(), Query.varPop(), Query.varSamp(), Query.bitAnd(), Query.bitOr(), and Query.bitXor(). Query.stddev() and Query.variance() return the population values, the same as Query.stddevPop() and Query.varPop(). The bit functions need an integer column.

Over an empty set of rows, counts return 0 and every other function returns null.

Name results with aliases

The alias, the second argument, is the key the result is returned under. Without one, Appwrite names the result after the function and column, such as sum_total, or count for Query.count().

To sort or filter on a result, give it an alias and use that alias. Sorting or filtering on a generated name is not supported. An alias:

  • Starts with a letter or _, and contains only letters, digits, and _
  • Is up to 63 characters long
  • Is unique among the aggregations in the query, and differs from the columns you group by

Group rows

Query.groupBy() splits rows into groups that share the same values, and runs each aggregation once per group. To get the number of orders and the revenue for each status:

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

Each 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 }
]
}

You can group by several columns, by system columns such as $createdAt, and by joined columns such as customer.country. When you group or aggregate, Query.select() and ordering can only use grouped columns and aggregation aliases.

Filter groups

Filters such as Query.equal() run on rows, before they are grouped. To filter on the results of an aggregation, wrap the conditions in Query.having(), which runs after grouping. For example, to keep only statuses with more than $1,000 in revenue:

Query.groupBy(['status']),
Query.sum('total', 'revenue'),
Query.having([
Query.greaterThan('revenue', 1000)
])

Conditions in Query.having() can use aggregation aliases and grouped columns. On an alias, you can use Query.equal(), Query.notEqual(), Query.lessThan(), Query.lessThanEqual(), Query.greaterThan(), Query.greaterThanEqual(), Query.between(), Query.notBetween(), Query.isNull(), and Query.isNotNull(). Compare an alias with numbers, or, for min and max, with values of the column's type. Several conditions in Query.having() must all match.

To match any of several conditions, group them with Query.or(), or with Query.and() to nest them further. Each group needs at least two conditions. For example, to keep statuses with more than 100 orders or more than $1,000 in revenue:

Query.groupBy(['status']),
Query.count('*', 'orders'),
Query.sum('total', 'revenue'),
Query.having([
Query.or([
Query.greaterThan('orders', 100),
Query.greaterThan('revenue', 1000)
])
])

On self-hosted Appwrite 2.7.5 and earlier, aliases can only be compared at the top level of Query.having(), not inside Query.and() or Query.or().

Sort and paginate

Sort groups by an alias or a grouped column, for example Query.orderDesc('revenue') to put the highest revenue first.

Use Query.limit() and Query.offset() to page through groups. Results are limited to 25 rows unless you set a limit. Cursor pagination is not supported with aggregations.

Distinct values

Query.distinct() removes duplicate rows from a selection. To list each country your customers are in once:

Query.select(['country']),
Query.distinct()

total is the number of distinct rows. To page through them with a cursor, sort by every selected column.

Aggregate across tables

Combine aggregations with joins to report across tables. To find the customers who spent more than $1,000, biggest spenders first, list the customers table, join their orders, and sum the order totals per customer. This example chains the queries with the query builder, which takes the same methods as the Query class:

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()
});

Grouping by $id as well as name keeps two customers with the same name apart. Joined columns keep their alias in the result, so grouping by order.status returns rows with an order.status key.

Result rows

Rows from aggregation, grouping, and distinct queries are not full rows from your table. They hold only the columns you group by or select, and the aggregation aliases. System columns such as $id, $createdAt, and $permissions are left out unless you group by or select them. The SDKs fill missing system columns with empty values, so read only the keys you asked for.

Permissions

Aggregations only include rows the caller can read. With row security, the same query can return different counts and sums for different users, and a server SDK with an API key sees every row.

Limits

  • Transactions: Aggregations and grouping cannot run inside a transaction, because they cannot read its uncommitted changes. Run them outside the transaction.
  • Single rows: getRow() does not accept aggregations. Use listRows(), or createQuery() for long query lists.
  • Totals: total counts up to 5,000 groups or rows.
  • Caching: Aggregation and distinct results can be cached with ttl, like other list responses.
  • Column types: sum, avg, and the other numeric functions need a numeric column. min and max do not work on boolean, JSON, spatial, vector, or array columns.

Common errors:

ErrorCause
general_query_invalidAn aggregation is malformed: an unsupported column type, an invalid or duplicate alias, a having condition on an unknown alias, a cursor, or a transactionId
database_query_out_of_rangeA result is too large for its type, such as a sum that overflows

Was this page helpful?

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