σμ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 1 · Querying tables›Topic 1.4·~45 minBeginner

Joining tables

Skill positionModule 1 of 3 · Topic 4 of 4
1.4 Joining tables
—Lab score— / 100Total XP—Streak—
Lecture0% read

3 min readCode examples: 5

  1. 01The idea in plain words
  2. 02Inner and left joins
  3. 03Joins that multiply rows
  4. 04A table joined to itself
  5. 05What the tasks ask

Prices live in one table and sectors in another. To total volume by sector, or to line KO up against JNJ day by day, the tables must be joined. A join is the most useful SQL feature and the easiest one to get silently wrong, because a bad join returns plausible numbers.

01

The idea in plain words

Where we are. Topics 1 to 3 worked on one table. Here a query reads two. The next topic, window functions, brings back the idea of "the previous day" without joining the table to itself.

a JOIN b ON a.key = b.key pairs every row of a with every row of b that has the same key, and keeps only the pairs. A row with no partner disappears. A LEFT JOIN keeps every row of the left table anyway and fills the right-hand columns with NULL where nothing matched.

DefinitionJoin key

The column (or columns) the ON clause compares. If a key value repeats in a table, each repeat pairs again and the output gains rows.

02

Inner and left joins

main.pyPython
# The second table: one row per symbol, including one with no barsprint(con.sql("SELECT * FROM sectors ORDER BY symbol"))
┌─────────┬────────────────────────┐
│ symbol  │         sector         │
│ varchar │        varchar         │
├─────────┼────────────────────────┤
│ AAPL    │ Technology             │
│ JNJ     │ Health Care            │
│ JPM     │ Financials             │
│ KO      │ Consumer Staples       │
│ TSLA    │ Consumer Discretionary │
│ XOM     │ Energy                 │
└─────────┴────────────────────────┘
main.pyPython
# JOIN pairs rows that agree on symbol; the sector arrives from the other tableprint(con.sql("""    SELECT s.sector, b.symbol, b.date, b.close    FROM bars b    JOIN sectors s ON s.symbol = b.symbol1    WHERE b.date = '2026-08-21'    ORDER BY s.sector"""))
┌──────────────────┬─────────┬────────────┬────────┐
│      sector      │ symbol  │    date    │ close  │
│     varchar      │ varchar │    date    │ double │
├──────────────────┼─────────┼────────────┼────────┤
│ Consumer Staples │ KO      │ 2026-08-21 │   91.1 │
│ Energy           │ XOM     │ 2026-08-21 │ 165.11 │
│ Financials       │ JPM     │ 2026-08-21 │ 351.58 │
│ Health Care      │ JNJ     │ 2026-08-21 │ 270.24 │
│ Technology       │ AAPL    │ 2026-08-21 │ 309.35 │
└──────────────────┴─────────┴────────────┴────────┘
  1. 1b and s are aliases, short names for the two tables.
main.pyPython
# LEFT JOIN keeps TSLA even though no bar matches; count(b.symbol) sees the NULLsprint(con.sql("""    SELECT s.symbol, s.sector, count(b.symbol) AS bars1    FROM sectors s    LEFT JOIN bars b ON b.symbol = s.symbol    GROUP BY s.symbol, s.sector    ORDER BY bars"""))
┌─────────┬────────────────────────┬───────┐
│ symbol  │         sector         │ bars  │
│ varchar │        varchar         │ int64 │
├─────────┼────────────────────────┼───────┤
│ TSLA    │ Consumer Discretionary │     0 │
│ JPM     │ Financials             │  6698 │
│ XOM     │ Energy                 │  6698 │
│ AAPL    │ Technology             │  6699 │
│ KO      │ Consumer Staples       │  6699 │
│ JNJ     │ Health Care            │  6699 │
└─────────┴────────────────────────┴───────┘
  1. 1count(b.symbol) skips NULL, so TSLA counts 0; count(*) would say 1.

To list only the unmatched rows, a LEFT JOIN followed by WHERE b.symbol IS NULL keeps exactly the rows of sectors that found no partner. This pattern is called an anti-join, and it is how you answer "which symbols have no data?".

One trap: a test about the right-hand table, such as b.date >= '2026-08-21', belongs in the ON clause of a LEFT JOIN. Put it in WHERE and every unmatched row, whose date is NULL, fails the test and disappears, so the left join quietly turns into an inner join. The lab task symbols_without_bars(since) is built to catch this.

03

Joins that multiply rows

main.pyPython
# A duplicated key doubles every KO bar, and every sum over themcon.execute("CREATE TABLE dup AS SELECT * FROM sectors UNION ALL SELECT 'KO', 'Beverages'")print(run(con, "SELECT count(*) FROM bars b JOIN sectors s ON s.symbol = b.symbol WHERE b.symbol = 'KO'"))print(run(con, "SELECT count(*) FROM bars b JOIN dup s ON s.symbol = b.symbol WHERE b.symbol = 'KO'"))
[(6699,)]
[(13398,)]
Count rows before and after

The second count is twice the first, and a sum(volume) would be doubled with no error message. After a join, check that the row count is what you expect, and make sure the key is unique on the side you did not mean to multiply.

04

A table joined to itself

To put two symbols side by side, use bars twice under different aliases and join on the date. Only the days where both have a bar survive, which is usually exactly what a correlation or a spread needs.

main.pyPython
# KO against JNJ on the days both tradedprint(con.sql("""    SELECT a.date, a.close AS ko, b.close AS jnj    FROM bars a    JOIN bars b ON b.date = a.date    WHERE a.symbol = 'KO' AND b.symbol = 'JNJ' AND a.date >= '2026-08-18'    ORDER BY a.date"""))
┌────────────┬────────┬────────┐
│    date    │   ko   │  jnj   │
│    date    │ double │ double │
├────────────┼────────┼────────┤
│ 2026-08-18 │  88.82 │ 271.11 │
│ 2026-08-19 │  90.35 │ 273.41 │
│ 2026-08-20 │   90.5 │ 267.37 │
│ 2026-08-21 │   91.1 │ 270.24 │
└────────────┴────────┴────────┘
05

What the tasks ask

  1. 1
    `bars_in_sector` and `sector_volume`An inner join, then (for the second) a GROUP BY on the sector. A sector with no bars must not appear.
  2. 2
    `symbols_without_bars`A LEFT JOIN whose ON holds the date test, and an IS NULL on the right side.
  3. 3
    `pair_closes`Join bars to itself on the date, one alias per symbol.

Key takeaways

  • Inner keeps matches, left keeps the left An unmatched left row vanishes in a plain JOIN and survives with NULLs in a LEFT JOIN.
  • Anti-join finds what is missing LEFT JOIN plus IS NULL on the right lists the left rows without a partner.
  • Check the row count A non-unique key multiplies rows and silently inflates sums. Next: window functions.
Quick check
Table sectors has 6 symbols and 5 of them have bars. How many rows does SELECT * FROM sectors s LEFT JOIN bars b ON b.symbol = s.symbol WHERE b.symbol IS NULL return?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • Inner JOIN: bars_in_sector25 pts
  • LEFT JOIN anti-join: symbols_without_bars25 pts
  • Join, then group: sector_volume25 pts
  • A self-join: pair_closes25 pts
Explorer · lab-4-1
▾ lab-4-1
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-4-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-4-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