SQL SUM() Function
The SQL SUM()
function is an aggregate function used to calculate the sum of values in a specified column of a table. It is commonly used in conjunction with the SELECT
statement to perform calculations on numeric data. Here’s the basic syntax of the SUM()
function:
1 2 3 |
SELECT SUM(column_name) FROM table_name WHERE condition; |
column_name
: The name of the column for which you want to calculate the sum.table_name
: The name of the table from which you want to retrieve data.condition
: An optional condition to filter the rows before calculating the sum.
The SUM()
function adds up all the values in the specified column. If a condition is provided, it filters the rows before performing the sum calculation.
Here’s an example using a fictional table named sales
:
id | region | sale_amount |
---|---|---|
1 | North | 100.52 |
2 | South | 123.85 |
3 | South | 456.12 |
4 | North | 321.23 |
Now, let’s calculate the total sale amount:
1 2 |
SELECT SUM(sale_amount) FROM sales; |
This would produce the result:
+————————-+
| SUM(sale_amount)|
+————————–+
|1001.72
+—————————+
In this example, the SUM()
function adds up all the values in the sale_amount
column of the sales
table, resulting in a total sale amount of 526.50.
You can also use the SUM()
function with the GROUP BY
clause to calculate sums for each group based on a specific column, as demonstrated in the previous response.
Now, let’s calculate the total sales for each region:
1 2 3 |
SELECT region, SUM(sale_amount) FROM sale_amount GROUP BY region; |
This would produce the following result:
+——–+———————-+
| region | SUM(amount) |
+——–+———————-+
| North | 421.75|
| South | 579.97|
+——–+———————-+
This result shows the total sales for each region based on the data in the sales
table.