SQL Aggregate Functions: COUNT, SUM, AVG, MIN and MAX
How SQL's aggregate functions turn many rows into one value: COUNT(*) versus COUNT(column), DISTINCT inside aggregates, how NULLs are skipped, empty inputs, integer averages, result types, and the errors you get when mixing aggregates with plain columns.
kvi5hnuCode Sprout team member18 min readOn this page
Every query so far has returned rows that came from rows: one output row per product, per order or per matching pair. Many questions need a single number instead. How many products are there? What's the total revenue? What's the average price? When was the first order placed? Aggregate functions answer them. They take a set of rows and return one value computed from all of them.
This article covers the five aggregates that every SQL database has, COUNT, SUM, AVG, MIN and MAX, and the details that trip people up: how they treat NULLs, what they return when there are no rows, why an average can come out as a whole number, and why SELECT name, MAX(price) is an error. The next article adds GROUP BY, which runs the same functions once per group instead of once for the whole table.
The examples use the products table from Part 2. Its seven rows include a lantern with no brand and no recorded weight, which is exactly what makes aggregates interesting.
A summary query returns one row
A query whose SELECT list contains aggregate functions and has no GROUP BY is a summary query. It treats all the rows that pass WHERE as one group and returns exactly one row:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
\pset null '(null)'
-- Seven products; one of them (the lantern) has no recorded weight
SELECT COUNT(*) AS all_rows,
COUNT(weight_g) AS with_weight,
COUNT(brand) AS with_brand,
COUNT(DISTINCT brand) AS distinct_brands,
SUM(weight_g) AS total_weight,
ROUND(AVG(weight_g), 2) AS avg_weight,
MIN(weight_g) AS lightest,
MAX(weight_g) AS heaviest
FROM products;
all_rows | with_weight | with_brand | distinct_brands | total_weight | avg_weight | lightest | heaviest
----------+-------------+------------+-----------------+--------------+------------+----------+----------
7 | 6 | 6 | 4 | 8360 | 1393.33 | 80 | 4300
(1 row)
Read each column against the table:
COUNT(*)counts rows. There are 7, and it doesn't matter what's in them.COUNT(weight_g)counts rows whereweight_gis not NULL. The lantern has no weight, so the answer is 6.COUNT(brand)is 6 for the same reason: the lantern has no brand.COUNT(DISTINCT brand)counts the different non-null brands: Alpina, Lumen, Kestrel and Woolly. Alpina and Kestrel each appear twice but are counted once.SUM(weight_g)adds the six known weights.AVG(weight_g)divides that sum by 6, the number of non-null values, not by 7.MINandMAXreturn the smallest and largest non-null values.

