SQL HAVING

Filters GROUPS after aggregation — the tool that finally makes 'channels where the average spend exceeds X' possible.

What & Why

WHERE filters individual rows, and it runs before grouping even happens — which means WHERE has no way to reference an aggregate result like AVG(spend), since that value doesn't exist yet at the point WHERE runs. HAVING solves this: it filters groups, after aggregation has already been computed, so conditions like "keep only groups where the average exceeds 50000" become possible for the first time.

Think of it this way: WHERE decides which raw rows are even allowed into the grouping process. HAVING decides which already-formed, already-summarized groups make it into the final output. They operate at two completely different stages of the query.

See How It Works

BUSINESS QUESTION

Marketing wants only channels with meaningful spend.

idnamechannelspendstart_dateend_datestatustarget_segment
1Spring Launchgoogle_ads55000.002024-01-152024-03-31activesmb
2Retention Webinaremail45000.002024-02-102024-04-15activeenterprise
3Finance Retargetinglinkedin50000.002024-03-122024-05-31activeenterprise
4Enterprise Searchgoogle_ads60000.002024-04-012024-06-30activeenterprise
EXAMPLE QUERY
SELECT
  channel,
  ROUND(SUM(spend), 2) AS total_spend
FROM marketing.campaigns
GROUP BY channel
HAVING SUM(spend) >= 10000
ORDER BY total_spend DESC;
RESULT — exact output from the displayed Queryflo rows
channeltotal_spend
google_ads115000.00
linkedin50000.00
email45000.00

HAVING keeps all three completed channel totals because each exceeds 10,000.

Now You Try

Practice this concept

Marketing wants campaign channels whose total spend is at least 10,000. Return channel and total_spend, ordered from highest total spend to lowest.

Available schema
marketing

Prefix tables with marketing.table_name.

channeltotal_spend
marketing.campaigns
ColumnType
idinteger
nametext
channeltext
spendnumeric
start_datedate
end_datedate
statustext
target_segmenttext
legacy_idtext
query.sql
Intermediate business practice

Sign up free to try it on a real business scenario