Learn SQL/Advanced/Subqueries/SQL Subquery Basics

SQL Subquery Basics

SQL Subquery Basics helps analysts nest one SELECT inside another query and use its result as an input.

What & Why

Every subquery follows three mechanical rules: it's wrapped in parentheses, it runs to completion before the outer query uses its result, and it returns one of three shapes — a single value, a single column of many rows, or a whole table — which determines where it's allowed to appear.

See How It Works

BUSINESS QUESTION

Marketing wants campaigns whose spend is above the overall 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
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;
RESULT — campaigns above average
campaign_idnamespend
4Enterprise Search60000.00
1Spring Launch55000.00

The average of the four representative campaign spends is 52,500.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario