Working with Aggregations
1. Counting Records
const active = await prisma.user.count({ where: { active: true } });
| Form | Returns |
count(args) | Number |
count({ select: { id: true, email: true } }) | Per-field non-null counts |
2. Calculating Sum
const { _sum } = await prisma.order.aggregate({ _sum: { total: true } });
| Aspect | Detail |
| Numeric only | Int, Float, Decimal, BigInt |
| Decimal | Result is Prisma.Decimal |
3. Finding Average
| Aspect | Detail |
_avg | Returns Float (or Decimal) |
| Null rows | Excluded from average |
4. Getting Minimum Value
| Aspect | Detail |
_min | Works on Int, Float, Decimal, DateTime, String |
5. Getting Maximum Value
| Aspect | Detail |
_max | Symmetric to _min |
6. Grouping Records
await prisma.order.groupBy({
by: ["status"],
_sum: { total: true },
_count: { _all: true }
});
| Option | Detail |
by | Group keys (array of fields) |
where | Filter before grouping |
having | Filter on aggregates |
orderBy | Sort grouped output |
7. Filtering Groups
await prisma.order.groupBy({
by: ["status"],
_sum: { total: true },
having: { total: { _sum: { gt: 1000 } } }
});
| Aspect | Detail |
| HAVING | Applied after aggregation |
8. Combining Multiple Aggregations
| Aggregator | Combinable |
_count + _sum | Yes |
_min + _max + _avg | Yes |
| Per-field selection | List fields under each |
9. Aggregating Nested Relations
| Approach | Detail |
_count in include | Cheap relation counts |
| Raw SQL | Required for SUM/AVG of relations |
10. Using Distinct in Aggregations
| Use | Detail |
groupBy + by | Equivalent of distinct |
| Raw COUNT(DISTINCT) | Use $queryRaw |