BigQuery error · Query and syntax errors
Aggregate function not allowed in WHERE clause
An aggregate such as SUM, COUNT or MAX is used in WHERE, which filters rows before they are grouped. Move the condition to HAVING, which filters groups after aggregation, or aggregate in a subquery and filter in the outer query.
The error message
Aggregate function <FUNCTION> not allowed in WHERE clause at [<line>:<column>]
Causes
Filtering groups with WHERE
WHERE SUM(amount) > 100 ... GROUP BY customer_id fails with Aggregate function SUM not allowed in WHERE clause. WHERE decides which rows enter the groups, so group totals don't exist yet.
Comparing rows with a total
Conditions such as WHERE amount > AVG(amount) try to compare each row with an aggregate over all rows. That needs the aggregate computed first, in a subquery or as a window function.
Aggregates in GROUP BY
The same rule applies to GROUP BY, where the message reads like Aggregate function COUNT(*) not allowed in GROUP BY. Group by the plain columns and put the aggregate in the SELECT list.
How to fix it
1. Move the condition to HAVING
Keep row filters in WHERE and group filters in HAVING. HAVING can repeat the aggregate or use its SELECT alias.
WITH orders AS (
SELECT 'c1' AS customer_id, DATE '2026-11-02' AS order_date, 120.0 AS amount UNION ALL
SELECT 'c1', DATE '2026-11-05', 15.0 UNION ALL
SELECT 'c2', DATE '2026-11-03', 40.0
)
SELECT customer_id, SUM(amount) AS revenue
FROM orders
WHERE order_date >= '2026-11-01'
GROUP BY customer_id
HAVING SUM(amount) > 100;2. Compare rows with an aggregate using a window function
To keep rows above the average, compute the average with OVER () and filter with QUALIFY.
WITH orders AS (
SELECT 1 AS order_id, 120.0 AS amount UNION ALL
SELECT 2, 15.0 UNION ALL
SELECT 3, 40.0
)
SELECT order_id, amount
FROM orders
WHERE TRUE
QUALIFY amount > AVG(amount) OVER ();How to prevent it
- Filter as many rows as possible in WHERE, especially on partition and cluster columns, before aggregating: that reduces bytes billed and slot time, while HAVING only filters the already aggregated result.
- Dry-run reports in CI; this error is caught during analysis, for free.
FAQ
What is the difference between WHERE and HAVING in BigQuery?
WHERE filters rows before GROUP BY and can't use aggregates. HAVING filters groups after aggregation and can. A condition on a plain column belongs in WHERE, where it also reduces the data processed.
Can HAVING use the SELECT alias in BigQuery?
Yes. HAVING revenue > 100 works when revenue is defined as SUM(amount) in the SELECT list.
Is a query that fails with this error billed?
No. It fails during analysis, before reading data, so nothing is billed on-demand and no slot time is used under editions.
Related
SQL reference
More query and syntax errors
All BigQuery error messages · What 50M daily events say about BigQuery failures
