SQL SUM Function Tutorial
Example Table
We will use the following table named sales
for our examples:
CREATE TABLE sales (
sale_id INT PRIMARY KEY,
product_name VARCHAR(50),
quantity INT,
price DECIMAL(10, 2)
);
INSERT INTO sales (sale_id, product_name, quantity, price) VALUES
(1, 'Laptop', 2, 1200.00),
(2, 'Mouse', 5, 25.00),
(3, 'Keyboard', 3, 45.00),
(4, 'Monitor', 1, 300.00),
(5, 'Chair', 4, 150.00);
Sales Table
sale_id | product_name | quantity | price |
---|---|---|---|
1 | Laptop | 2 | 1200.00 |
2 | Mouse | 5 | 25.00 |
3 | Keyboard | 3 | 45.00 |
4 | Monitor | 1 | 300.00 |
5 | Chair | 4 | 150.00 |
Using the SQL SUM Function
The SQL SUM
function is used to calculate the total sum of a numeric column. In this tutorial, we will demonstrate how to use the SUM
function with the sales
table.
Example: Calculating Total Sales Quantity
To calculate the total quantity of all products sold:
SELECT SUM(quantity) AS total_quantity FROM sales;
Result:
Query | SELECT SUM(quantity) AS total_quantity FROM sales; |
---|---|
Result | 15 |
Example: Calculating Total Sales Revenue
To calculate the total revenue from all sales:
SELECT SUM(quantity * price) AS total_revenue FROM sales;
Result:
Query | SELECT SUM(quantity * price) AS total_revenue FROM sales; |
---|---|
Result | 3075.00 |
Example: Calculating Total Revenue by Product
To calculate the total revenue for each product:
SELECT product_name, SUM(quantity * price) AS total_revenue
FROM sales
GROUP BY product_name;
Result:
Query | SELECT product_name, SUM(quantity * price) AS total_revenue FROM sales GROUP BY product_name; |
---|---|
Result |
|