0
0
MySQLquery~5 mins

SUM function in MySQL

Choose your learning style9 modes available
Introduction
The SUM function adds up all the numbers in a column to give you the total. It helps you quickly find the total amount or quantity.
When you want to find the total sales made in a day.
When you need to calculate the total number of items sold.
When you want to add up all the expenses in a budget.
When you want to find the total score of a player in a game.
When you want to sum up all the hours worked by employees.
Syntax
MySQL
SELECT SUM(column_name) FROM table_name;
Replace column_name with the name of the column you want to add up.
Replace table_name with the name of your table.
Examples
Adds up all the prices in the products table.
MySQL
SELECT SUM(price) FROM products;
Adds up the quantity of only completed orders.
MySQL
SELECT SUM(quantity) FROM orders WHERE status = 'completed';
Adds up sales for each category separately.
MySQL
SELECT category, SUM(sales) FROM sales_data GROUP BY category;
Sample Program
This creates a sales table, adds some sales amounts, and then sums all amounts to find the total sales.
MySQL
CREATE TABLE sales (
  id INT,
  product VARCHAR(50),
  amount INT
);

INSERT INTO sales VALUES
(1, 'Apple', 10),
(2, 'Banana', 15),
(3, 'Apple', 5),
(4, 'Orange', 20);

SELECT SUM(amount) AS total_amount FROM sales;
OutputSuccess
Important Notes
SUM ignores NULL values, so they do not affect the total.
You can use SUM with GROUP BY to get totals for different groups.
SUM only works with numeric columns.
Summary
SUM adds all numbers in a column to get a total.
Use SUM to quickly find totals like sales, quantities, or scores.
Works well with conditions and grouping to get specific totals.