Sum Function In Sql in SQL
The SUM function in SQL is an aggregate function used to calculate the total sum of numeric values in a column or expression over a set of rows.
? Syntax
SUM(expression)expression: A numeric column or an expression that evaluates to a number.
? What it does
Adds up all the values in the specified column or expression.
Ignores
NULLvalues.Returns a single numeric result.
? Example Usage
Suppose you have a table Sales with a column Amount:
SELECT SUM(Amount) AS TotalSalesFROM Sales;This returns the total sum of all sales amounts.
More Examples
Sum with
WHEREclause:
SELECT SUM(Amount) AS TotalSales2023FROM SalesWHERE YEAR(SaleDate) = 2023;Sum grouped by category:
SELECT Category, SUM(Amount) AS TotalCategorySalesFROM SalesGROUP BY Category;Notes
SUMworks only with numeric data types.Can be combined with
GROUP BYto get sums per group.Returns
NULLif there are no rows (no matching data).
If you'd like, I can show you how to use SUM in more complex queries or with specific SQL dialects!