Quick Reach
The Sum function
- The SQL sum() function is used to calculate the sum of the given numeric column.
- You can use the sum function in the simple select statement with the where clause.
- You can also use the sum aggregate function with the group by clause to return aggregated group values.
See Sum example online
Syntax of using sum in SQL
The general syntax of using the Sum function is:
Select sum(numeric_column_name) from table_name
Where col_name = value
Examples of using SQL sum function
Following examples show how to use the Sum function. In our examples, we will use the tbl_emp_salary_paid table that stores employees salaries. That means salaries paid every month to employees are stored in this table.
The data in the table is shown along with each example to make it easier to understand. Simply click on demo link.
Example of using Sum SQL in simple select statement
In this example, we will calculate the total salaries paid to all employees. We will use the Sum function in the simple select statement and query the tbl_emp_salary_paid table.
The SQL select with Sum query:
1
|
select sum(emp_sal_paid) as Total_paid_salaries from tbl_emp_salary_paid
|
Demo Table with SQL select sum
SUM with Group by example
This query will return the total salary paid to each employee by using the Sum function which is used with the group by clause.
The SUM – group by query:
1
2
3
|
select emp_name,sum(emp_sal_paid)as total_paid from tbl_emp_salary_paid
group by emp_name
|
Demo Table with SUM SQL and group by
As you can see in above graphic, two queries are shown. The first query will fetch all records from the table. The other query is using the Sum aggregate function of SQL with the group by clause to retrieve each employee total salary.
Leave A Comment?