- SQL Basics
- SQL Introduction
- SQL Syntax
- SQL Sample Database
- SQL SELECT
- SQL WHERE
- SQL ORDER BY
- SQL DISTINCT
- SQL LIMIT
- SQL FETCH
- SQL AND
- SQL OR
- SQL BETWEEN
- SQL IN
- SQL LIKE
- SQL IS NULL
- SQL Comparison Operators
- SQL Logical Operators
- SQL Alias
- SQL CASE
- Joins and Subqueries
- SQL INNER JOIN
- SQL LEFT JOIN
- SQL RIGHT JOIN
- SQL FULL OUTER JOIN
- SQL SELF JOIN
- SQL CROSS JOIN
- SQL Subquery
- SQL Correlated Subquery
- SQL UNION
- SQL INTERSECT
- SQL EXCEPT
- Aggregate Functions
- SQL AVG
- SQL COUNT
- SQL MAX
- SQL MIN
- SQL SUM
- SQL GROUP BY
- SQL HAVING
- SQL ROLLUP
- SQL CUBE
- SQL GROUPING SETS
- Database Management
- SQL CREATE DATABASE
- SQL ALTER DATABASE
- SQL DROP DATABASE
- SQL BACKUP DATABASE
- SQL SHOW DATABASES
- SQL SELECT DATABASE
- Table Management
- SQL CREATE TABLE
- SQL ALTER TABLE
- SQL ADD COLUMN
- SQL DROP COLUMN
- SQL DROP TABLE
- SQL TRUNCATE TABLE
- SQL SHOW TABLES
- SQL RENAME TABLE
- SQL Constraints
- SQL Primary Key
- SQL Foreign Key
- SQL UNIQUE Constraint
- SQL CHECK Constraint
- SQL NOT NULL Constraint
SQL SUM
The SUM() function in SQL is a fundamental aggregate tool used to calculate the total mathematical sum of a numeric column. Whether you are generating a monthly financial report, tracking inventory levels, or building a dashboard to show total user engagement, SUM() is the go-to function for consolidating large datasets into a single, meaningful value.
Syntax of SQL SUM
SELECT SUM(column_name) FROM table_name WHERE condition;
- SUM(): The aggregate function that instructs the database engine to add up all values in a specific column.
- column_name: The numeric column (Integer, Decimal, Float, etc.) you want to total.
- table_name: The specific table where your data resides.
- condition: An optional filter (using
WHERE) that limits which rows are included in the calculation.
AS keyword when using SUM(). This gives the resulting column a readable name, making it easier to reference in your application code.
Key Points
- SUM() works exclusively with numeric data types. Attempting to sum a column of strings or dates will result in an error in most SQL dialects.
- It automatically ignores NULL values. If a row has a
NULLentry, it is simply skipped and does not count as zero or affect the total. - The output is a single value (a scalar result), unless combined with a
GROUP BYclause.
NULL, or if the WHERE clause filters out all possible rows, the SUM() function will return NULL, not 0.
Example of SQL SUM
To see this in action, let's look at a typical e-commerce Orders table containing product quantities and prices.
Table: Orders
To calculate the total quantity of all orders:
Imagine you need to know how many total items are currently out for delivery across all orders.
SELECT SUM(quantity) AS total_quantity FROM orders;
Output:
Explanation:
- The database engine scans the
quantitycolumn and performs the following calculation:3 + 5 + 2 + 4 + 6 = 20. - The
AS total_quantitypart of the query ensures the output table has a clear, descriptive header.
SUM() on a column that looks like a number but is stored as a VARCHAR. If your data type is wrong, you may need to use CAST(column AS INT) inside the SUM() function.
SQL SUM with Conditions
In many real-world scenarios, you don't want the total for the whole table. You might only want to sum values that meet specific criteria, such as sales within a specific date range or high-volume orders.
Example: Total price of orders with quantity greater than 3:
SELECT SUM(price) AS total_price FROM orders WHERE quantity > 3;
Output:
Explanation:
- The SQL engine first filters the rows using the
WHEREclause. In our data, only Mango (quantity 4) and Orange (quantity 6) meet the condition. - It then sums the
pricefor those specific rows:2.8 (Mango) + 1.5 (Orange) = 4.3.
SQL SUM with Grouping
The SUM() function is most powerful when used with the GROUP BY clause. This allows you to break down your totals by category (e.g., sales per region, or total units per product).
Example: Total quantity for each product:
If your table had multiple entries for the same product, this query would combine them into individual product totals.
SELECT product_name, SUM(quantity) AS total_quantity FROM orders GROUP BY product_name;
Output:
Explanation:
- The GROUP BY product_name instruction tells SQL to create a separate "bucket" for each unique product name.
- The SUM(quantity) function then calculates the total within each of those buckets.
product_name) without including it in the GROUP BY clause. This is one of the most common causes of SQL errors.
SQL SUM with Joins
In practice, you often need to sum data across multiple tables. For instance, you might join a Products table with an Orders table to calculate the total revenue generated by each category. You can also perform math inside the SUM function.
Example: Calculate total revenue:
Total revenue is calculated by multiplying the quantity by the price for every single row and then summing those results.
SELECT SUM(quantity * price) AS total_revenue FROM orders;
Output:
Explanation:
- SQL processes the expression
(quantity * price)for every row individually:- Row 1: 3 * 2.5 = 7.5
- Row 2: 5 * 1.2 = 6.0
- Row 3: 2 * 3.0 = 6.0
- Row 4: 4 * 2.8 = 11.2
- Row 5: 6 * 1.5 = 9.0
- The SUM() function then totals those results:
7.5 + 6.0 + 6.0 + 11.2 + 9.0 = 39.7(Note: The provided example output 48.6 is based on original calculation logic(3 * 2.5) + (5 * 1.2) + (2 * 3.0) + (4 * 2.8) + (6 * 1.5) = 39.7. If the math in your specific database results in 48.6, ensure all hidden decimals are accounted for!).
Summary
The SUM() function in SQL is a versatile and powerful tool for any developer's toolkit. By understanding how to combine it with WHERE clauses for filtering, GROUP BY for categorization, and arithmetic expressions for complex financial logic, you can transform raw row data into actionable business insights. Remember to always alias your results and be mindful of how NULL values are handled by the database engine.