SQL SUM Function

SQL SUM Function with query example – Sum function returns sum of all values of a column or expression.

  1. SUM Function returns the sum value of an expression.
  2. SUM function returns NULL as return value when there are no rows exists in the table.
  3. 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.

TITLEPRICE
Historica98 
The Castle100 
The Castle150 
Animal Farm300 
Animal Farm120 

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];

Related Posts