Back to all posts

SQL Aggregate Functions: COUNT, SUM, AVG, MIN, MAX, and GROUP BY

For someone learning SQL who can already write a SELECT with WHERE and ORDER BY; GROUP BY, HAVING and ROLLUP are explained where they appear.

On this page

An aggregate function returns one value from many rows, such as how many rows there are or the sum of a column. For example, you can get the number of sales in a sales table and the sum of their amounts.

A query with an aggregate function has this shape:

SELECT column, FUNCTION(column)
FROM table
WHERE condition
GROUP BY column
HAVING condition;
  • FUNCTION is one of the aggregate functions in the table under this list.
  • WHERE condition is optional. It chooses the rows before the function reads them.
  • GROUP BY column is optional. Without GROUP BY, all rows form one group, and the query returns one row. With GROUP BY, the query returns one row for each value of the column.
  • HAVING condition is optional. It runs after the function, and keeps only the groups whose aggregate value matches the condition.

Every function except COUNT(*) skips NULL, the mark of a missing value:

FunctionWhat it returnsSkips NULL
COUNT(*)the number of rowsNo
COUNT(column)the number of values that are not NULLYes
SUM(column)the total of the valuesYes
AVG(column)the average of the valuesYes
MIN(column)the smallest valueYes
MAX(column)the largest valueYes

Create a sample table of six sales, and fill it:

CREATE TABLE sales (
  region  varchar(10),
  product varchar(10),
  amount  int
);

INSERT INTO sales VALUES
  ('North', 'Widget', 120),
  ('South', 'Gadget', 200),
  ('North', 'Gadget', 180),
  ('East',  'Widget',  90),
  ('South', 'Widget', 150),
  ('North', 'Gizmo',  NULL);

The Gizmo sale has no amount yet, so its amount is NULL. Every statement below was run on three database engines: PostgreSQL 18.6, MySQL 9.1.0 and SQLite 3.50.4. All three returned the same values, except where an engine is named.

COUNT

COUNT(*) counts the rows. COUNT(column) counts only the rows where that column holds a value. For example, you can count all sales, and the sales that have an amount.

SELECT COUNT(*)      AS all_rows,
       COUNT(amount) AS with_amount
FROM sales;
all_rowswith_amount
65

The table has six rows, so COUNT(*) returns 6. The Gizmo sale has no amount, so COUNT(amount) leaves the Gizmo sale out and returns 5. SQL COUNT, AVG, and SUM also shows COUNT(DISTINCT column), which counts the different values of a column.

SUM

SUM adds up the values of a numeric column. For example, you can add up the amounts of all sales.

SELECT SUM(amount) AS total
FROM sales;
total
740

SUM adds 120, 200, 180, 90 and 150, and skips the NULL amount of the Gizmo sale.

AVG

AVG returns the average of a numeric column: the total of the values, divided by the number of values. For example, you can get the average amount of a sale.

SELECT AVG(amount) AS average
FROM sales;
average
148.0000000000000000

AVG divides the total of 740 by 5, because only five sales have an amount. The engines print 148 in different ways: PostgreSQL as in the table, MySQL as 148.0000, and SQLite as 148.0.

If a missing amount should count as 0, the average is 740 divided by 6. SQL COUNT, AVG, and SUM shows how to get that average with COALESCE, which replaces NULL with 0.

MIN and MAX

MIN returns the smallest value of a column, and MAX returns the largest. For example, you can find the smallest and the largest sale.

SELECT MIN(amount) AS lowest,
       MAX(amount) AS highest
FROM sales;
lowesthighest
90200

East's sale of 90 is the smallest, and South's sale of 200 is the largest. MIN skips the NULL amount of the Gizmo sale. MIN and MAX also work on text and dates, as SQL MIN() and MAX() shows.

Practice this in Lesson 6 of the SQL tutorial: you run COUNT, SUM, AVG, MIN and MAX on a shop database in your browser, and each exercise is checked.

GROUP BY

GROUP BY splits the rows into groups, one group for each value of a column. Each aggregate function then returns one value per group. For example, you can count the sales of each region and add up their amounts.

SELECT region,
       COUNT(*)    AS sales,
       SUM(amount) AS total
FROM sales
GROUP BY region
ORDER BY region;
regionsalestotal
East190
North3300
South2350

North has three sales, and its total of 300 comes from 120 and 180. COUNT(*) counts the Gizmo sale, and SUM skips its NULL amount. East has one sale, and South has two.

The six sales rows sorted into East, North and South by GROUP BY region, then summed to 90, 300 and 350, with the NULL amount skipped

SQL GROUP BY Statement shows GROUP BY on several columns and with joins.

HAVING

HAVING keeps only the groups whose aggregate value matches a condition. For example, you can keep the regions whose sales add up to more than 100.

SELECT region, SUM(amount) AS total
FROM sales
GROUP BY region
HAVING SUM(amount) > 100
ORDER BY region;
regiontotal
North300
South350

East's total is 90, so HAVING drops East, and North and South stay.

Put a condition on a plain column, such as region = 'North', in WHERE. WHERE removes rows before GROUP BY makes the groups. SQL HAVING Clause has more examples.

FILTER and CASE

FILTER gives one aggregate function a condition of its own. That function reads only the rows where the condition is true (PostgreSQL 18 documentation). For example, you can return the total of all sales and the total of North side by side.

SELECT SUM(amount)                                 AS total,
       SUM(amount) FILTER (WHERE region = 'North') AS north_total
FROM sales;
totalnorth_total
740300

The first SUM reads all six rows, and the second SUM reads only North's three rows. WHERE can't do this. WHERE region = 'North' removes the other rows for every function in the query, so the first SUM would also return 300.