The rule that ties all of this together:
Every aggregate function ignores NULL inputs, except
COUNT(*), which counts rows rather than values.
Where the aggregate runs in the query
In the logical processing order from article 4, FROM and WHERE run first, then the rows are grouped, then aggregates are computed, then SELECT produces the output. So WHERE decides which rows the aggregates see:
SELECT COUNT(*), AVG(price)
FROM products
WHERE category = 'tents'; -- counts and averages only the two tents
This order also explains two of the errors later in this article: WHERE can't use an aggregate because the aggregate hasn't been computed yet when WHERE runs.
COUNT in all its forms
COUNT has more variations than the other aggregates, and each answers a different question.
| Form | Counts | On the products table |
|---|---|---|
COUNT(*) | rows | 7 |
COUNT(brand) | rows where brand is not NULL | 6 |
COUNT(DISTINCT brand) | different non-null values of brand | 4 |
COUNT(1) | rows (the constant 1 is never NULL) | 7 |
COUNT(NULL) | nothing: the argument is always NULL | 0 |
COUNT(ALL brand) | same as COUNT(brand); ALL is the default | 6 |
COUNT(*) or COUNT(1)?
They return the same number, and the difference in speed is negligible in PostgreSQL, Oracle, SQL Server, MySQL and SQLite (in PostgreSQL, COUNT(*) is in fact slightly faster, because COUNT(1) checks its argument for NULL on every row). The belief that COUNT(1) is faster because it "doesn't read the columns" is a myth: COUNT(*) doesn't read the columns either, the * here doesn't mean "all columns". Write COUNT(*), which says "count rows" most clearly.
COUNT(column) as a NULL detector
Because COUNT(column) skips NULLs, COUNT(*) - COUNT(column) is the number of NULLs in that column:
SELECT COUNT(*) - COUNT(weight_g) AS missing_weights FROM products; -- 1
The same skipping is a trap when you meant to count rows. If you write COUNT(brand) to count products, you get 6, silently leaving out the unbranded lantern. Count a column only when "rows where this column is known" is what you mean.
Counting distinct combinations
COUNT(DISTINCT ...) takes one expression in standard SQL. To count distinct pairs, there are a few options:
- MySQL accepts several arguments:
COUNT(DISTINCT category, brand). It skips any row where one of them is NULL, so on this table it returns 4. - PostgreSQL accepts a row value:
COUNT(DISTINCT (category, brand)). A row value is NULL only when all its fields are NULL, so the lantern's(lighting, NULL)is counted, and the result is 5. - Everywhere, you can count the rows of a distinct subquery, which makes the NULL handling explicit:
SELECT COUNT(*)
FROM (SELECT DISTINCT category, brand FROM products) AS pairs; -- 5: DISTINCT keeps (lighting, NULL)
Concatenating the columns, as in COUNT(DISTINCT category || brand), is a common workaround but a fragile one: 'ab' || 'c' and 'a' || 'bc' give the same string, and || with a NULL yields NULL, which is then skipped.
SUM and AVG
SUM adds values and AVG averages them. Both need numeric input, or input that the database can convert to a number. Both skip NULLs, which has a consequence that's easy to miss:
AVG(x)isSUM(x) / COUNT(x), notSUM(x) / COUNT(*).
For the weights, that's 8360 / 6 = 1393.33. If a missing weight should count as zero, you have to say so: AVG(COALESCE(weight_g, 0)) gives 8360 / 7 = 1194.29. Which one is right depends on what NULL means in your data. "Not measured yet" usually means skip it, which is what AVG does. "Nothing was sold" might mean zero.
What aggregates return when there are no rows
A summary query without GROUP BY returns one row even when no rows match. What's in that row is defined by the SQL standard:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
\pset null '(null)'
-- No product costs more than 1000, yet the query still returns one row
SELECT COUNT(*) AS how_many,
SUM(price) AS total,
AVG(price) AS average,
MAX(price) AS highest
FROM products
WHERE price > 1000;
-- COALESCE turns the empty-input NULL into a 0 when 0 is the right answer
SELECT COALESCE(SUM(price), 0) AS total
FROM products
WHERE price > 1000;
how_many | total | average | highest
----------+--------+---------+---------
0 | (null) | (null) | (null)
(1 row)
total
-------
0
(1 row)
COUNT returns 0, because zero rows were counted. SUM, AVG, MIN and MAX return NULL, because there's no value to report: the maximum of nothing isn't 0, and the average of nothing can't be computed. SUM also returns NULL rather than 0, which surprises many people. If 0 is the right answer for your report, wrap it in COALESCE, as the second query does.
SUM and AVG also return NULL when there are rows but every value is NULL, for the same reason: there's nothing to add.
Integer averages
What type does an aggregate return? The answer differs between databases, and it matters most for averages of integer columns:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- Average stock per product, three ways
SELECT SUM(stock) / COUNT(*) AS integer_division,
SUM(stock) * 1.0 / COUNT(*) AS forced_decimal,
AVG(stock) AS avg_function,
ROUND(AVG(stock), 1) AS rounded
FROM products;
-- The result types PostgreSQL picks
SELECT pg_typeof(COUNT(*)) AS count_type,
pg_typeof(SUM(stock)) AS sum_of_integer,
pg_typeof(AVG(stock)) AS avg_of_integer,
pg_typeof(SUM(price)) AS sum_of_decimal
FROM products;
integer_division | forced_decimal | avg_function | rounded
------------------+---------------------+---------------------+---------
23 | 23.8571428571428571 | 23.8571428571428571 | 23.9
(1 row)
count_type | sum_of_integer | avg_of_integer | sum_of_decimal
------------+----------------+----------------+----------------
bigint | bigint | numeric | numeric
(1 row)
SUM(stock) / COUNT(*) is integer divided by integer, and in PostgreSQL, SQL Server and SQLite, integer division throws away the fraction: 167 / 7 is 23. Multiplying by 1.0 first, or casting to a decimal type, gives the exact answer. AVG does this for you in PostgreSQL, which returns numeric for the average of integers.
Not every database does. Here's the result type of AVG over an integer column in each:
| Database | AVG(int_column) returns | AVG(stock) here |
|---|---|---|
| PostgreSQL | numeric, full precision | 23.8571428571428571 |
| Oracle | NUMBER, full precision | 23.857142857142857... |
| MySQL | DECIMAL, 4 extra decimal places by default | 23.8571 |
| SQLite | floating point | 23.8571428571429 (as displayed) |
| SQL Server | int, truncated | 23 |
SQL Server's behaviour catches people moving from other databases. Write AVG(CAST(stock AS DECIMAL(10, 2))) or AVG(stock * 1.0) there when you want the fraction.
In MySQL, / never truncates (dividing two integers gives a decimal) and DIV is the integer division operator, so SUM(stock) / COUNT(*) gives 23.8571 rather than 23. That's another reason to check, rather than assume, how division behaves in the database you're using. Article 38 covers division and rounding in depth.
Overflow
SUM can produce a number larger than any input. PostgreSQL protects you by widening the type: SUM of integer returns bigint, and SUM of bigint returns numeric, so it practically can't overflow. SQL Server doesn't widen: SUM of an int column returns int, and a total above about 2.1 billion fails with an arithmetic overflow error. The fix there is SUM(CAST(col AS BIGINT)). Similarly, SQL Server's COUNT returns int, and COUNT_BIG exists for tables with more than about 2.1 billion rows. MySQL returns DECIMAL from SUM of integers, which doesn't overflow in practice.
Rounding the result
An average usually has more decimal places than you want to show. Round it in the final SELECT, not before aggregating:
ROUND(AVG(price), 2) -- round the average: correct
AVG(ROUND(price, 0)) -- average of rounded prices: a different number
Rounding each value before adding loses accuracy in every row. Rounding the result loses it once.
MIN and MAX
MIN and MAX work on any type that can be sorted: numbers, dates and timestamps, and text. For text, "smallest" means first in the column's collation, the same ordering ORDER BY uses, so the result can depend on the collation, as article 9 explained.
MIN and MAX can also be used on columns that SUM and AVG can't touch, as in this query on the order tables:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Sales figures from the order lines: aggregate an expression, not just a column
SELECT COUNT(*) AS order_lines,
COUNT(DISTINCT order_id) AS orders_with_lines,
COUNT(DISTINCT product_id) AS products_sold,
SUM(qty) AS units,
SUM(qty * unit_price) AS revenue,
ROUND(AVG(qty * unit_price), 2) AS avg_line_value
FROM order_items;
-- MIN and MAX work on dates and text too
SELECT MIN(placed_on) AS first_order,
MAX(placed_on) AS last_order,
MAX(placed_on) - MIN(placed_on) AS days_between,
COUNT(customer_id) AS orders_by_customers,
COUNT(DISTINCT customer_id) AS distinct_customers
FROM orders;
order_lines | orders_with_lines | products_sold | units | revenue | avg_line_value
-------------+-------------------+---------------+-------+---------+----------------
9 | 6 | 6 | 13 | 1080.44 | 120.05
(1 row)
first_order | last_order | days_between | orders_by_customers | distinct_customers
-------------+------------+--------------+---------------------+--------------------
2026-03-02 | 2026-03-22 | 20 | 5 | 4
(1 row)
The first query aggregates an expression: SUM(qty * unit_price) multiplies each line's quantity by its price and adds the products. The argument of an aggregate can be any expression that doesn't itself contain an aggregate. It also uses COUNT(DISTINCT order_id) to count orders in a table that has one row per order line, which is the safe way to count the "one" side after rows have been multiplied.
The second query shows MIN and MAX on dates, and the difference between them. It also shows two counts on orders that differ for different reasons: there are 6 orders, but COUNT(customer_id) is 5 because the guest order has a NULL customer, and COUNT(DISTINCT customer_id) is 4 because Asha placed two orders.
MIN and MAX return a value, not a row
MAX(price) tells you the highest price, 489.00. It doesn't tell you which product has that price. Getting the row that holds the maximum is a separate problem, with several solutions covered in articles 22, 27 and 47. The simplest compares each row with the aggregate in a subquery, which you'll see in the next section.
Two errors everyone makes
The two most common aggregate mistakes both come from wanting the aggregate and some row-level detail at the same time:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- Mistake 1: a plain column next to an aggregate
SELECT name, MAX(price) FROM products;
-- Mistake 2: an aggregate in WHERE
SELECT name, price FROM products WHERE price = MAX(price);
-- The fix: compute the aggregate in a subquery, then compare with it
SELECT name, price
FROM products
WHERE price = (SELECT MAX(price) FROM products);
psql:/workspace/solution.sql:20: ERROR: column "products.name" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT name, MAX(price) FROM products;
^
psql:/workspace/solution.sql:23: ERROR: aggregate functions are not allowed in WHERE
LINE 1: SELECT name, price FROM products WHERE price = MAX(price);
^
name | price
---------------+--------
Summit 4 tent | 489.00
(1 row)
A plain column next to an aggregate
SELECT name, MAX(price) FROM products asks for one row (the aggregate collapses seven rows into one) and also for name, which has seven different values. Which name should appear? SQL refuses to guess and reports an error: the column must either be listed in GROUP BY or be inside an aggregate function.
The rule, which you'll meet again in the next article, is:
In a query with aggregates, every column in
SELECTmust either be inside an aggregate function or be one of the grouping columns.
Without GROUP BY there are no grouping columns, so every column reference must be inside an aggregate.
Older versions of MySQL accepted this query and returned the name from some arbitrary row, not necessarily the row with the maximum price. Since MySQL 5.7 the ONLY_FULL_GROUP_BY mode is on by default and MySQL rejects the query too. If you find code that relies on the old behaviour, it's a bug waiting to happen.
An aggregate in WHERE
WHERE price = MAX(price) fails because WHERE filters individual rows before any aggregation has happened. At that point, there's no MAX to compare with. The fix is to compute the aggregate separately, in a subquery, and compare each row with its result. That's the third query: the subquery (SELECT MAX(price) FROM products) returns 489.00, and the outer query keeps the rows with that price. If two products shared the top price, both would be returned. Subqueries get a full article of their own in Part 5.
Conditions on aggregate results do have a place: the HAVING clause, which filters after aggregation. It's covered in the next article.
Aggregates can't be nested directly
AVG(COUNT(*)) is an error in standard SQL and in PostgreSQL: "aggregate function calls cannot be nested". To average per-customer order counts, compute the counts in a subquery and average its result:
SELECT AVG(order_count)
FROM (SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id) AS per_customer;
Oracle is the exception: it allows one level of nesting, as in SELECT AVG(COUNT(*)) FROM orders GROUP BY customer_id, where the inner aggregate runs per group and the outer one over the groups' results. It's non-standard and works nowhere else, so prefer the subquery.
DISTINCT inside an aggregate
DISTINCT can go inside any aggregate, not just COUNT. It removes duplicate values before the function sees them:
SELECT SUM(DISTINCT price) FROM products; -- adds each different price once
SELECT AVG(DISTINCT stock) FROM products;
With COUNT, it's very useful. With SUM and AVG it's rarely what you want, because two rows that happen to have the same value are different facts. If two products both cost 16.00, SUM(DISTINCT price) counts that 16.00 once, so the total is wrong. Article 17 showed the same problem when SUM(DISTINCT ...) is used to patch over join fan-out. MIN(DISTINCT x) and MAX(DISTINCT x) are allowed but pointless, since duplicates can't change a minimum or a maximum.
More aggregate functions
The five basics are in every database. Most databases have more, though names and syntax vary:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
-- Aggregates beyond the big five (PostgreSQL names; other databases differ)
SELECT BOOL_AND(stock > 0) AS all_in_stock,
BOOL_OR(stock = 0) AS any_sold_out,
STRING_AGG(name, ', ' ORDER BY price) AS cheapest_first,
ARRAY_AGG(DISTINCT category ORDER BY category) AS categories
FROM products;
-- A trimmed average: drop the single cheapest and single dearest product
SELECT ROUND(AVG(price), 2) AS plain_avg,
ROUND((SUM(price) - MIN(price) - MAX(price)) / (COUNT(*) - 2), 2) AS trimmed_avg
FROM products;
all_in_stock | any_sold_out | cheapest_first | categories
--------------+--------------+------------------------------------------------------------------------------------------------------------------+---------------------------------
f | t | Merino socks, Basecamp lantern, Glow head torch, Day 18 backpack, Trail 30 backpack, Ridge 2 tent, Summit 4 tent | {clothing,lighting,packs,tents}
(1 row)
plain_avg | trimmed_avg
-----------+-------------
137.21 | 91.09
(1 row)
BOOL_ANDandBOOL_OR(PostgreSQL) answer "is this true for every row?" and "is it true for any row?". The standard name forBOOL_ANDisEVERY, which PostgreSQL also accepts. Elsewhere, writeMIN(CASE WHEN stock > 0 THEN 1 ELSE 0 END) = 1for "all" andMAX(...) = 1for "any".STRING_AGGjoins strings with a separator, in an order you choose. The name differs by database:STRING_AGGin PostgreSQL and SQL Server,LISTAGGin Oracle, andGROUP_CONCATin MySQL and SQLite, which also supportsSTRING_AGGfrom version 3.44. Article 37 covers them in detail.ARRAY_AGG(PostgreSQL and others) collects values into an array, andJSON_AGGorJSON_ARRAYAGGinto a JSON array (article 43).- Statistical aggregates such as
STDDEV,VARIANCE,CORRand the ordered-set aggregatesPERCENTILE_CONTandMODEgive the median, percentiles and the most common value. Article 38 covers them. ANY_VALUE(x)returns the value ofxfrom some row in the group, without promising which one. It's in the SQL standard, PostgreSQL 16 and later, MySQL, Oracle, Snowflake and BigQuery. It's useful when you know all the rows have the same value, which is a situation the next article explains.
The second query computes a trimmed average, which ignores the extremes. The plain average price is pulled up by the 489.00 tent. Dropping the cheapest and the most expensive product and averaging the other five gives 91.09, closer to a "typical" price. This version drops exactly one row at each end; if several products shared the lowest price, only one of them would be dropped. Window functions (Part 6) and percentiles (article 38) give more robust ways to discount outliers.
Aggregates and performance
A few facts that are useful when tables get large:
MINandMAXon an indexed column are almost free. The database reads one end of the index instead of the whole table.COUNT(*)on a whole table is not free in PostgreSQL. Because of how PostgreSQL handles concurrent transactions (article 61), different transactions can see different row counts, so there's no stored total. It has to count, though it can use an index-only scan. If an approximate figure is enough, the planner's estimate inpg_class.reltuplesis instant. MySQL's InnoDB engine also counts rather than storing a total.- To check whether any row exists, don't count them all.
WHERE EXISTS (...)orLIMIT 1stops at the first match, whileCOUNT(*) > 0has to count every match first. COUNT(DISTINCT ...)on large inputs is expensive, because it has to sort or hash every value. Some systems offer fast approximate versions, such asAPPROX_COUNT_DISTINCTin Oracle and SQL Server.
What's current
ANY_VALUEwas standardized in SQL and added in PostgreSQL 16.- SQLite 3.44 (November 2023) added
STRING_AGGandORDER BYinside aggregate calls, as inGROUP_CONCAT(name ORDER BY name). - MySQL has had
ONLY_FULL_GROUP_BYon by default since 5.7, so the "arbitrary row" behaviour ofSELECT name, MAX(price)only appears when someone has turned the mode off. - The core behaviour of
COUNT,SUM,AVG,MINandMAX, including skipping NULLs and the empty-input results, has been fixed by the standard for decades and is the same in every major database. What still differs is the result type, as the table in theAVGsection shows.
Common questions
Why does SUM return NULL instead of 0 when no rows match?
Because the standard defines the sum of no values as unknown rather than zero. COUNT is the only aggregate that returns 0 for empty input. Use COALESCE(SUM(x), 0) when 0 is the right answer.
Does COUNT(column) count duplicates?
Yes. It counts every non-null value, duplicates included. Use COUNT(DISTINCT column) to count different values.
Is COUNT(1) faster than COUNT(*)?
No. Every major database treats them the same way. Use COUNT(*).
Does AVG treat NULL as zero?
No, it skips NULLs, so they don't count in the divisor either. Use AVG(COALESCE(x, 0)) if a missing value should count as zero.
Can I use MAX on text?
Yes. MIN and MAX work on any sortable type, and for text they follow the column's collation.
Why does my average come out as a whole number?
You're probably dividing integers, as in SUM(x) / COUNT(*), or using SQL Server, where AVG of an integer column returns an integer. Multiply by 1.0 or cast to a decimal type before dividing or averaging.
Can I put an aggregate in WHERE?
No. WHERE runs before aggregation. Use HAVING to filter on an aggregate's result (next article), or compute the aggregate in a subquery and compare with it.
Why can't I select name together with MAX(price)?
Because the aggregate collapses all rows into one and SQL doesn't know which row's name to show. To get the row that holds the maximum, compare with a subquery, as shown above, or use the techniques in articles 27 and 47.
Can an aggregate's argument be an expression?
Yes, any expression that doesn't contain another aggregate: SUM(qty * unit_price), MAX(LENGTH(name)), COUNT(CASE WHEN stock = 0 THEN 1 END). That last pattern is the subject of article 21.
What happens to an aggregate when its argument is a constant, like SUM(1)?
It's evaluated once per row, so SUM(1) counts rows, just like COUNT(*), except that it returns NULL instead of 0 when there are no rows.
Summary
- Aggregate functions turn a set of rows into one value. A query with aggregates and no
GROUP BYreturns exactly one row, even when no rows match. - All aggregates skip NULLs except
COUNT(*), which counts rows. SoAVG(x)divides byCOUNT(x), not by the number of rows. - On no rows,
COUNTreturns 0 and the others return NULL. WrapSUMinCOALESCEwhen you need 0. COUNT(DISTINCT x)counts different non-null values.DISTINCTinSUMorAVGis usually a mistake.- Integer division and SQL Server's integer
AVGdrop fractions. Convert to a decimal type first when the fraction matters. MINandMAXwork on numbers, dates and text, and return a value, not the row that holds it.- A plain column can't appear next to an aggregate unless it's a grouping column, aggregates aren't allowed in
WHERE, and aggregates can't be nested. Use a subquery for each of these needs.
Practice questions
The products table has 7 rows, and weight_g is NULL for one of them. What do COUNT(*), COUNT(weight_g) and COUNT(DISTINCT category) return? The categories are tents, tents, lighting, lighting, packs, packs and clothing.
Answer
COUNT(*) returns 7, because it counts rows. COUNT(weight_g) returns 6, because the NULL is skipped. COUNT(DISTINCT category) returns 4: tents, lighting, packs and clothing.
A query returns SUM(amount) from payments WHERE order_id = 999, and no payments exist for order 999. What is the result, and how would you make it show 0?
Answer
One row with NULL. SUM over no rows is NULL, not 0. Write SELECT COALESCE(SUM(amount), 0) FROM payments WHERE order_id = 999; to get 0.
A column rating holds the values 4, 5, NULL and 3. What do AVG(rating) and AVG(COALESCE(rating, 0)) return, and when is each right?
Answer
AVG(rating) is (4 + 5 + 3) / 3 = 4, because the NULL is skipped and the divisor is 3. AVG(COALESCE(rating, 0)) is 12 / 4 = 3. The first is right when NULL means "not rated", which shouldn't drag the average down. The second is right only if a missing rating really means a rating of 0.
Write a query that returns the name and price of the cheapest product. Explain why SELECT name, MIN(price) FROM products doesn't work.
Answer
SELECT name, price
FROM products
WHERE price = (SELECT MIN(price) FROM products);
It returns Merino socks at 16.00. SELECT name, MIN(price) FROM products is rejected because the aggregate collapses the table to one row and name isn't aggregated or grouped, so SQL can't know which name to show. MIN(price) gives a value, not the row it came from.
In SQL Server, SELECT AVG(stock) FROM products returns 23 although the true average is 23.857. Why, and how do you fix it?
Answer
In SQL Server, AVG of an int column returns int, so the fraction is discarded. Convert the values first: SELECT AVG(CAST(stock AS DECIMAL(10, 2))) FROM products; or SELECT AVG(stock * 1.0) FROM products;. PostgreSQL, Oracle and MySQL already return a decimal result for AVG of integers.
Write one query on order_items(order_id, product_id, qty, unit_price) that returns the number of order lines, the number of different orders, and the total revenue.
Answer
SELECT COUNT(*) AS order_lines,
COUNT(DISTINCT order_id) AS orders,
SUM(qty * unit_price) AS revenue
FROM order_items;
On the course's shop data, this returns 9 lines, 6 orders and 1080.44. COUNT(DISTINCT order_id) is needed because an order with several lines appears several times.
Previous: SQL Join Pitfalls: Fan-Out, Duplicates and Comparing Two Tables

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.