Course

Aggregates - Sum

In this lesson, we will learn how to use the sum aggregate function in Prisma. We will use the method to calculate the sum of a column in a table. We will also learn how to filter the rows before calculating the sum.

Sum

Sum is the total of a column in a table. Let's say we wanted to get the total price of all the products in the products table. We can use the sum aggregate function to calculate the total price. I want to buy everything in the products table!

//
const total = await prisma.product.aggregate({
  _sum: {
    price: true,
  },
});

This gives us an object back with the sum of the price of all the products in the products table. The key of the object is _sum and the value is the sum of the price of all the products.

//
{
  _sum: {
    price: 622.96;
  }
}

Aggregates are similar to our queries. We can also filter the rows before calculating the sum. Let's say we only want to get the total price of the products in a specific category. We can use the where argument to filter the rows before calculating the sum.

Hint
monkey

//
const total = await prisma.product.aggregate({
  where: {
    category: 'electronics',
  },
  _sum: {
    price: true,
  },
});

0 Comments

"Please login to view comments"

glass-bbok

Join the Conversation!

Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.

Upgrade your account
tick-guideNext Lesson

Grouping Aggregations