HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

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 ;

sum quantity table

Syntax:

SELECT SUM (column_name)
FROM table_name
WHERE condition;

Demo Products table


This product table is used for examples:


product table

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 ;

sum with where table

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 AS kwyword

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 ;

sum with expression

Demo product table for SUM with an Expression.
 demo table for sum with expression