SQL SUM Function

The SQL SUM() function is an aggregate function used to calculate the total sum of a numeric column in a result set. It helps in getting the sum of all values in a column or the sum of values that meet specific criteria.

SUM() Function

The SUM() function can be used in queries to add up values of a numeric column.


-- Calculate the total sales
SELECT SUM(SalesAmount) AS TotalSales
FROM Sales;

-- Calculate the total salary of employees in a specific department
SELECT SUM(Salary) AS TotalSalaries
FROM Employees
WHERE DepartmentID = 3;

        

Syntax

The basic syntax for using the SUM() function is:


SELECT SUM(column_name) AS Alias
FROM table_name
WHERE condition;

        

Examples

Here are some examples of using the SUM() function:


-- Calculate the total amount of orders
SELECT SUM(OrderAmount) AS TotalOrderAmount
FROM Orders;

-- Calculate the total quantity of products sold
SELECT SUM(Quantity) AS TotalQuantity
FROM OrderDetails
WHERE ProductID = 10;