Mysql sum select column

For example, you might wish to know how the combined total salary of all employees whose salary is above $50,000 / year.

SELECT SUM(salary) AS "Total Salary"
FROM employees
WHERE salary > 50000;

In this SUM function example, we've aliased the SUM(salary) expression as "Total Salary". As a result, "Total Salary" will display as the field name when the result set is returned.

Example - Using DISTINCT

You can use the DISTINCT clause within the SUM function. For example, the SQL statement below returns the combined total salary of unique salary values where the salary is above $50,000 / year.

SELECT SUM(DISTINCT salary) AS "Total Salary"
FROM employees
WHERE salary > 50000;

If there were two salaries of $82,000/year, only one of these values would be used in the SUM function.

Example - Using Formula

The expression contained within the SUM function does not need to be a single field. You could also use a formula. For example, you might want to calculate the total commission.

SELECT SUM(sales * 0.05) AS "Total Commission"
FROM orders;

Example - Using GROUP BY

In some cases, you will be required to use the GROUP BY clause with the SUM function.

For example, you could also use the SUM function to return the name of the department and the total sales (in the associated department).

SELECT department, SUM(sales) AS "Total sales"
FROM order_details
GROUP BY department;

Because you have listed one column in your SELECT statement that is not encapsulated in the SUM function, you must use a GROUP BY clause. The department field must, therefore, be listed in the GROUP BY section.

Our database has a table named game with data in the following columns: id, player, and score.

idplayerscore1John1342Tom1463Lucy204Tom1185Tom1026Lucy907Lucy348John122

Let’s find the total score obtained by all players.

Solution:

SELECT SUM(score) as sum_score
FROM game;

Here’s the result:

sum_score766

Discussion:

The aggregate function SUM is ideal for computing the sum of a column’s values. This function is used in a SELECT statement and takes the name of the column whose values you want to sum.

If you do not specify any other columns in the SELECT statement, then the sum will be calculated for all records in the table. In our example, we only select the sum and no other columns. Therefore, the query in our example returns the sum all scores (766).

Of course, we can also compute the total score earned by each player by using a GROUP BY clause and selecting each player’s name from the table, alongside the sum:

MySQL SUM() function returns the sum of an expression. SUM() function returns NULL when the return set has no rows.

Syntax:

SUM([DISTINCT] expr)

Where expr is an expression.

The DISTINCT keyword can be used to sum only the distinct values of expr.

MySQL Version: 5.6

Contents:

Example: MySQL SUM() function

The following MySQL statement returns the sum of 'total_cost' from purchase table.

Sample table: purchase


Code:

SELECT SUM(total_cost)             
FROM purchase;

Relational Algebra Expression:

Mysql sum select column

Relational Algebra Tree:

Mysql sum select column

Sample Output:

mysql> SELECT SUM(total_cost)             
    -> FROM purchase;
+-----------------+
| SUM(total_cost) |
+-----------------+
|         3590.00 | 
+-----------------+
1 row in set (0.00 sec)

PHP script:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>example-SUM()- php MySQL examples | w3resource</title>
<meta name="description" content="example-SUM()- php MySQL examples | w3resource">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Sum of total costs of purchases:</h2>
<table class='table table-bordered'>
<tr>
<th>Sum of total costs of purchases</th>
</tr>
<?php
$hostname="your_hostname";
$username="your_username";
$password="your_password";
$db = "your_dbname";
$dbh = new PDO("MySQL:host=$hostname;dbname=$db", $username, $password);
foreach($dbh->query('SELECT SUM(total_cost) 
FROM purchase') as $row) {
echo "<tr>";
echo "<td>" . $row['SUM(total_cost)'] . "</td>";
echo "</tr>"; 
}
?>
</tbody></table>
</div>
</div>
</div>
</body>
</html>

View the example in browser

JSP script:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>example-sum()</title>
</head>
<body>
<%
try {
Class.forName("com.MySQL.jdbc.Driver").newInstance();
String Host = "jdbc:MySQL://localhost:3306/w3resour_bookinfo";
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
connection = DriverManager.getConnection(Host, "root", "datasoft123");
statement = connection.createStatement();
String Data = "SELECT SUM(total_cost) FROM purchase";
rs = statement.executeQuery(Data);
%>
<TABLE border="1">
<tr width="10" bgcolor="#9979">
<td>Sum of total costs of purchases</td>
</tr>
<%
while (rs.next()) {
%>
<TR>
<TD><%=rs.getString("SUM(total_cost)")%></TD>
</TR>
<%   }    %>
</table>
<%
rs.close();
statement.close();
connection.close();
} catch (Exception ex) {
out.println("Can’t connect to database.");
}
%>
</body>
</html>

Example: MySQL SUM() function with where clause

MySQL SUM() function with WHERE retrieves the sum of a given expression which is filtered against a condition placed after WHERE. The following MySQL statement returns the sum of 'total_cost' from purchase table for the category ('cate_id') given with WHERE clause.

Sample table: purchase


Code:

SELECT SUM(total_cost) 
FROM purchase          
WHERE cate_id='CA001';

Relational Algebra Expression:

Mysql sum select column

Relational Algebra Tree:

Mysql sum select column

Sample Output:

mysql> SELECT SUM(total_cost) 
    -> FROM purchase          
    -> WHERE cate_id='CA001';
+-----------------+
| SUM(total_cost) |
+-----------------+
|         1725.00 | 
+-----------------+
1 row in set (0.00 sec)

PHP script:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>example-aggregate-functions-and-grouping-sum-with-where- php MySQL examples | w3resource</title>
<meta name="description" content="example-aggregate-functions-and-grouping-sum-with-where- php MySQL examples | w3resource">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Sum of total costs of purchases for category id CA001:</h2>
<table class='table table-bordered'>
<tr>
<th>Sum of total costs of purchases for category id CA001</th>
</tr>
<?php
$hostname="your_hostname";
$username="your_username";
$password="your_password";
$db = "your_dbname";
$dbh = new PDO("MySQL:host=$hostname;dbname=$db", $username, $password);
foreach($dbh->query('SELECT SUM(total_cost) 
FROM purchase
WHERE cate_id="CA001"') as $row) {
echo "<tr>";
echo "<td>" . $row['SUM(total_cost)'] . "</td>";
echo "</tr>";
}
?>
</tbody></table>
</div>
</div>
</div>
</body>
</html>

View the example in browser

Example: MySQL SUM() function using multiple columns

MySQL SUM() function retrieves the sum of a unique value of an expression if it is accompanied by DISTINCT clause. The following MySQL statement returns the sum of a number of branches ('no_of_branch') from publisher table, where, if more than one publisher has the same number of branches, that number (i.e. number of branches) is taken once only.

How do I sum a column in MySQL?

The MySQL sum() function is used to return the total summed value of an expression. It returns NULL if the result set does not have any rows. It is one of the kinds of aggregate functions in MySQL..
SELECT SUM(aggregate_expression).
FROM tables..
[WHERE conditions];.

How do I sum a selection in SQL?

If you need to add a group of numbers in your table you can use the SUM function in SQL. This is the basic syntax: SELECT SUM(column_name) FROM table_name; If you need to arrange the data into groups, then you can use the GROUP BY clause.

How to sum multiple column value in MySQL?

MySQL SUM() function retrieves the sum value of an expression which is made up of more than one columns. The above MySQL statement returns the sum of multiplication of 'receive_qty' and 'purch_price' from purchase table for each group of category ('cate_id') .

How do you sum a column in a query?

You can sum a column of numbers in a query by using a type of function called an aggregate function. Aggregate functions perform a calculation on a column of data and return a single value. Access provides a variety of aggregate functions, including Sum, Count, Avg (for computing averages), Min and Max.