SQL SUM Function with query example – Sum function returns sum of all values of a column or expression.
- SUM Function returns the sum value of an expression.
- SUM function returns NULL as return value when there are no rows exists in the table.
- The Distinct keyword can be used in SUM function to calculate the distinct values.
SQL SUM function Syntax:
SELECT SUM(Expression)
FROM [Table_Name]
Where [CONDITION];
SUM function example
In below BOOKS table, we can find the sum of prices for all books.
TITLE | PRICE | |
---|---|---|
Historica | 98 | |
The Castle | 100 | |
The Castle | 150 | |
Animal Farm | 300 | |
Animal Farm | 120 |
Query :
SELECT SUM(PRICE) FROM BOOKS;
Output:
Sum(price)
768
SQL SUM function by using Group By
Syntax:
SELECT [COLUMN1],[COLUMN2], ……SUM[COLUMN_N]
FROM [TABLE_NAME] [WHERE CONDITION]
GROUP BY COLUMN1,COLUMN2……[COLUMNN];