Working with Aggregations

1. Counting Records

const active = await prisma.user.count({ where: { active: true } });
FormReturns
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 } });
AspectDetail
Numeric onlyInt, Float, Decimal, BigInt
DecimalResult is Prisma.Decimal

3. Finding Average

AspectDetail
_avgReturns Float (or Decimal)
Null rowsExcluded from average

4. Getting Minimum Value

AspectDetail
_minWorks on Int, Float, Decimal, DateTime, String

5. Getting Maximum Value

AspectDetail
_maxSymmetric to _min

6. Grouping Records

await prisma.order.groupBy({
  by: ["status"],
  _sum: { total: true },
  _count: { _all: true }
});
OptionDetail
byGroup keys (array of fields)
whereFilter before grouping
havingFilter on aggregates
orderBySort grouped output

7. Filtering Groups

await prisma.order.groupBy({
  by: ["status"],
  _sum: { total: true },
  having: { total: { _sum: { gt: 1000 } } }
});
AspectDetail
HAVINGApplied after aggregation

8. Combining Multiple Aggregations

AggregatorCombinable
_count + _sumYes
_min + _max + _avgYes
Per-field selectionList fields under each

9. Aggregating Nested Relations

ApproachDetail
_count in includeCheap relation counts
Raw SQLRequired for SUM/AVG of relations

10. Using Distinct in Aggregations

UseDetail
groupBy + byEquivalent of distinct
Raw COUNT(DISTINCT)Use $queryRaw