SQL COUNT, SUM, AVG

The SQL COUNT(), SUM() and AVG() Functions

These are three of the most common aggregate functions in SQL.


COUNT() Function

The COUNT() function returns the number of rows that matches a specified criterion.

COUNT() Syntax

SELECT COUNT(column_name)
FROM table_name
WHERE condition;

COUNT(*) returns the total number of records in a table. COUNT(column_name) returns the number of non-NULL values in that column.


SUM() Function

The SUM() function returns the total sum of a numeric column.

SUM() Syntax

SELECT SUM(column_name)
FROM table_name
WHERE condition;

AVG() Function

The AVG() function returns the average value of a numeric column.

AVG() Syntax

SELECT AVG(column_name)
FROM table_name
WHERE condition;

Demo Database

Below is a selection from the Orders table:

Orders Table:

OrderID CustomerID OrderDate
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20

Example 1: Using COUNT()

The following SQL statement finds the total number of orders in the Orders table.

COUNT() Example

SELECT COUNT(OrderID) FROM Orders;

Example 2: Using SUM()

The following SQL statement finds the sum of the "CustomerID" fields for all orders.

SUM() Example

SELECT SUM(CustomerID) FROM Orders;

Example 3: Using AVG()

The following SQL statement finds the average CustomerID for all orders.

AVG() Example

SELECT AVG(CustomerID) FROM Orders;