Learn SQL/Advanced/Subqueries/SQL Subquery in WHERE

SQL Subquery in WHERE

The most common home for a subquery — filtering rows using a value the query computes itself.

What & Why

A subquery inside WHERE computes something to filter against — a single number, or a whole list — before the outer query decides which rows survive.

See How It Works

BUSINESS QUESTION

Return campaigns whose spend is above the overall campaign average.

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
Watch a WHERE subquery calculate, compare, then filterStep 1 of 3
SELECT AVG(spend) FROM marketing.campaigns
inner input rowsaverage spend
4 campaigns52,500.00

The inner query resolves first and returns exactly one benchmark value.

EXAMPLE QUERY
SELECT
  id AS campaign_id,
  name,
  spend
FROM marketing.campaigns
WHERE spend > (
  SELECT AVG(spend)
  FROM marketing.campaigns
)
ORDER BY spend DESC, campaign_id;

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario