Sikau

Prisma · Day 11 · about 30 min

Aggregations and groupBy

count, aggregate, groupBy and having.

Numbers for the dashboard

Dashboards need totals, averages and per-group numbers — computed in the database, not by loading every row into JavaScript. Prisma's aggregate and groupBy map to SQL's aggregate functions and GROUP BY.

aggregate and groupBy

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

console.log(await prisma.dish.aggregate({
  _count: true,
  _avg: { price: true },
  _min: { price: true },
  _max: { price: true },
  where: { veg: true },
}));

console.log(await prisma.order.groupBy({
  by: ["status"],
  _count: { _all: true },
  orderBy: { status: "asc" },
}));

console.log(await prisma.orderItem.groupBy({
  by: ["dishId"],
  _sum: { qty: true },
  having: { qty: { _sum: { gte: 2 } } },
  orderBy: [{ _sum: { qty: "desc" } }, { dishId: "asc" }],
}));

The rest of this lesson

  • groupBy in detailexplain
  • When to drop to SQLexplain
  • Where or having?predict
  • Pick the callmatch
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 15 lessons of Prisma