Aggregate function

On this page 7

An aggregate function in SQL is a function that takes a set of rows as input and returns a single summary value, such as a count, total, average, minimum or maximum. Aggregates turn detailed records into the figures that reports and dashboards display, and they are among the most frequently used features of SQL in analytical and operational databases.

Aggregate functions work together with GROUP BY, which divides rows into groups and produces one output row per group, and with HAVING, which filters those groups after aggregation. Without GROUP BY, an aggregate treats the entire filtered result as one group and returns exactly one row.

How SQL evaluates an aggregate function

An aggregate function is evaluated in a fixed position of the logical query order. The database first builds the row source from FROM and JOIN, then filters rows with WHERE, then forms groups with GROUP BY, computes the aggregates for each group, filters groups with HAVING, and only then evaluates the SELECT list and ORDER BY.

This order explains a classic error: an aggregate cannot appear in a WHERE clause, because WHERE runs before any group exists. Conditions on aggregated values belong in HAVING. Internally, the engine keeps a small accumulator state per group, for example a running sum and a counter for AVG, and updates it as each row arrives, using either hash aggregation or sort-based aggregation.

The table below shows which clause handles which kind of condition.

ClauseRuns relative to aggregationTypical condition
WHEREBeforeorder_date >= ‘2026-01-01’
GROUP BYDefines the groupscustomer_id, region
HAVINGAfterSUM(amount) > 10000
ORDER BYAfterSorting by an aggregate result
Where conditions belong in an aggregated query

Standard aggregate functions and their behavior

The SQL standard defines a core set of aggregates that every major database supports. Their most important shared rule is that NULL values are ignored, with the single exception of COUNT(*), which counts rows regardless of content.

FunctionReturnsNULL handlingResult on empty input
COUNT(*)Number of rowsCounts all rows0
COUNT(column)Number of non-NULL valuesSkips NULL0
SUMTotal of numeric valuesSkips NULLNULL
AVGArithmetic meanSkips NULL in both sum and countNULL
MIN and MAXSmallest or largest valueSkips NULLNULL
Core aggregate functions

Beyond the core set, databases offer statistical aggregates such as STDDEV and VAR_SAMP, string aggregation with STRING_AGG or LISTAGG, array and JSON aggregation, boolean aggregates such as BOOL_AND, and ordered-set aggregates such as PERCENTILE_CONT for medians. Names and exact syntax vary by product, so portable code should rely on the standard set.

Modifiers: DISTINCT, FILTER and grouping extensions

Aggregate calls accept modifiers that change which values enter the calculation. DISTINCT inside an aggregate, as in COUNT(DISTINCT customer_id), removes duplicate values before aggregation. The FILTER clause, defined in the SQL standard and supported by PostgreSQL and SQLite, restricts input rows for one aggregate only; elsewhere the same effect is achieved with a CASE expression inside the function.

Grouping extensions compute several levels of aggregation in one statement. The following table compares them.

ExtensionGroups producedTypical use
ROLLUP(a, b)(a, b), (a), grand totalHierarchical subtotals such as year and month
CUBE(a, b)Every combination of a and bCross-tab reports
GROUPING SETSExactly the listed combinationsCustom sets of subtotals
GROUPING()Flag for a subtotal rowDistinguishes generated NULL from real NULL
Grouping extensions for multi-level totals

Aggregate functions compared with window functions

The same functions, such as SUM or AVG, can act as window functions when followed by an OVER clause. The decisive difference is that an aggregate collapses rows, while a window function keeps every row and adds the computed value alongside it.

AspectAggregate functionWindow function
Output rowsOne per groupOne per input row
Grouping syntaxGROUP BYOVER (PARTITION BY …)
Access to detail columnsOnly grouped or aggregated columnsAll columns of the row
Typical questionTotal revenue per regionEach order’s share of its region’s revenue
Aggregate and window usage side by side

Choosing between them depends on the required output: a summary report calls for an aggregate, while running totals, rankings and comparisons with a group average call for a window function. Combining both in one query is common, typically by aggregating in a common table expression first.

Common mistakes with aggregate functions

Most aggregate errors produce plausible but wrong numbers rather than error messages, which makes them dangerous in reporting.

  • Join fan-out: joining orders to order lines before summing order totals multiplies each total by the number of lines.
  • AVG on NULL-heavy columns: the mean covers only non-NULL rows, which may not be the intended denominator.
  • COUNT(column) instead of COUNT(*): rows with NULL in that column silently disappear from the count.
  • SUM on an empty set: the result is NULL, not zero, unless wrapped in COALESCE.
  • Non-grouped columns in SELECT: the standard rejects them, and older permissive modes return an arbitrary value.
  • Integer division in averages: some databases return an integer AVG for integer input unless values are cast.

For performance, aggregates over large tables benefit from covering indexes, partial pre-aggregation in materialized views, and filtering in WHERE rather than HAVING whenever the condition does not depend on an aggregated value.

The short version

An aggregate function boils many rows down to one number. Ask a database how many orders arrived today, what they were worth in total, or what the biggest one was, and an aggregate function does the counting and adding.

You can also split the rows into piles first, for example one pile per store, and get one answer for each pile. That is how a list of thousands of sales becomes a short summary table.

Where it makes a difference

A finance analyst at a subscription business prepares a monthly revenue report with one row per country. The query joins invoices to invoice_items and sums the invoice amount grouped by country. The total comes out about 2.6 times higher than the accounting ledger, because every invoice amount was repeated once for each of its line items.

The analyst rewrites the query to aggregate invoice_items in a common table expression first, then joins one row per invoice, and adds COALESCE so that countries without sales show zero instead of NULL. The report now matches the ledger to the cent, and a ROLLUP on region and country adds regional subtotals in the same statement.