SQL Sum
On this page
SQL SUM Function
The SUM() function returns the total of a numeric column. It is commonly used to calculate totals such as revenue, quantities, or balances.
Basic Syntax
SELECT SUM(column_name) FROM table_name;
Example: Total Revenue
SELECT SUM(price) AS total_revenue FROM orders;
Using SUM with WHERE
You can filter rows before calculating the total.
SELECT SUM(price) AS electronics_revenue FROM products WHERE category = 'Electronics';
Using SUM with GROUP BY
To calculate totals per category, country, or group, combine SUM with GROUP BY.
SELECT category,
SUM(price) AS total_sales
FROM products
GROUP BY category
ORDER BY total_sales DESC;
Using SUM with Expressions
You can calculate totals from computed values, such as price multiplied by quantity.
SELECT SUM(price * quantity) AS total_revenue FROM order_items;
NULL Behavior
SUM() ignores NULL values. If all values are NULL, the result will be NULL.
Common Mistakes
- Using SUM on non-numeric columns
- Forgetting GROUP BY when selecting additional columns
- Not handling NULL values when needed
Performance Note
Indexes can improve performance when SUM is combined with WHERE filters. However, aggregations on very large tables may still require scanning many rows.
Next Step
Continue with SQL AVG to calculate average values.