SQL SUM

The SUM() function is an aggregate function used to calculate the total of numeric values in a column.
👉 In simple terms:
SUM() adds all the values of a numeric column and returns the total.

Important Points:
1️. SUM() works only with numeric columns
2️. It ignores NULL values
3️. Often used with GROUP BY for reports
4️. Can be used with expressions like Quantity * Price

Syntax

SELECT SUM(column_name)
FROM table_name;

Calculate total quantity sold.

SELECT SUM(Quantity) AS TotalQuantity
FROM Orders;

Calculate total quantity for CustomerID = 101

SELECT SUM(Quantity) AS TotalQuantity
FROM Orders
WHERE CustomerID = 101;

Calculate total quantity per customer

SELECT CustomerID, SUM(Quantity) AS TotalQuantity
FROM Orders
GROUP BY CustomerID;

SUM with GROUP BY and HAVING

SELECT CustomerID, SUM(Quantity * Price) AS TotalAmount
FROM Orders
GROUP BY CustomerID
HAVING SUM(Quantity * Price) > 2000;


Simple Definition (Interview/Exam):
SUM() is an SQL aggregate function used to calculate the total sum of values in a numeric column.


Topics