PostgreSQL and SQLite run FILTER. MySQL 9.1.0 rejects it with ERROR 1064, a syntax error at (WHERE region = 'North'). A CASE expression inside SUM returns the same totals on all three engines:

SELECT SUM(amount)                                     AS total,
       SUM(CASE WHEN region = 'North' THEN amount END) AS north_total
FROM sales;
totalnorth_total
740300

On North's rows, the CASE expression returns the amount. On every other row, CASE returns NULL, because this CASE has no ELSE. SUM skips those NULLs and adds up North's amounts.

If the query has to run on MySQL too, use CASE.

ROLLUP

ROLLUP adds total rows to a grouped result. For example, you can return the total of each region and the total of all regions in one result.

SELECT region, SUM(amount) AS total
FROM sales
GROUP BY ROLLUP(region)
ORDER BY region;

PostgreSQL returns:

regiontotal
East90
North300
South350
NULL740

The first three rows are the result of GROUP BY region. The last row is the total of all regions. Its region is NULL, because the total covers every region.

MySQL sorts NULL before every other value in ascending order (MySQL 8.4 manual). So MySQL returns the same four rows with the total first.

With two columns, ROLLUP(region, product) returns each region and product, a subtotal for each region, and the grand total. CUBE(region, product) adds a total for each product as well. GROUPING SETS lists the exact groupings to return (PostgreSQL 18 documentation).

MySQL also accepts GROUP BY region WITH ROLLUP (MySQL 8.4 manual). The three engines support different clauses:

ClausePostgreSQL 18.6MySQL 9.1.0SQLite 3.50.4
ROLLUP(...)runsrunsno such function: ROLLUP
WITH ROLLUPsyntax errorrunssyntax error
CUBE(...)runsERROR 3889no such function: CUBE
GROUPING SETSrunsERROR 1064syntax error

Aggregate functions with OVER

OVER makes an aggregate function show its value on every row, and keeps every row in the result. For example, you can list every sale with its region's total beside it.

SELECT region, product, amount,
       SUM(amount) OVER (PARTITION BY region) AS region_total
FROM sales
ORDER BY region, product;
regionproductamountregion_total
EastWidget9090
NorthGadget180300
NorthGizmoNULL300
NorthWidget120300
SouthGadget200350
SouthWidget150350

PARTITION BY region splits the rows into the same groups as GROUP BY region. SUM runs once in each group, but all six sales stay, and each of North's three rows shows 300. Window Functions in SQL explains OVER.

What goes wrong

An aggregate function in WHERE

When WHERE runs, the groups and their totals don't exist yet:

SELECT region, SUM(amount) AS total
FROM sales
WHERE SUM(amount) > 100
GROUP BY region;

Each engine rejects the query:

  • PostgreSQL: ERROR: aggregate functions are not allowed in WHERE
  • MySQL: ERROR 1111 (HY000): Invalid use of group function
  • SQLite: misuse of aggregate: SUM()

Move the condition to HAVING.

A column that is neither grouped nor aggregated

In a query with GROUP BY, each column of the SELECT list has to be in GROUP BY or inside an aggregate function. Here product is in neither, and North has three products:

SELECT region, product, SUM(amount) AS total
FROM sales
GROUP BY region
ORDER BY region;

PostgreSQL rejects the query with column "sales.product" must appear in the GROUP BY clause or be used in an aggregate function. MySQL 9.1.0 rejects it with ERROR 1055, because its ONLY_FULL_GROUP_BY setting is on by default (MySQL 8.4 manual).

SQLite runs the query, and takes product from one row of each group, chosen by SQLite (SQLite documentation):

regionproducttotal
EastWidget90
NorthWidget300
SouthGadget350

North's 300 includes the Gadget sale of 180, but the row says Widget. Add product to GROUP BY for one row per region and product, or remove product from the SELECT list.

SUM of a text column

SUM and AVG add up numbers. On a text column, the three engines behave differently:

SELECT SUM(region) AS total
FROM sales;

PostgreSQL rejects the query with function sum(character varying) does not exist.

MySQL returns 0 and a warning for each row, such as Truncated incorrect DOUBLE value: 'North'. SQLite returns 0.0 and no warning. On both, a SUM of the wrong column looks like a real total.

Build aggregate queries in DbSchema

The SQL Editor in DbSchema runs a query and shows its rows in a grid under the editor. Press Editor in the toolbar, choose SQL Editor, paste a query from this article, and press Run.

The GROUP BY query in the DbSchema SQL Editor, with the sales count and total of East, North and South in the result grid under the editor

The Query Builder in DbSchema writes the aggregate functions and the GROUP BY for you. DbSchema's menus call it the Query Editor.

  1. Right-click a table on the diagram and choose Query Editor.
  2. Tick the columns you want.
  3. Right-click a column, choose Aggregate, then a function such as Sum(?), Count(*) or Avg(?).
  4. Press Run.

DbSchema adds a GROUP BY on the ticked columns that have no aggregate function, and the result grid under the builder lists one row per group.

The DbSchema Query Builder with the Aggregate menu open on total_amount, listing Min, Max, Count, Avg and Sum, and the summed rows in the result grid

Download DbSchema at https://dbschema.com/download.html and connect it to PostgreSQL, MySQL or SQLite. Paste the CREATE TABLE and INSERT statements into the SQL Editor, then run and change each query. The free Community Edition includes the database connection and the SQL Editor, and the Query Builder is part of DbSchema Pro.

DbSchema ER diagram designer DbSchema ER diagram designer

Design and visualize
your database schema

Edit referenced records
in related tables

Query your data
visually too

Reuse the SQL
generated

Free Download