SQL Cookbook Lesson
How to sum values of a column in SQL
Learn how to sum values of a column in SQL with examples and explanations from SQLPad.
Problem
You have a table with numerical data and you need to calculate the sum of the values in a specific column.
Sample Data
Let's consider a table called Orders with the following data:
| OrderID | Product | Quantity |
|---|---|---|
| 1 | Apples | 5 |
| 2 | Oranges | 3 |
| 3 | Bananas | 7 |
| 4 | Apples | 2 |
| 5 | Oranges | 4 |
MySQL Solution
SELECT SUM(Quantity) AS TotalQuantity
FROM Orders;
PostgreSQL Solution
SELECT SUM(Quantity) AS TotalQuantity
FROM Orders;
Explanation
In both MySQL and PostgreSQL, the SUM() function is used to calculate the sum of a numeric column.
In the given solution, we are calculating the sum of the Quantity column from the Orders table. The AS keyword is used to rename the result column as TotalQuantity.
The result will be the sum of all the values in the Quantity column. For the given sample data, the result will be 21 (5+3+7+2+4).
This operation is often used in data analysis for aggregating data. It's important to note that the SUM() function will return NULL if the column contains no non-NULL values. If you want to return 0 in this case, you can use the COALESCE() function.