SQLite SUM() Function
The SUM() Function
SUM() adds all the values of a column together.
This example returns the sum of all the quantities in the OrderDetails table:
SUM With WHERE
This example returns the total quantity ordered of the product with ProductID 11:
SUM for Each Group
This example returns the total quantity of each order:
Example
SELECT OrderID, SUM(Quantity) AS TotalQuantity
FROM OrderDetails
GROUP BY OrderID;
Try it Yourself »
SUM of a Calculation
The value inside SUM() can be a calculation. This example finds the total value of all the orders, by multiplying the quantity with the price of each product. It uses a JOIN, which you will learn about later:
Example
SELECT SUM(Products.Price * OrderDetails.Quantity)
FROM OrderDetails
JOIN Products
ON OrderDetails.ProductID = Products.ProductID;
Try it Yourself »
SUM() and TOTAL()
SQLite also has a TOTAL() function. It works like SUM(), with two differences:
- When there are no values to add,
SUM()returns NULL, andTOTAL()returns 0.0 TOTAL()always returns a decimal number
There is no order with OrderID 1, so this example has no values to add:
Example
SELECT SUM(Quantity), TOTAL(Quantity),
typeof(TOTAL(Quantity))
FROM OrderDetails
WHERE OrderID = 1;
Try it Yourself »
The last column shows that the result of TOTAL() is a real (decimal) number, even when it looks like 0.