> For the complete documentation index, see [llms.txt](https://crystal-garage.gitbook.io/lustra-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://crystal-garage.gitbook.io/lustra-docs/querying/the-collection-object/filter-the-query-1/aggregation.md).

# Aggregation

Collections expose common SQL aggregate helpers.

## Count

`count` returns the number of matching rows:

```crystal
user_count = User.query.count
active_count = User.query.where(active: true).count
```

You can choose the return type:

```crystal
count = User.query.count(Int32)
```

When the query contains `limit`, `offset`, or `group_by`, Lustra wraps the query in a subquery so the count applies to the filtered result set.

## Min, Max, Avg, and Sum

```crystal
max_id = User.query.max("id", Int64)
min_id = User.query.min("id", Int64)
average_id = User.query.avg("id", Float64)
total_ids = User.query.sum("id")
```

`min`, `max`, and `avg` require the expected return type. `sum` currently returns `Float64`.

`sum` does not sanitize the `field` input, so pass trusted SQL fragments only.

```crystal
total_post_ids = Post.query.where(published: true).sum("id")
# => Float64
```

For typed aggregate output, use `agg`.

## Custom Aggregates

Use `agg` for custom aggregate expressions:

```crystal
median_age = User.query.agg("PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY age)", Float64)
max_updated_at = User.query.agg("MAX(updated_at)", Time)
```

`agg` returns one scalar value. `agg` should not be used with `group_by` unless your intent is to wrap grouped rows first and aggregate that result as a whole. For grouped results, use `select`, `group_by`, and `fetch`/`pluck`.

`agg` also handles paginated/limited queries by wrapping them in a subquery.

## Exists

`exists?` checks whether at least one row exists:

```crystal
if User.query.where(active: true).exists?
  puts "There are active users"
end
```

`exists?` always queries the database. It is useful when you want a direct existence check instead of loading records.

`count` and `exists?` have different costs: `count` asks for row cardinality, while `exists?` only checks that at least one row matches.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://crystal-garage.gitbook.io/lustra-docs/querying/the-collection-object/filter-the-query-1/aggregation.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
