The SUM function in MySQL is an aggregate function used to calculate the total sum of a numeric column. This function is frequently used in data analysis, reporting, and summarization tasks where numerical totals are required. Whether calculating total sales, total expenses, or aggregating metrics like distances or counts, the SUM function is indispensable.
In this guide, we will explore the syntax, practical examples, advanced usages, and performance considerations related to the SUM function in MySQL.
SELECT SUM(column_name) AS total_sum
FROM table_name
WHERE condition;
Here:
We will use a sales table to illustrate how the SUM function works:
CREATE TABLE sales (
id INT AUTO_INCREMENT PRIMARY KEY,
product_name VARCHAR(100),
category VARCHAR(50),
quantity INT,
price DECIMAL(10, 2),
sale_date DATE
);
INSERT INTO sales (product_name, category, quantity, price, sale_date) VALUES
('Laptop', 'Electronics', 2, 700.00, '2024-06-01'),
('Smartphone', 'Electronics', 3, 300.00, '2024-06-02'),
('Tablet', 'Electronics', 5, 200.00, '2024-06-05'),
('Headphones', 'Accessories', 4, 50.00, '2024-06-03'),
('Charger', 'Accessories', 6, 20.00, '2024-06-04'),
('Mouse', 'Accessories', 10, 15.00, '2024-06-06');
SELECT SUM(quantity) AS total_quantity
FROM sales;
+----------------+
| total_quantity |
+----------------+
| 30 |
+----------------+
This query sums all the quantities from the sales table, giving us the total number of items sold.
SELECT SUM(quantity) AS electronics_quantity
FROM sales
WHERE category = 'Electronics';
+----------------------+
| electronics_quantity |
+----------------------+
| 10 |
+----------------------+
This example sums the quantity of only the Electronics category.
Total revenue can be calculated by multiplying quantity by price for each sale and summing the result.
SELECT SUM(quantity * price) AS total_revenue
FROM sales;
+---------------+
| total_revenue |
+---------------+
| 3950.00 |
+---------------+
To get a summed value grouped by another column, use the GROUP BY clause.
SELECT category, SUM(quantity) AS total_quantity
FROM sales
GROUP BY category;
+-------------+----------------+
| category | total_quantity |
+-------------+----------------+
| Accessories | 20 |
| Electronics | 10 |
+-------------+----------------+
SELECT product_name, SUM(quantity * price) AS product_revenue
FROM sales
GROUP BY product_name;
+-------------+----------------+
| product_name| product_revenue|
+-------------+----------------+
| Laptop | 1400.00 |
| Smartphone | 900.00 |
| Tablet | 1000.00 |
| Headphones | 200.00 |
| Charger | 120.00 |
| Mouse | 150.00 |
+-------------+----------------+
In complex databases, SUM is often used with JOINs to aggregate data across multiple tables.
CREATE TABLE products (
product_id INT PRIMARY KEY,
product_name VARCHAR(100),
category VARCHAR(50)
);
INSERT INTO products (product_id, product_name, category) VALUES
(1, 'Laptop', 'Electronics'),
(2, 'Smartphone', 'Electronics'),
(3, 'Tablet', 'Electronics'),
(4, 'Headphones', 'Accessories'),
(5, 'Charger', 'Accessories'),
(6, 'Mouse', 'Accessories');
SELECT p.category, SUM(s.quantity * s.price) AS total_revenue
FROM sales s
JOIN products p ON s.product_name = p.product_name
GROUP BY p.category;
+-------------+---------------+
| category | total_revenue |
+-------------+---------------+
| Accessories | 470.00 |
| Electronics | 3480.00 |
+-------------+---------------+
To sum distinct values, use SUM(DISTINCT column_name).
SELECT SUM(DISTINCT quantity) AS sum_distinct_quantity
FROM sales;
+-----------------------+
| sum_distinct_quantity |
+-----------------------+
| 27 |
+-----------------------+
The HAVING clause filters aggregated data.
SELECT category, SUM(quantity * price) AS total_revenue
FROM sales
GROUP BY category
HAVING total_revenue > 1000;
+-------------+---------------+
| category | total_revenue |
+-------------+---------------+
| Electronics | 3480.00 |
+-------------+---------------+
SELECT product_name, SUM(quantity * price) AS product_revenue
FROM sales
GROUP BY product_name
HAVING product_revenue > (
SELECT AVG(quantity * price) FROM sales
);
+-------------+----------------+
| product_name| product_revenue|
+-------------+----------------+
| Laptop | 1400.00 |
| Smartphone | 900.00 |
| Tablet | 1000.00 |
+-------------+----------------+
SUM automatically ignores NULLs. For example, if a price is NULL, that row is not counted in the sum.
INSERT INTO sales (product_name, category, quantity, price, sale_date)
VALUES ('Keyboard', 'Accessories', 5, NULL, '2024-06-07');
SELECT SUM(price) AS total_price
FROM sales;
The price for 'Keyboard' being NULL is excluded from the total sum.
Window functions allow cumulative sums over partitions of data.
SELECT
product_name,
quantity * price AS revenue,
SUM(quantity * price) OVER (ORDER BY sale_date) AS running_total
FROM sales;
+-------------+---------+--------------+
| product_name| revenue | running_total|
+-------------+---------+--------------+
| Laptop | 1400.00 | 1400.00 |
| Smartphone | 900.00 | 2300.00 |
| Headphones | 200.00 | 2500.00 |
| Charger | 120.00 | 2620.00 |
| Tablet | 1000.00 | 3620.00 |
| Mouse | 150.00 | 3770.00 |
| Keyboard | NULL | 3770.00 |
+-------------+---------+--------------+
The SUM function in MySQL is a core aggregate function that plays a vital role in data summarization and analysis. Whether youβre calculating simple totals, aggregating with GROUP BY, or analyzing data over time with window functions, SUM is a powerful and versatile tool.
By understanding its syntax, behavior with NULLs, integration with GROUP BY, JOINs, HAVING, and window functions, users can leverage SUM effectively to derive insights from their datasets. With good indexing and query optimization, even complex SUM queries can be made efficient and scalable.
Use the command: CREATE INDEX index_name ON table_name (column_name); to create an index on a MySQL table.
To install MySQL on Windows, download the installer from the official MySQL website, run the setup, and follow the installation wizard to configure the server and set up user accounts.
MySQL is an open-source relational database management system (RDBMS) that uses SQL (Structured Query Language) for managing and manipulating databases. It is widely used in web applications for its speed and reliability.
Use the command: INSERT INTO table_name (column1, column2) VALUES (value1, value2); to add records to a MySQL table.
Use the command: mysql -u username -p database_name < data.sql; to import data from a SQL file into a MySQL database.
DELETE removes records based on a condition and can be rolled back, while TRUNCATE removes all records from a table and cannot be rolled back.
A trigger is a set of SQL statements that automatically execute in response to certain events on a MySQL table, such as INSERT, UPDATE, or DELETE.
The default MySQL port is 3306, and the root password is set during installation. If not set, you may need to configure it manually.
Replication in MySQL allows data from one MySQL server (master) to be copied to one or more servers (slaves), providing data redundancy and load balancing.
A primary key is a unique identifier for a record in a MySQL table, ensuring that no two records have the same key value.
Use the command: SELECT column1, column2 FROM table_name; to fetch data from a MySQL table.
Use the command: CREATE DATABASE database_name; to create a new MySQL database.
Use the command: CREATE PROCEDURE procedure_name() BEGIN SQL_statements; END; to define a stored procedure in MySQL.
Indexing in MySQL improves query performance by allowing the database to find rows more quickly. Common index types include PRIMARY KEY, UNIQUE, and FULLTEXT.
Use the command: UPDATE table_name SET column1 = value1 WHERE condition; to modify existing records in a MySQL table.
CHAR is a fixed-length string data type, while VARCHAR is variable-length. CHAR is faster for fixed-size data, whereas VARCHAR saves space for variable-length data.
MyISAM is a storage engine that offers fast read operations but lacks support for transactions, while InnoDB supports transactions and foreign keys, providing better data integrity.
A stored procedure is a set of SQL statements that can be stored and executed on the MySQL server, allowing for modular programming and code reuse.
Use the command: mysqldump -u username -p database_name > backup.sql; to create a backup of a MySQL database.
Use the command: DELETE FROM table_name WHERE condition; to remove records from a MySQL table.
A foreign key is a column or set of columns in one MySQL table that references the primary key in another, establishing a relationship between the two tables.
Use the command: CREATE TRIGGER trigger_name BEFORE INSERT ON table_name FOR EACH ROW BEGIN SQL_statements; END; to create a trigger in MySQL.
Normalization in MySQL is the process of organizing data to reduce redundancy and improve data integrity by dividing large tables into smaller ones.
JOIN is used to combine rows from two or more MySQL tables based on a related column, allowing for complex queries and data retrieval.
Use the command: mysqldump -u username -p database_name > backup.sql; to export a MySQL database to a SQL file.
Copyrights © 2024 letsupdateskills All rights reserved