SQL: Structured Query LanguageSQL FundamentalsAggregate Functions
What is a SQL aggregate function?
Question 26 of 30 · Updated
On this page
- 1. Why do we use aggregate functions?
- 2. Five common SQL aggregate functions
- 3. A reproducible example dataset
- 4. Summarize the entire input
- 5. Aggregate functions with GROUP BY
- 6. Filter rows before computing a summary
- 7. What happens with NULL and empty input?
- 8. Aggregate versus ordinary per-row calculations
- 9. Result data types and precision
- 10. Practical reporting considerations
- 11. Common mistakes and interview checks
- 12. Validation and authoritative references
A SQL aggregate function summarizes a collection of input rows into one result value per group. Common aggregate functions include COUNT, SUM, AVG, MIN and MAX. For example, SUM(amount) calculates a total from the known amounts in a group of sales records, rather than returning the amount of every sale separately.
Without an explicit GROUP BY, an ordinary aggregate query treats its selected input as one group. With GROUP BY, the database can calculate a separate result for each group. An aggregate query can return several summary columns in the same result row. The essential idea is that the result describes a collection, not just an individual input record.
1. Why do we use aggregate functions?#
Imagine an application displaying a sales dashboard. The underlying table contains individual transactions. The dashboard needs a transaction count, total recorded sales amount, average recorded sale, lowest recorded sale and highest recorded sale. Returning every transaction to the application and calculating all the summaries there is usually unnecessary. SQL can calculate the summaries where the data is stored and return only the requested results.
Aggregates are useful in financial reports, inventory summaries, attendance counts, analytics, monitoring, data-quality checks and many other applications. Choosing an aggregate begins with defining what the result should mean. A transaction count is not necessarily a count of distinct customers, and a sum of recorded sales is not necessarily recognized revenue.
2. Five common SQL aggregate functions#
| Function | What it summarizes | Example use |
|---|---|---|
| COUNT(*) | Number of input rows | Number of transactions |
| COUNT(expression) | Number of non-NULL expression results | Number of recorded amounts |
| SUM(expression) | Total of non-NULL numeric values | Total recorded sales |
| AVG(expression) | Arithmetic mean of non-NULL numeric values | Average recorded sale |
| MIN(expression) | Smallest non-NULL comparable value | Lowest recorded amount |
| MAX(expression) | Largest non-NULL comparable value | Highest recorded amount |
These are frequently used aggregates, not an exhaustive list. PostgreSQL supports other aggregates, including array, string, Boolean and statistical aggregates. Their rules can differ. The five common aggregates above provide a useful foundation before learning specialized functions.
COUNT(*) is special syntax for counting input rows. The asterisk does not mean that all columns must be materialized or transferred to the client. For the other examples, the expression identifies what is being summarized. The expression may be a column or a suitable calculation, such as quantity multiplied by unit price.
3. A reproducible example dataset#
Use a small inline sales dataset with six records. Each record represents one transaction. The amount is a whole number in the same unit throughout this example; NULL means the amount has not been recorded, not that the transaction was worth zero.
| id | region | amount |
|---|---|---|
| 1 | North | 100 |
| 2 | North | 150 |
| 3 | North | NULL |
| 4 | South | 50 |
| 5 | South | 200 |
| 6 | West | NULL |
The examples below use a common table expression (CTE) with VALUES so that each query is independently executable in PostgreSQL without creating or modifying a permanent table. The explicit integer cast gives the missing amount a compatible type. The same query shapes work with ordinary tables when their columns have suitable types.
4. Summarize the entire input#
To compute the principal dashboard metrics in one query:
SQLWITH sales(id, region, amount) AS ( VALUES (1, 'North', 100), (2, 'North', 150), (3, 'North', NULL::integer), (4, 'South', 50), (5, 'South', 200), (6, 'West', NULL::integer) ) SELECT COUNT(*) AS rows, COUNT(amount) AS known, SUM(amount) AS total, AVG(amount) AS average, MIN(amount) AS minimum, MAX(amount) AS maximum FROM sales;
| rows | known | total | average | minimum | maximum |
|---|---|---|---|---|---|
| 6 | 4 | 500 | 125 | 50 | 200 |
The database returned one row with six summary columns. In the PostgreSQL result, the numeric average was represented as 125.0000000000000000; the table displays the equivalent value 125 for readability.
To understand the output, count the six transaction rows, then identify the four recorded amounts: 100, 150, 50 and 200. Their total is 500; dividing that total by four gives 125. The smallest recorded amount is 50 and the largest is 200. The two NULL values do not contribute to the sum, average or extrema, but their transaction rows still contribute to COUNT(*).
An aggregate query does not modify the original records. It produces a summarized result at a new level of detail. Here the result describes the entire selected set of transactions rather than a single transaction.
5. Aggregate functions with GROUP BY#
Suppose the dashboard needs a separate summary for each region. GROUP BY identifies groups according to the supplied grouping expressions, and each aggregate is evaluated over the input rows belonging to the respective group.
SQLWITH sales(id, region, amount) AS ( VALUES (1, 'North', 100), (2, 'North', 150), (3, 'North', NULL::integer), (4, 'South', 50), (5, 'South', 200), (6, 'West', NULL::integer) ) SELECT region, COUNT(*) AS rows, SUM(amount) AS total, AVG(amount) AS average FROM sales GROUP BY region ORDER BY region;
| region | rows | total | average |
|---|---|---|---|
| North | 3 | 250 | 125 |
| South | 2 | 250 | 125 |
| West | 1 | NULL | NULL |
The six input rows become three result rows. North has three transactions, two with recorded amounts. South has two transactions, both recorded. West contains one transaction with an unknown amount, so the group exists even though SUM and AVG return NULL. The total of 250 in each of North and South does not imply that their transaction counts are equal.
The diagram represents the logical grouping and summarization process. It does not assert a particular physical algorithm, such as sort-based or hash-based aggregation. ORDER BY makes the order of the three result rows explicit; GROUP BY itself does not guarantee result ordering.
Keep the grouping level aligned with the question. A region report groups by region, while a region-and-month report would group by both region and a suitable month expression. Adding a grouping column changes the possible number and meaning of result rows. Detailed grouping design and grouping rules are separate curriculum topics.
6. Filter rows before computing a summary#
Aggregate functions operate on the rows that reach them at their query level. To summarize just the North region without producing a separate row for every region, apply a WHERE condition first:
SQLWITH sales(id, region, amount) AS ( VALUES (1, 'North', 100), (2, 'North', 150), (3, 'North', NULL::integer), (4, 'South', 50), (5, 'South', 200), (6, 'West', NULL::integer) ) SELECT COUNT(*) AS rows, SUM(amount) AS total FROM sales WHERE region = 'North';
Result: one row with rows = 3 and total = 250. The other regions are excluded from the input. The count includes the North record whose amount is NULL.
WHERE selects input rows. HAVING selects groups after aggregation in the logical query model. For example, this query includes groups whose recorded total is at least 250:
SQLWITH sales(id, region, amount) AS ( VALUES (1, 'North', 100), (2, 'North', 150), (3, 'North', NULL::integer), (4, 'South', 50), (5, 'South', 200), (6, 'West', NULL::integer) ) SELECT region, SUM(amount) AS total FROM sales GROUP BY region HAVING SUM(amount) >= 250 ORDER BY region;
Result: North with total 250 and South with total 250. West does not pass because its total is NULL and the comparison is UNKNOWN. The threshold is a group-level rule rather than a condition on each individual transaction.
WHERE and HAVING are different stages; replacing one with the other can change the question being answered. For example, filtering out each small sale before summation is different from calculating the full total and then filtering small totals. A more detailed treatment of the distinction belongs to the WHERE/HAVING lesson. SQL describes the required result; the optimizer is free to choose an equivalent execution strategy.
7. What happens with NULL and empty input?#
The common aggregates do not all return zero when no numeric data is present. COUNT returns a count, while SUM, AVG, MIN and MAX return NULL on an empty input in PostgreSQL. The same latter functions also return NULL when the input contains rows but every relevant expression is NULL.
Consider a filter for East, which has no transactions in the dataset:
SQLWITH sales(id, region, amount) AS ( VALUES (1, 'North', 100), (2, 'North', 150), (3, 'North', NULL::integer), (4, 'South', 50), (5, 'South', 200), (6, 'West', NULL::integer) ) SELECT COUNT(*) AS rows, COUNT(amount) AS known, SUM(amount) AS total, AVG(amount) AS average, MIN(amount) AS minimum, MAX(amount) AS maximum FROM sales WHERE region = 'East';
| rows | known | total | average | minimum | maximum |
|---|---|---|---|---|---|
| 0 | 0 | NULL | NULL | NULL | NULL |
The ungrouped aggregate query returns one result row, even when no input rows qualify. That does not mean a transaction exists. It is a summary of the empty set. By contrast, an ordinary grouped query with no qualifying input has no groups to report:
SQLWITH sales(id, region, amount) AS ( VALUES (1, 'North', 100), (2, 'North', 150), (3, 'North', NULL::integer), (4, 'South', 50), (5, 'South', 200), (6, 'West', NULL::integer) ) SELECT region, SUM(amount) AS total FROM sales WHERE region = 'East' GROUP BY region;
Result: zero result rows. The distinction matters when building APIs and dashboards. An aggregate row containing NULL is different from an empty result set.
| Input condition | COUNT(*) | COUNT(amount) | SUM(amount) |
|---|---|---|---|
| Six transactions in the example | 6 | 4 | 500 |
| West group: one unknown amount | 1 | 0 | NULL |
| East filter: no input rows | 0 | 0 | NULL |
The West COUNT(amount) value follows directly from the documented non-NULL counting rule; the grouped query in section 5 tested the row count and total, not that additional count column.
An application may display zero for an empty total if that is the intended business interpretation, using an expression such as COALESCE(SUM(amount), 0). But a genuine absence of transactions and a set of transactions with unrecorded amounts can represent different conditions. Preserve a row count or known-value count when that difference matters. The COALESCE expression is an illustrative template, not a separately executed example here.
8. Aggregate versus ordinary per-row calculations#
An aggregate takes multiple input rows into account. An ordinary scalar expression calculates a result for an individual input row. Consider doubling each recorded amount:
SQLWITH sales(id, region, amount) AS ( VALUES (1, 'North', 100), (2, 'North', 150), (3, 'North', NULL::integer), (4, 'South', 50), (5, 'South', 200), (6, 'West', NULL::integer) ) SELECT id, amount, amount * 2 AS doubled FROM sales ORDER BY id;
| id | amount | doubled |
|---|---|---|
| 1 | 100 | 200 |
| 2 | 150 | 300 |
| 3 | NULL | NULL |
| 4 | 50 | 100 |
| 5 | 200 | 400 |
| 6 | NULL | NULL |
This query still returns six rows; it calculates one expression for each transaction. In contrast, the ungrouped SUM example returns one summary row. Both operations can be combined: SUM(amount * 2) would first evaluate the appropriate expression for each input and then summarize those results. That combined expression is illustrative.
A window function can also use an aggregate such as SUM(amount) OVER (...) while retaining individual result rows. This is a different query construct from ordinary grouped aggregation. Learn ordinary aggregate cardinality first; partitions, ordering and window frames belong to the window-function curriculum.
9. Result data types and precision#
An aggregate's result type is not necessarily the same as its argument type. PostgreSQL promotes certain numeric aggregate results to wider or different types. Verify the types rather than assuming every aggregate of an INTEGER column is an INTEGER.
SQLWITH sales(id, region, amount) AS ( VALUES (1, 'North', 100), (2, 'North', 150), (3, 'North', NULL::integer), (4, 'South', 50), (5, 'South', 200), (6, 'West', NULL::integer) ) SELECT pg_typeof(COUNT(*))::text AS count_type, pg_typeof(SUM(amount))::text AS sum_type, pg_typeof(AVG(amount))::text AS avg_type FROM sales;
| count_type | sum_type | avg_type |
|---|---|---|
| bigint | bigint | numeric |
The test confirms that PostgreSQL COUNT returns bigint, SUM of integer returns bigint, and AVG of integer returns numeric. Other input types can yield different output types, and database engines may have different promotion and overflow rules. Even widening does not imply an unlimited numeric range. Choose types appropriate to the data volume and precision requirements.
For financial totals, exact numeric types or appropriate integer minor units are usually preferable to approximate floating-point values when exact decimal or minor-unit calculations are required. Do not confuse display rounding with a change in the underlying mathematical definition of the aggregate. The detailed precision, rounding and currency policies depend on the application.
10. Practical reporting considerations#
Input grain: Know what one input row represents before counting or summing. A transaction table is different from a transaction-line table. If a join repeats a transaction once for each line, summing a transaction-level amount over that result may overcount the total. Correct the input grain rather than applying DISTINCT to arbitrary amounts: two valid sales can have the same amount.
Selection rules: Confirm the time range, status, currency and other filters before computing a business metric. A correct SUM expression can still answer the wrong business question if its input contains refunded transactions or incompatible currencies. Use explicit rules about missing data.
Output grain: Select grouping expressions and aggregates appropriate to the report. An arbitrary ungrouped nonaggregate column generally cannot be selected alongside a single summary in PostgreSQL unless an applicable grouping or functional-dependency rule makes it valid. Do not depend on permissive behavior in another database to choose an arbitrary representative row. A detailed treatment of grouping legality belongs to the GROUP BY lesson.
Performance: Aggregating in the database can reduce result size and network transfer but does not make the computation free. The engine may still need to read many rows, evaluate expressions, maintain aggregate state or group rows. An index can help some access paths and certain extrema queries, but an exact count or total over a large dataset is not generally a constant-time operation. No performance benchmark was performed here.
Supabase's official Inspect the database guide includes practical PostgreSQL aggregate expressions, including SUM over database statistics. Its examples illustrate why aggregation is useful in operational monitoring as well as business dashboards. This guide was consulted through the documentation connector; the PostgreSQL manual references listed below were not live fetched.
11. Common mistakes and interview checks#
| Mistake | Better approach |
|---|---|
| Expecting SUM to return each input amount | Select the amount column for individual rows |
| Assuming every aggregate ignores NULL in the same way | Distinguish COUNT(*) from expression aggregates |
| Treating unknown amounts as zero without a rule | Keep missing-value semantics explicit |
| Using a group threshold as a row filter | Use HAVING for the intended aggregate condition |
| Assuming an aggregate query must return one row | Account for grouping and window-function semantics |
| Expecting GROUP BY to guarantee order | Add ORDER BY when ordering matters |
| Summing repeated transaction values after a join | Check the input grain and join cardinality |
Interview-ready answer: A SQL aggregate function computes a summary over a set of rows. Common examples are COUNT for counting rows or non-NULL expressions, SUM for totals, AVG for arithmetic means, and MIN and MAX for extrema. An ordinary aggregate without GROUP BY produces a single summary row for the selected input, whereas GROUP BY produces a summary per group. Most of these functions ignore NULL arguments; COUNT(*) counts input rows, and common non-count aggregates return NULL on empty input. Aggregate functions are essential for reporting and analytics because they express the required summaries directly in SQL.
Quick checks: Can several aggregates appear in the same SELECT list? Yes. Does an ordinary SUM change stored rows? No. Does GROUP BY automatically sort the output? No. Does COUNT(*) over an empty input return NULL? No, it returns zero. Does SUM always return zero when no data matches? No, PostgreSQL returns NULL. Does an ordinary aggregate always preserve the number of input rows? No.
12. Validation and authoritative references#
Eight read-only PostgreSQL statements were executed using synthetic VALUES data: whole-input summaries, grouped summaries, WHERE filtering, ungrouped empty-input behavior, grouped empty-input behavior, per-row arithmetic, HAVING filtering and aggregate result-type inspection. All returned the displayed results. No permanent educational tables were created and no application data was read or modified. The Mermaid diagram was checked structurally and enclosed in an exact triple-backtick mermaid code block; full Mermaid parser validation and live public rendering were unavailable.
Live web browsing was unavailable under the established offline research exception. The Supabase Inspect the database guide was retrieved through the official documentation connector. The additional PostgreSQL references are authoritative reference destinations but were not independently fetched in this session. Illustrative expressions, other-engine behavior and performance claims were not benchmarked.
References
- 1.PostgreSQL — Aggregate Functionspostgresql.org
- 2.PostgreSQL — Tutorial: Aggregate Functionspostgresql.org
- 3.PostgreSQL — Table Expressionspostgresql.org
- 4.PostgreSQL — Aggregate Expressionspostgresql.org
- 5.PostgreSQL — Window Functionspostgresql.org
- 6.Supabase — Inspect the databasesupabase.com
Related questions
Explore other topics:Forward Deployed EngineeringPythonAI System DesignMachine Learning