Learn SQL/Advanced/Subqueries/SQL Non-Correlated Subquery

SQL Non-Correlated Subquery

Runs once, independently — the far more common case, and the opposite of correlated.

What & Why

A non-correlated subquery doesn't reference anything from the outer query — it's a complete, independent question that runs exactly once, and every outer row compares against that same single answer.

Nearly every subquery in this series so far has been non-correlated. The correlated subquery lesson is the exception, not the rule.

See How It Works

BUSINESS QUESTION

Marketing wants campaigns above one global spend benchmark.

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
  id AS campaign_id,
  name,
  spend
FROM marketing.campaigns
WHERE spend > (SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY spend) FROM marketing.campaigns)
ORDER BY spend DESC, campaign_id;
RESULT — spend above the 52,500 median
campaign_idnamespend
4Enterprise Search60000.00
1Spring Launch55000.00

The independent subquery calculates the campaign-spend median once.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario