SQL SUM Function – Tutorialpath

SQL SUM Function

This SQL tutorial explains how to use the SQL SUM function with syntax and examples.

Description

The SQL SUM function is used to return the sum of an expression in a SELECT statement.

SQL SELECT COUNT, SUM, AVG

  • SELECT COUNT returns a count of the number of data values.
  • SELECT SUM returns the sum of the data values.
  • SELECT AVG returns the average of the data values.

COUNT Syntax:

SUM Syntax:

AVG Syntax:

Example – With Single Expression

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

In this SQL 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 SQL GROUP BY

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

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *