Learn SQL/Advanced/Subqueries/SQL Subquery in FROM

SQL Subquery in FROM

A subquery that acts as a temporary table — the outer query just selects from it.

What & Why

A subquery in FROM — sometimes called a derived table — produces a full result set that the outer query treats like any other table. It must be given an alias.

See How It Works

BUSINESS QUESTION

Marketing wants channel summaries whose average spend exceeds 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
  summary.channel,
  summary.avg_spend
FROM (
  SELECT channel, ROUND(AVG(spend), 2) AS avg_spend
  FROM marketing.campaigns
  GROUP BY channel
) AS summary
WHERE summary.avg_spend > (SELECT AVG(spend) FROM marketing.campaigns)
ORDER BY summary.avg_spend DESC, summary.channel;
RESULT — channel summaries above the overall average
channelavg_spend
google_ads57500.00

Only the google_ads channel average exceeds the overall 52,500 campaign average.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario