SQL Server SUM() Function

The SUM() function in SQL Server calculates the sum (total) of numeric values in a column. It's a fundamental aggregate function, used for summarizing numerical data from multiple rows.



SUM(): Definition and Usage

SUM() is incredibly useful for getting totals from your data. It efficiently adds up all the non-null numeric values in the specified column. NULL values are automatically skipped in the summation, ensuring you get a clean total of only the valid numeric data. This function is frequently used for tasks such as calculating total sales, summing quantities, or aggregating other numeric values across a table or a subset of a table.

Syntax

Syntax

SUM(expression)
      

Parameter Values

Parameter Description
expression A numeric column name or a formula that results in a numeric value. This is required.

Example

Calculating the Total Quantity

This example calculates the total 'Quantity' from the 'OrderDetails' table (assuming a table named 'OrderDetails' exists with a 'Quantity' column). Rows where 'Quantity' is NULL are not included in the sum.

Syntax

SELECT SUM(Quantity) AS TotalItemsOrdered FROM OrderDetails;
      
Output

TotalItemsOrdered
-----------------
(The sum of all non-null Quantity values from the OrderDetails table will be shown here.)
      

**Note:** The example output will vary depending on the data in your `OrderDetails` table. If the table is empty or if all the `Quantity` values are `NULL`, then the output will be 0.