---
layout: article
title: Aggregations
description: Count, sum, average, and group TablesDB rows on the server, filter groups with having, list distinct values, and aggregate across joined tables.
---

**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](/docs/products/databases/tablesdb/queries). You pass them to `listRows()` in the `queries` array, and combine them with filters, grouping, and [joins](/docs/products/databases/tablesdb/joins).

**Availability**

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

# 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 ID | Columns |
|----------|---------|
| `customers` | `name` (string), `country` (string) |
| `orders` | `customerId` (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:

```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.equal('status', ['paid']),
        Query.count('*', 'orders'),
        Query.sum('total', 'revenue')
    ]
});

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

const { orders, revenue } = result.rows[0];
```
```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.equal('status', ['paid']),
        Query.count('*', 'orders'),
        Query.sum('total', 'revenue'),
    ],
);
```
```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.equal("status", value: ["paid"]),
        Query.count("*", alias: "orders"),
        Query.sum("total", alias: "revenue")
    ]
)
```
```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.equal("status", listOf("paid")),
        Query.count("*", "orders"),
        Query.sum("total", "revenue")
    )
)
```
```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.equal('status', ['paid']),
        Query.count('*', 'orders'),
        Query.sum('total', 'revenue')
    ]
)
```
```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::equal('status', ['paid']),
        Query::count('*', 'orders'),
        Query::sum('total', 'revenue')
    ]
);
```
```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.equal('status', ['paid']),
        Query.count('*', 'orders'),
        Query.sum('total', 'revenue')
    ]
)
```
```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.Equal("status", []interface{}{"paid"}),
            query.Count("*", "orders"),
            query.Sum("total", "revenue"),
        }),
    )
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(result.Rows)
}
```
```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.Equal("status", new List<string> { "paid" }),
        Query.Count("*", "orders"),
        Query.Sum("total", "revenue")
    }
);
```
```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::equal("status", vec!["paid"]).to_string(),
                Query::count("*", "orders").to_string(),
                Query::sum("total", "revenue").to_string(),
            ]),
            None,
            None,
            None,
        )
        .await?;

    println!("{:?}", result);
    Ok(())
}
```
```http
{"method":"equal","attribute":"status","values":["paid"]}
{"method":"count","attribute":"*","values":["orders"]}
{"method":"sum","attribute":"total","values":["revenue"]}
```

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

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

```client-web
Query.groupBy(['status']),
Query.count('*', 'orders'),
Query.sum('total', 'revenue')
```
```server-nodejs
sdk.Query.groupBy(['status']),
sdk.Query.count('*', 'orders'),
sdk.Query.sum('total', 'revenue')
```
```client-flutter
Query.groupBy(['status']),
Query.count('*', 'orders'),
Query.sum('total', 'revenue'),
```
```client-apple
Query.groupBy(["status"]),
Query.count("*", alias: "orders"),
Query.sum("total", alias: "revenue")
```
```client-android-kotlin
Query.groupBy(listOf("status")),
Query.count("*", "orders"),
Query.sum("total", "revenue")
```
```server-python
Query.group_by(['status']),
Query.count('*', 'orders'),
Query.sum('total', 'revenue')
```
```server-php
Query::groupBy(['status']),
Query::count('*', 'orders'),
Query::sum('total', 'revenue')
```
```server-ruby
Query.group_by(['status']),
Query.count('*', 'orders'),
Query.sum('total', 'revenue')
```
```server-go
query.GroupBy([]interface{}{"status"}),
query.Count("*", "orders"),
query.Sum("total", "revenue"),
```
```server-dotnet
Query.GroupBy(new List<string> { "status" }),
Query.Count("*", "orders"),
Query.Sum("total", "revenue")
```
```server-rust
Query::group_by(vec!["status"]).to_string(),
Query::count("*", "orders").to_string(),
Query::sum("total", "revenue").to_string(),
```
```http
{"method":"groupBy","values":["status"]}
{"method":"count","attribute":"*","values":["orders"]}
{"method":"sum","attribute":"total","values":["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:

```client-web
Query.groupBy(['status']),
Query.sum('total', 'revenue'),
Query.having([
    Query.greaterThan('revenue', 1000)
])
```
```server-nodejs
sdk.Query.groupBy(['status']),
sdk.Query.sum('total', 'revenue'),
sdk.Query.having([
    sdk.Query.greaterThan('revenue', 1000)
])
```
```client-flutter
Query.groupBy(['status']),
Query.sum('total', 'revenue'),
Query.having([
    Query.greaterThan('revenue', 1000),
]),
```
```client-apple
Query.groupBy(["status"]),
Query.sum("total", alias: "revenue"),
Query.having([
    Query.greaterThan("revenue", value: 1000)
])
```
```client-android-kotlin
Query.groupBy(listOf("status")),
Query.sum("total", "revenue"),
Query.having(listOf(
    Query.greaterThan("revenue", 1000)
))
```
```server-python
Query.group_by(['status']),
Query.sum('total', 'revenue'),
Query.having([
    Query.greater_than('revenue', 1000)
])
```
```server-php
Query::groupBy(['status']),
Query::sum('total', 'revenue'),
Query::having([
    Query::greaterThan('revenue', 1000)
])
```
```server-ruby
Query.group_by(['status']),
Query.sum('total', 'revenue'),
Query.having([
    Query.greater_than('revenue', 1000)
])
```
```server-go
query.GroupBy([]interface{}{"status"}),
query.Sum("total", "revenue"),
query.Having([]string{
    query.GreaterThan("revenue", 1000),
}),
```
```server-dotnet
Query.GroupBy(new List<string> { "status" }),
Query.Sum("total", "revenue"),
Query.Having(new List<string>
{
    Query.GreaterThan("revenue", 1000)
})
```
```server-rust
Query::group_by(vec!["status"]).to_string(),
Query::sum("total", "revenue").to_string(),
Query::having(vec![
    Query::greater_than("revenue", 1000).to_string(),
]).to_string(),
```
```http
{"method":"groupBy","values":["status"]}
{"method":"sum","attribute":"total","values":["revenue"]}
{"method":"having","values":[{"method":"greaterThan","attribute":"revenue","values":[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:

```client-web
Query.groupBy(['status']),
Query.count('*', 'orders'),
Query.sum('total', 'revenue'),
Query.having([
    Query.or([
        Query.greaterThan('orders', 100),
        Query.greaterThan('revenue', 1000)
    ])
])
```
```server-nodejs
sdk.Query.groupBy(['status']),
sdk.Query.count('*', 'orders'),
sdk.Query.sum('total', 'revenue'),
sdk.Query.having([
    sdk.Query.or([
        sdk.Query.greaterThan('orders', 100),
        sdk.Query.greaterThan('revenue', 1000)
    ])
])
```
```client-flutter
Query.groupBy(['status']),
Query.count('*', 'orders'),
Query.sum('total', 'revenue'),
Query.having([
    Query.or([
        Query.greaterThan('orders', 100),
        Query.greaterThan('revenue', 1000),
    ]),
]),
```
```client-apple
Query.groupBy(["status"]),
Query.count("*", alias: "orders"),
Query.sum("total", alias: "revenue"),
Query.having([
    Query.or([
        Query.greaterThan("orders", value: 100),
        Query.greaterThan("revenue", value: 1000)
    ])
])
```
```client-android-kotlin
Query.groupBy(listOf("status")),
Query.count("*", "orders"),
Query.sum("total", "revenue"),
Query.having(listOf(
    Query.or(listOf(
        Query.greaterThan("orders", 100),
        Query.greaterThan("revenue", 1000)
    ))
))
```
```server-python
Query.group_by(['status']),
Query.count('*', 'orders'),
Query.sum('total', 'revenue'),
Query.having([
    Query.or_queries([
        Query.greater_than('orders', 100),
        Query.greater_than('revenue', 1000)
    ])
])
```
```server-php
Query::groupBy(['status']),
Query::count('*', 'orders'),
Query::sum('total', 'revenue'),
Query::having([
    Query::or([
        Query::greaterThan('orders', 100),
        Query::greaterThan('revenue', 1000)
    ])
])
```
```server-ruby
Query.group_by(['status']),
Query.count('*', 'orders'),
Query.sum('total', 'revenue'),
Query.having([
    Query.or([
        Query.greater_than('orders', 100),
        Query.greater_than('revenue', 1000)
    ])
])
```
```server-go
query.GroupBy([]interface{}{"status"}),
query.Count("*", "orders"),
query.Sum("total", "revenue"),
query.Having([]string{
    query.Or([]string{
        query.GreaterThan("orders", 100),
        query.GreaterThan("revenue", 1000),
    }),
}),
```
```server-dotnet
Query.GroupBy(new List<string> { "status" }),
Query.Count("*", "orders"),
Query.Sum("total", "revenue"),
Query.Having(new List<string>
{
    Query.Or(new List<string>
    {
        Query.GreaterThan("orders", 100),
        Query.GreaterThan("revenue", 1000)
    })
})
```
```server-rust
Query::group_by(vec!["status"]).to_string(),
Query::count("*", "orders").to_string(),
Query::sum("total", "revenue").to_string(),
Query::having(vec![
    Query::or(vec![
        Query::greater_than("orders", 100).to_string(),
        Query::greater_than("revenue", 1000).to_string(),
    ]).to_string(),
]).to_string(),
```
```http
{"method":"groupBy","values":["status"]}
{"method":"count","attribute":"*","values":["orders"]}
{"method":"sum","attribute":"total","values":["revenue"]}
{"method":"having","values":[{"method":"or","values":[{"method":"greaterThan","attribute":"orders","values":[100]},{"method":"greaterThan","attribute":"revenue","values":[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:

```client-web
Query.select(['country']),
Query.distinct()
```
```server-nodejs
sdk.Query.select(['country']),
sdk.Query.distinct()
```
```client-flutter
Query.select(['country']),
Query.distinct(),
```
```client-apple
Query.select(["country"]),
Query.distinct()
```
```client-android-kotlin
Query.select(listOf("country")),
Query.distinct()
```
```server-python
Query.select(['country']),
Query.distinct()
```
```server-php
Query::select(['country']),
Query::distinct()
```
```server-ruby
Query.select(['country']),
Query.distinct()
```
```server-go
query.Select([]interface{}{"country"}),
query.Distinct(),
```
```server-dotnet
Query.Select(new List<string> { "country" }),
Query.Distinct()
```
```server-rust
Query::select(vec!["country"]).to_string(),
Query::distinct().to_string(),
```
```http
{"method":"select","values":["country"]}
{"method":"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](/docs/products/databases/tablesdb/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](/docs/products/databases/tablesdb/queries#query-builder), which takes the same methods as the `Query` class:

```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?;
```
```http
{"method":"join","attribute":"orders","values":["order",{"method":"on","values":["$id","=","customerId"]}]}
{"method":"groupBy","values":["$id","name"]}
{"method":"sum","attribute":"order.total","values":["spent"]}
{"method":"having","values":[{"method":"greaterThan","attribute":"spent","values":[1000]}]}
{"method":"orderDesc","attribute":"spent"}
{"method":"limit","values":[10]}
```

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](/docs/products/databases/tablesdb/permissions#row-level), 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](/docs/products/databases/tablesdb/transactions), because they cannot read its uncommitted changes. Run them outside the transaction.
- **Single rows**: `getRow()` does not accept aggregations. Use `listRows()`, or [`createQuery()`](/docs/products/databases/tablesdb/queries#create-query) 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](/docs/products/databases/tablesdb/pagination#cache-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:

| Error | Cause |
|-------|-------|
| `general_query_invalid` | An 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_range` | A result is too large for its type, such as a sum that overflows |
