The SQL SUM() Function
The SUM() function returns the total sum of a numeric column.
Example:
Return the sum of all Quantity fields in the products table:
SELECT SUM(Quantity)
FROM products ;
Syntax:
SELECT SUM (column_name)
FROM table_name
WHERE condition;
Demo Products table
This product table is used for examples:
Add a Where Clause
You can add a WHERE clause to specify conditions:
Example:
Return the number of orders made for the product with product_id 8:
SELECT SUM(Quantity)
FROM products
WHERE Product_id = 8 ;
Use an Alias
It give the summarized column a name by using the AS keyword .
Example:
Name the column "total":
SELECT SUM(Quantity) AS total
FROM products ;
SUM() With an Expression
The parameter inside the SUM() function can also be an expression..
Example:
Name the column "total":
SELECT SUM(Price* Quantity)
FROM products ;