SQL SUM function

Here is a clear, practical guide to the SQL SUM() function, with examples, behavior notes, and best practices.


✅ What SUM() Does

SUM() returns the total of all non-NULL numeric values in a column.


✅ Basic Syntax

SELECT SUM(column_name) AS total_value
FROM table_name;

📌 Basic Examples

1. Total sales amount

SELECT SUM(amount) AS total_sales
FROM payments;

2. Total quantity sold

SELECT SUM(quantity) AS total_quantity
FROM order_items;

🔥 SUM with WHERE (filter rows first)

SELECT SUM(amount) AS june_sales
FROM payments
WHERE payment_date >= '2024-06-01'
AND payment_date < '2024-07-01';

🔥 SUM with GROUP BY

Compute totals per category, per customer, etc.

SELECT customer_id,
SUM(amount) AS total_spent
FROM payments
GROUP BY customer_id;

Another example:

SELECT department,
SUM(salary) AS payroll_cost
FROM employees
GROUP BY department;

🧠 Important Behavior Notes

SUM() ignores NULL values
✔ Returns NULL if all rows are NULL
✔ Works only on numeric data types
✔ Often combined with GROUP BY for summary reports


⚡ Real-World Use Cases

Monthly revenue

SELECT DATE_TRUNC('month', created_at) AS month,
SUM(amount) AS revenue
FROM orders
GROUP BY month
ORDER BY month;

Total stock value

SELECT SUM(price * quantity) AS inventory_value
FROM products;

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *