How to Sum Values of a Column in SQL?
Database:
Operators:
Problem:
You’d like to compute the sum the values of a column.
Example 1: Computing the Total Sum for a Column
Our database has a table named game with the following columns: id, player, and score. You want to find the total score obtained by all players.
| id | player | score |
|---|---|---|
| 1 | John | 134 |
| 2 | Tom | 146 |
| 3 | Lucy | 20 |
| 4 | Tom | 118 |
| 5 | Tom | 102 |
| 6 | Lucy | 90 |
| 7 | Lucy | 34 |
| 8 | John | 122 |
Solution:
SELECT SUM(score) as sum_score FROM game;
Here’s the result:
| sum_score |
|---|
| 766 |
Discussion:
The aggregate function SUM is ideal for computing the sum of a column’s values. This function is used in a SELECT statement and takes the name of the column whose values you want to sum.
If you do not specify any other columns in the SELECT statement, then the sum will be calculated for all records in the table. In our example, we only select the sum and no other columns. Therefore, the query in our example returns the sum all scores (766).
Example 2: Computing the Sum for Each Group
We can also compute the total score earned by each player by using a GROUP BY clause and selecting each player’s name from the table, alongside the sum:
Solution:
SELECT player, SUM(score) as sum_score FROM game GROUP BY player;
This query returns the total score for each player:
| player | score |
|---|---|
| John | 256 |
| Tom | 366 |
| Lucy | 144 |