Best SQL SUM() Function in 2023

The SQL SUM() Function

What is the SUM() function in sql?

The SQL SUM() function is an aggregate function used to calculate the sum of values in a specified column. It is often used with numeric data types to find the total of all values in a particular column or a set of rows that meet certain criteria in a SQL database.

To determine the sum or total of the values in a given column, use the SQL SUM() function. It is frequently used to carry out operations like figuring out the entire sales amount, adding up numerical data, and carrying out other kinds of aggregation.

The basic syntax of the SQL SUM() function is as follows:

SELECT SUM(column_name)
FROM table_name
WHERE condition;

Example 1: Sum of Numeric Values in a Column
SQL> SELECT SUM(Amount) AS TotalSales
FROM Sales;

SUM(Amount) calculates the sum of all values in the “Amount” column.
AS TotalSales provides an alias for the result column for clarity.

Example 2: Sum with a Conditional WHERE Clause
SQL> SELECT SUM(Amount) AS TotalProductSales
FROM Sales
WHERE ProductID = 123;

SUM(Amount) calculates the sum of “Amount” values for rows where the “ProductID” is 123.

Example 3: Sum with Grouping
SQL> SELECT Category, SUM(Amount) AS TotalSalesPerCategory
FROM Products
GROUP BY Category;

GROUP BY Category groups the products by their category.
SUM(Amount) calculates the sum of “Amount” values for each product category.

Example 4: Sum with Joining Tables
SQL> SELECT Products.ProductName, SUM(Sales.Amount) AS TotalSalesPerProduct
FROM Products
INNER JOIN Sales ON Products.ProductID = Sales.ProductID
GROUP BY Products.ProductName;

INNER JOIN combines the “Products” and “Sales” tables based on the common “ProductID” column.
SUM(Sales.Amount) calculates the sum of sales amounts for each product.

The above examples shown you how to execute various forms of summation and aggregation operations on numerical data in your database tables using the SQL SUM() function. A useful tool for determining totals and conducting data analysis is the SUM function.

Leave a Comment