SQL Sum Function | Sum a Column of Rows Matching a Criteria

SQL Sum is an inbuilt function in SQL Server. It returns the sum of a particular field/column in the rows matching criteria. Also, it can return the sum of all the fields of all rows in the table if you don’t specify any criteria. In this article, we will discuss the SQL Sum Function. Also, we will discuss a few examples of using it.

Syntax

SELECT SUM(column_name) FROM table_name WHERE condition;

  • column_name: The column to sum.
  • table_name: The table from which to sum.
  • condition: The condition to specify which rows to sum. The function will return the sum of fields of only those rows which match the WHERE condition.

Demo Table

For instance, consider the demo table to refer to all the queries in this article.

mysql> SELECT * FROM employees;
+----+--------+--------+------------+-------+
| id | name   | salary | experience | team  |
+----+--------+--------+------------+-------+
|  1 | David  |  20000 |          5 | Alpha |
|  2 | Monica |  25000 |          6 | Beta  |
|  3 | John   |  15000 |          3 | Beta  |
|  4 | Mary   |  18000 |          4 | Gamma |
|  5 | Ross   |  30000 |          8 | Alpha |
+----+--------+--------+------------+-------+

Examples

Let’s discuss a few examples of using the sum function in SQL.

Example 1: Sum of Fields of All Rows in Table

For instance, we want to find the sum of a field in the rows in the table. We can use the SQL Sum function without specifying any where condition. In this case, the function returns the total sum of all salaries in the table.

mysql> SELECT sum(salary) FROM employees;
+-------------+
| sum(salary) |
+-------------+
|      109000 |
+-------------+

Example 2: Sum of a Field in Rows Satisfying a Criteria

Similarly, you can specify a WHERE condition in the query. The Sum Function in SQL will sum a column of only those rows which satisfy the criteria. For instance, let’s sum the salaries of employees in Alpha Team.

mysql> SELECT sum(salary) FROM employees WHERE team = 'Alpha';
+-------------+
| sum(salary) |
+-------------+
|       46000 |
+-------------+

Example 3: Sum With Limit

However, even if you provide a limit in the query, the function will always return the full sum of a field in rows in the table. For example, let’s sum the salaries in all the rows in the table and specify a limit of 2. You should notice that the function will still return the full sum.

mysql> SELECT sum(salary) FROM employees LIMIT 2;
+-------------+
| sum(salary) |
+-------------+
|      109000 |
+-------------+

Conclusion

In conclusion, we discussed the SQL Sum Function in this article. You can read more about it on the Official Microsoft Documentation. Additionally, you can also learn more about SQL on Concatly.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *