Summing values with SUM #
SUM is another aggregate function. Instead of counting rows, it adds up the values in a numeric column across all the rows.
SELECT
SUM(column_name) AS total
FROM
table_name;
SUM(column_name) adds together every value in column_name. Rows where the column is NULL are ignored rather than treated as zero.
Example #
SELECT
SUM(age) AS total_age
FROM
customers;
Result:
+-----------+
| total_age |
+-----------+
| 716 |
+-----------+
This adds up the age column across every row in customers into a single number.
Exercise #
The order_items table has one row per product in an order, with a quantity column showing how many units were bought. Write a command that sums up the quantity column across every row in order_items.
- The result has a
total_quantitycolumn. - The value of
total_quantitymatches the sum of thequantitycolumn inorder_items.
Solution
SELECT
SUM(quantity) AS total_quantity
FROM
order_items;
Basic Data Retrieval
Filtering Data
Aggregating Data
Joining Tables
Creating and Managing Tables
Transactions and Data Integrity