Let’s say we have a database table named orders with columns: id, name, and cost.
In our application we might want to find the total cost of all orders, this is a perfect use case for the SUM aggregate function. Here’s what our query would look like:
SELECT SUM(cost) as total_cost FROM orders
And here’s the result:
But we can take this even further, what if we wanted to total up each persons orders? We can alter our select to include the order name and then grouping on it. So our new query looks like this:
SELECT name, SUM(cost) as total_cost FROM orders GROUP BY name;
And this is our result: