Learn SQL/Advanced/Subqueries/SQL Scalar Subquery

SQL Scalar Subquery

A subquery that returns exactly one value — nothing more, nothing less.

What & Why

A scalar subquery is a subquery guaranteed to return a single row and a single column — one value. That's what lets it sit anywhere a literal number or string could go: after =, inside SELECT, even inside a calculation.

See How It Works

BUSINESS QUESTION

Show every campaign beside the overall average spend so analysts can compare the two directly.

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 one scalar value join every campaign rowStep 1 of 5
(SELECT ROUND(AVG(spend), 2) FROM marketing.campaigns) = 52,500.00
steprows readscalar result
inner aggregate4 campaign rows52,500.00

The inner aggregate reduces the four campaign spends to one scalar benchmark.

EXAMPLE QUERY
SELECT
  name,
  spend,
  (SELECT ROUND(AVG(spend), 2) FROM marketing.campaigns) AS overall_avg_spend
FROM marketing.campaigns
ORDER BY spend DESC, name;

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario