σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
SQL skill›Module 2 · Prices over time›Topic 2.2·~40 minIntermediate

CTEs and subqueries

Skill positionModule 2 of 3 · Topic 2 of 4
2.2 CTEs and subqueries
—Lab score— / 100Total XP—Streak—
Lecture0% read

3 min readCode examples: 4

  1. 01The idea in plain words
  2. 02Name a result, then filter it
  3. 03Subqueries as values and lists
  4. 04Chaining CTEs
  5. 05What the tasks ask

"Show me the days a stock fell more than 10%" sounds like one filter, but the return does not exist as a column: it has to be computed from yesterday's close first. A query that needs a result before it can filter it is what CTEs and subqueries are for.

01

The idea in plain words

Where we are. Topic 5 computed per-row values from neighbouring rows, and noted that WHERE cannot see them. Here you learn the general fix: compute in an inner query, filter in the outer one. The next topic uses the same idea for joins on time.

DefinitionCTE

A common table expression: WITH name AS (query) gives a query result a name that the rest of the statement reads like a table. Several can be chained with commas, each seeing the ones before it.

02

Name a result, then filter it

main.pyPython
# A CTE names the returns; the outer query filters on themprint(con.sql("""    WITH r AS (1        SELECT symbol, date, close / lag(close) OVER (PARTITION BY symbol ORDER BY date) - 1 AS ret        FROM bars    )    SELECT symbol, date, round(ret, 3) AS ret    FROM r2    WHERE ret <= -0.1    ORDER BY ret    LIMIT 4"""))
┌─────────┬────────────┬────────┐
│ symbol  │    date    │  ret   │
│ varchar │    date    │ double │
├─────────┼────────────┼────────┤
│ AAPL    │ 2000-09-29 │ -0.518 │
│ JPM     │ 2009-01-20 │ -0.207 │
│ JPM     │ 2002-07-23 │ -0.181 │
│ JPM     │ 2008-11-20 │ -0.179 │
└─────────┴────────────┴────────┘
  1. 1The inner query makes the ret column.
  2. 2The outer WHERE can finally see it.
03

Subqueries as values and lists

A subquery that returns one row and one column can be used wherever a number can, such as on the right of >. A subquery that returns one column of many rows can follow IN. Both are written in parentheses and may read the same table as the outer query.

main.pyPython
# A scalar subquery computes one value, the symbol's own averageprint(con.sql("""    SELECT count(*) AS days_above, (SELECT round(avg(close), 2) FROM bars WHERE symbol = 'KO') AS ko_mean    FROM bars    WHERE symbol = 'KO' AND close > (SELECT avg(close) FROM bars WHERE symbol = 'KO')"""))
┌────────────┬─────────┐
│ days_above │ ko_mean │
│   int64    │ double  │
├────────────┼─────────┤
│       2732 │   33.39 │
└────────────┴─────────┘
main.pyPython
# IN takes its list of dates from a subqueryprint(run(con, """    SELECT count(*) FROM bars    WHERE symbol = 'AAPL' AND close > open      AND date IN (SELECT date FROM bars WHERE symbol = 'JPM' AND close > open)"""))
[(2140,)]
04

Chaining CTEs

Break a long query into steps, each with a name. Below, r computes every return from all the history, recent keeps only the dates wanted, and the last SELECT picks the best day per symbol. The order matters: returns are computed before the date filter, so the first day in the window still has a previous close to compare with.

main.pyPython
# Two chained CTEs: all returns first, then only the recent ones, then the best per symbolprint(con.sql("""    WITH r AS (        SELECT symbol, date, close / lag(close) OVER (PARTITION BY symbol ORDER BY date) - 1 AS ret FROM bars    ),    recent AS (SELECT * FROM r WHERE date >= '2026-01-01' AND ret IS NOT NULL)    SELECT symbol, date, round(ret, 3) AS ret    FROM recent    QUALIFY row_number() OVER (PARTITION BY symbol ORDER BY ret DESC, date) = 1    ORDER BY symbol"""))
┌─────────┬────────────┬────────┐
│ symbol  │    date    │  ret   │
│ varchar │    date    │ double │
├─────────┼────────────┼────────┤
│ AAPL    │ 2026-07-02 │  0.048 │
│ JNJ     │ 2026-06-26 │   0.04 │
│ JPM     │ 2026-02-06 │  0.039 │
│ KO      │ 2026-07-28 │   0.05 │
│ XOM     │ 2026-08-10 │  0.044 │
└─────────┴────────────┴────────┘
A scalar subquery must return one row

Used with > or =, a subquery that returns several rows is an error, and one that returns no rows is NULL, so the comparison keeps nothing. Make sure it ends in an aggregate such as avg or max, which always gives exactly one row.

05

What the tasks ask

  1. 1
    `big_down_days`A CTE that computes the return with lag, filtered by the outer query.
  2. 2
    `above_own_average` and `days_both_up`A scalar subquery for the average, and IN (SELECT ...) for the second symbol's dates.
  3. 3
    `best_day_per_symbol`Two chained CTEs: returns on all history, then the date filter, then the best per symbol.

Key takeaways

  • Compute inside, filter outside A CTE or subquery makes a computed column available to WHERE.
  • Scalar or list One row and column is a value; one column of rows is a list for IN.
  • Order the steps on purpose Whether the date filter comes before or after a window changes the answer. Next: as-of and range joins.
Quick check
You want each symbol's best return since 1 January, but the first January return needs the 31 December close. Where does the date filter go?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • A CTE over a window: big_down_days25 pts
  • A scalar subquery: above_own_average25 pts
  • Chained CTEs: best_day_per_symbol25 pts
  • IN (SELECT ...): days_both_up25 pts
Explorer · lab-6-1
▾ lab-6-1
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-6-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-6-1 goes back to the starter files and the terminal is cleared. Your current solution will be lost — this can't be undone.

Will be reset
  • main.py → starter code
  • Terminal history and test output
  • Unsubmitted changes
Will be kept
  • Best lab score
  • Your XP and streak
  • Lecture progress and notes