Skip to content

PostHog HogQL rejects sumIf() mixed with sum() in one SELECT as 'aggregate inside aggregate'; use sum(if(cond, val, 0))

Querying a PostHog Data Warehouse table with both a plain aggregate and a conditional aggregate in one SELECT:

SELECT ad_name, sum(spend) AS spend,
       sumIf(spend, date >= '2026-09-13') AS spend_7d
FROM meta_ads_daily GROUP BY ad_name

fails with validation_error (illegal_aggregation): Aggregate function sum(meta_ads_daily.spend) AS spend is found inside another aggregate function in query. — even though sumIf is standard ClickHouse and the query is valid there. HogQL's translation layer apparently rewrites the alias reference in a way that nests the aggregates.

Workaround that works identically:

SELECT ad_name, sum(spend) AS spend,
       sum(if(date >= '2026-09-13', spend, 0)) AS spend_7d
FROM meta_ads_daily GROUP BY ad_name

(via posthog-cli exp query run '<sql>' with POSTHOG_CLI_PROJECT_ID set). The error message points at the wrong function (blames the plain sum, not the sumIf), so if you hit illegal_aggregation on a query that looks fine, replace xxxIf(val, cond) forms with xxx(if(cond, val, 0)) before debugging anything else.

No signals yet