MySQL SUM function

MySQL SUM function

  • The SUM() function returns the total sum of a numeric column.
  • The SUM() function is an aggregate function that allows you to calculate the sum of a set of values or an expression.
  • Syntax for SUM function would be as below:

SELECT SUM(column_name)
FROM table_name
WHERE condition;

  • You can also use distinct value while sum function

SELECT SUM(distinct column_name)
FROM table_name
WHERE condition;

  • If you use the SUM() function in a SELECT statement that returns no matching row, the SUM()function returns NULL, not zero.
  • The DISTINCT operator allows you to calculate distinct values in the set.
  • The SUM() function ignores the NULL values in the calculation

 

Query Example:

Example 1:
SELECT
    FORMAT(SUM(quantityOrdered * priceEach),
        2) total
FROM
    orderdetails
WHERE
    orderNumber = 10100;
Example 2:
SELECT SUM(Quantity)
FROM OrderDetails;