0
0
SQLquery~5 mins

SUM function in SQL

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
SQL
SELECT SUM(column_name) FROM table_name;
The column_name should be a numeric column like numbers or amounts.
You can use SUM with WHERE to add only certain rows.
Examples
Adds up all the prices in the products table.
SQL
SELECT SUM(price) FROM products;
Adds up quantities only for completed orders.
SQL
SELECT SUM(quantity) FROM orders WHERE status = 'completed';
Adds sales for each category separately.
SQL
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 the amounts.
SQL
CREATE TABLE sales (
  id INT,
  product VARCHAR(50),
  amount INT
);

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

SELECT SUM(amount) FROM sales;
OutputSuccess
Important Notes
SUM ignores NULL values in the column.
If there are no rows, SUM returns NULL, not zero.
Use GROUP BY with SUM to get totals for groups.
Summary
SUM adds all numbers in a column to get a total.
It works only on numeric columns.
You can filter rows or group them before summing.