Skip to content

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

Three functions summarise a column in a single value:

  • COUNT() counts rows.
  • SUM() adds up a numeric column.
  • AVG() takes the average of a numeric column.
SELECT SUM(column_name)
FROM table_name
WHERE condition;

The examples use the Invoices and Crew tables from the example database.

COUNT(*) counts rows. COUNT(column) counts only the rows where that column has a value, which makes the difference a useful question in itself. Here it tells you how many invoices there are, and how many have been paid:

SELECT COUNT(*) AS Invoices, COUNT(PaidDate) AS Paid
FROM Invoices;
Invoices Paid
4 2

COUNT(PaidDate) skips the two invoices whose paid date is NULL.

The total of all invoices:

SELECT SUM(Amount) AS Total
FROM Invoices;
Total
71,970.00

With a WHERE clause, the total covers only the rows that pass. The amount still to be paid:

SELECT SUM(Amount) AS Outstanding
FROM Invoices
WHERE PaidDate IS NULL;
Outstanding
44,190.00

The average day rate across the crew:

SELECT AVG(DayRate) AS AverageRate
FROM Crew;
AverageRate
470

To work these out for each production or department separately, rather than for the whole table, add GROUP BY.