Learn SQL/Advanced/Subqueries/Writing Subqueries in SQL

Writing Subqueries in SQL

A query inside a query — used whenever the answer to your question depends on another question first.

What & Why

A subquery is a complete SQL query nested inside another query, wrapped in parentheses. The database runs the inner query first, then uses its result to help answer the outer one.

Subqueries can appear in three places: inside WHERE (to filter), inside SELECT (to compute a value), or inside FROM (as a stand-in table). This lesson series covers all three.

See How It Works

BUSINESS QUESTION

Marketing wants campaigns whose spend is above the overall campaign 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
  name,
  channel,
  spend
FROM marketing.campaigns
WHERE spend > (
  SELECT AVG(spend)
  FROM marketing.campaigns
)
ORDER BY spend DESC, name;
RESULT — campaigns above the 52,500 average
namechannelspend
Enterprise Searchgoogle_ads60000.00
Spring Launchgoogle_ads55000.00

The scalar subquery returns 52,500 before the outer query filters campaign rows.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario