Published on

December 5, 2022

Understanding the SQL SUM() Function in SQL Server

In SQL Server, there are various mathematical calculations that we often need to perform in our day-to-day business requirements. One such calculation is getting the sum of values stored in a numeric column. Luckily, SQL Server provides us with the SUM() function, which is an aggregate function used to perform calculations on a set of values and return a single value as the output.

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

SUM([ALL | DISTINCT] expression)

The ALL argument, which is the default argument, considers all values to calculate the result. On the other hand, the DISTINCT argument only considers unique values and ignores duplicates.

Let’s consider a scenario where we have a table named “Sales” with columns such as ProductName, Price, Quantity, InvoiceMonth, and City. We can use the SUM() function to perform various calculations on this table.

For example, to get the total sales and total units sold, we can use the following query:

SELECT SUM(Price) AS [Total Sales], SUM(Quantity) AS [Total Units Sold] FROM Sales;

If we want to group the data by month and get the total sales for each month, we can use the GROUP BY statement:

SELECT InvoiceMonth, SUM(Price) AS [Total Sales] FROM Sales GROUP BY InvoiceMonth;

We can also use the SUM() function with other aggregate functions like MIN, MAX, and AVG. For example, to get the minimum, maximum, average, and total sales, we can use the following query:

SELECT MIN(Price) AS [Minimum Invoice], MAX(Price) AS [Maximum Invoice], AVG(Price) AS [Average Sales], SUM(Price) AS [Total Sales] FROM Sales;

The SUM() function can also be used with expressions. For instance, if we want to calculate the total sales value for each product by multiplying the price and quantity, we can use the following query:

SELECT ProductName, SUM(Price * Quantity) AS [Total Sales] FROM Sales GROUP BY ProductName;

It’s important to note that the SUM() function ignores NULL values in the columns during its calculation. For example, if we have NULL values in the Price and Quantity columns, the SUM() function will still return the sum of the non-NULL values.

In conclusion, the SQL SUM() function is a powerful tool for performing calculations on numeric columns in SQL Server. It can be used with various SQL clauses like GROUP BY, HAVING, and ORDER BY to get the desired results. By leveraging the SUM() function, we can easily obtain the sum of values and perform other mathematical calculations in our SQL queries.

Give the SQL SUM() function a try in your own SQL Server projects and see how it simplifies your calculations. If you have any feedback or questions, please let us know in the comments section.

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.