Learn SQL/Advanced/Subqueries/SQL Subquery in SELECT

SQL Subquery in SELECT

A subquery used to compute one extra column, not to filter anything.

What & Why

A subquery can sit directly inside the SELECT list to add a computed column — as long as it returns a single value. It doesn't filter rows; it just adds information to each one.

See How It Works

BUSINESS QUESTION

Marketing wants every campaign beside overall average campaign 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
  id AS campaign_id,
  name,
  spend,
  (SELECT ROUND(AVG(spend), 2) FROM marketing.campaigns) AS overall_avg_spend
FROM marketing.campaigns
ORDER BY spend DESC, campaign_id;
RESULT — one scalar beside every campaign
campaign_idnamespendoverall_avg_spend
4Enterprise Search60000.0052500.00
1Spring Launch55000.0052500.00
3Finance Retargeting50000.0052500.00
2Retention Webinar45000.0052500.00

The scalar average repeats without changing campaign grain.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario