The SUM() function in MySQL is used to calculate the sum of a set of values. It can be used with any set of numeric values, such as integers, floats, doubles, and decimals.
The syntax for the SUM() function is as follows:
SQL
SUM(column_name)
The column_name parameter is the name of the column that you want to sum. For example, the following SQL statement will calculate the sum of all product prices in the
products table:
SQL
SELECT SUM(price)
FROM products;
This will return a single value, which is the sum of all product prices in the
products table.
Here is an example of how to use the SUM() function in MySQL:
SQL
CREATE TABLE products (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
price INT NOT NULL,
PRIMARY KEY (id)
);
INSERT INTO products (name, price) VALUES
('Product 1', 100),
('Product 2', 200),
('Product 3', 300),
('Product 4', 400),
('Product 5', 500);
SELECT SUM(price)
FROM products;
This will return the following result:
1500
As you can see, the SUM() function has calculated the sum of all product prices in the
products table, which is 1500.
Here are some additional things to keep in mind when using the SUM() function:
The SUM() function ignores NULL values.
You can use the DISTINCT keyword to calculate the sum of distinct values in a column.
You can use the GROUP BY clause to calculate the sum of values in a group.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
The
SUM()function in MySQL is used to calculate the sum of a set of values. It can be used with any set of numeric values, such as integers, floats, doubles, and decimals.The syntax for the
SUM()function is as follows:SQL
The
column_nameparameter is the name of the column that you want to sum. For example, the following SQL statement will calculate the sum of all product prices in theproductstable:SQL
This will return a single value, which is the sum of all product prices in the
productstable.Here is an example of how to use the
SUM()function in MySQL:SQL
This will return the following result:
As you can see, the
SUM()function has calculated the sum of all product prices in theproductstable, which is 1500.Here are some additional things to keep in mind when using the
SUM()function:SUM()function ignores NULL values.DISTINCTkeyword to calculate the sum of distinct values in a column.GROUP BYclause to calculate the sum of values in a group.