MySQL SUM() Function
MySQL SUM() Function: Totaling Numeric Values Across Rows
The SUM() aggregate function adds together all non-NULL values in a numeric column or expression. You can summarize an entire table or combine SUM() with GROUP BY to total revenue per customer, hours per department, or stock per category.
Adding the optional DISTINCT modifier (SUM(DISTINCT col)) adds each unique value only once. For conditional counts, MySQL lets you sum boolean expressions like SUM(status = 'paid') directly.
Syntax
SUM([DISTINCT] expr)
DISTINCT: Optional keyword to sum only unique non-NULLvalues.expr: Numeric column or expression to total.
Practical Example
Suppose demo_orders tracks order totals (total_amount), optional discounts (discount_amount), and order_status. You can calculate gross sales, total discounts, and paid-order counts per customer in a single pass.
SELECT
customer_id,
SUM(total_amount) AS gross_sales,
COALESCE(SUM(discount_amount), 0.00) AS total_discounts,
SUM(order_status = 'paid') AS paid_orders
FROM demo_orders
GROUP BY customer_id
ORDER BY gross_sales DESC;
| customer_id | gross_sales | total_discounts | paid_orders |
|---|---|---|---|
| 201 | 840.50 | 45.00 | 3 |
| 202 | 310.00 | 0.00 | 1 |
| 203 | 125.00 | 0.00 | 0 |
Customer 202 had NULL in discount_amount on every order, so SUM(discount_amount) returned NULL and COALESCE(..., 0.00) converted it cleanly to 0.00.
Common Mistakes & NULL Behavior
- SUM() returns NULL on empty sets or all-NULL rows: Unlike
COUNT(*), which returns0,SUM(col)returnsNULLwhen zero rows match yourWHEREfilter or every matching row isNULL. Wrap totals withCOALESCE(SUM(col), 0)in dashboards and APIs. - NULLs are skipped inside mixed groups: If a group has
(100, NULL, 50),SUM()ignoresNULLand returns150. - Adding nullable columns row-by-row before summing: Writing
SUM(price + tax)returnsNULLfor any row wheretaxisNULL, dropping the wholepricefrom the sum! WriteSUM(price + COALESCE(tax, 0))instead.
Frequently Asked Questions
What data type does MySQL SUM() return?
For exact integers (INT, BIGINT) and DECIMAL columns, SUM() returns DECIMAL to prevent integer overflow. For FLOAT or DOUBLE, it returns DOUBLE.
How does SUM(status = 'shipped') work in MySQL?
In MySQL, boolean comparisons evaluate to 1 for true, 0 for false, and NULL if the column is NULL, so SUM(status = 'shipped') counts matching rows cleanly.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.