$ settings --editor

$ settings --general

$ save --settings

SQL for beginners

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_quantity column.
  • The value of total_quantity matches the sum of the quantity column in order_items.
Solution
SELECT
    SUM(quantity) AS total_quantity
FROM
    order_items;
Output will be displayed here