σμ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
  • 日本語
  • 中文
DuckDB skill›Module 3 · Fast and at scale›Topic 3.1·~45 minAdvanced

Query profiling and plans

Skill positionModule 3 of 3 · Topic 1 of 3
3.1 Query profiling and plans
—Lab score— / 100Total XP—Streak—
Lecture0% read

3 min readCode examples: 3

  1. 01The idea in plain words
  2. 02A plan is a tree you can read
  3. 03EXPLAIN ANALYZE: what it actually read
  4. 04What the tasks ask

Two queries return the same answer, one in a blink and the other after a coffee. SQL does not say how to get the answer, so the difference is hidden in the plan DuckDB chose: what it read, what it filtered early, how it joined. Reading a plan is how you find out, and it is a skill you use whenever a query is slower than it should be.

01

The idea in plain words

Where we are. The SQL skill's indexes and plans topic used a cost simulator. Here it is DuckDB's own plan, read as data. The next topic asks what to do when the answer to a query does not fit in memory.

DefinitionQuery plan

The tree of operators the database chose to answer a query, data flowing from the scans at the leaves up to the result. EXPLAIN shows it without running; EXPLAIN ANALYZE runs it and records how many rows each operator produced.

02

A plan is a tree you can read

main.pyPython
# EXPLAIN prints the plan as boxes; the JSON form is the same tree as dataquery = "SELECT symbol, avg(close) AS mean_close FROM bars WHERE date >= '2026-08-01' GROUP BY symbol"print(con.sql("EXPLAIN " + query).fetchall()[0][1])print(operator_names(plan_tree(con, query)))
╭─ Projection ────────────────────────────╮
│ Projections:                            │
│ __internal_decompress_string(#0), #1    │
│ ~5 rows                                 │
╰────────────────────┬────────────────────╯
╭─ Hash Group By ────┴────────────────────╮
│ Groups: #0                              │
│ Aggregates: avg(#1)                     │
│ ~5 rows                                 │
╰────────────────────┬────────────────────╯
╭─ Projection ───────┴────────────────────╮
│ Projections: symbol, close              │
│ ~6,698 rows                             │
╰────────────────────┬────────────────────╯
╭─ Projection ───────┴────────────────────╮
│ Projections:                            │
│ __internal_compress_string_ubigint(#0), │
│ #1                                      │
│ ~6,698 rows                             │
╰────────────────────┬────────────────────╯
╭─ Seq Scan ─────────┴────────────────────╮
│ Table: memory.main.bars                 │
│ Type: Sequential Scan                   │
│ Projections: symbol, close              │
│ Filters: date >= '2026-08-01'::DATE     │
│ ~6,698 rows                             │
╰─────────────────────────────────────────╯

['PROJECTION', 'HASH_GROUP_BY', 'PROJECTION', 'PROJECTION', 'SEQ_SCAN']

Read it from the bottom: the scan reads bars, then the aggregate groups the rows, then projections shape the output. The scan box lists Filters: the date test was handed to the reader, which can skip data before producing any row. A condition that DuckDB cannot push into the scan, such as one on an aggregate result (HAVING), shows up as a separate FILTER node higher up, after the work is done.

main.pyPython
# A WHERE condition lives in the scan; a HAVING condition becomes a FILTER node after the aggregatewhere = plan_tree(con, "SELECT symbol, avg(close) FROM bars WHERE date >= '2026-08-01' GROUP BY symbol")having = plan_tree(con, "SELECT symbol, avg(close) AS m FROM bars GROUP BY symbol HAVING avg(close) > 50")print("WHERE  ->", scan_filters(where), "| FILTER nodes:", operator_names(where).count("FILTER"))print("HAVING ->", scan_filters(having), "| FILTER nodes:", operator_names(having).count("FILTER"))
WHERE  -> ["(date >= '2026-08-01'::DATE)"] | FILTER nodes: 0
HAVING -> [] | FILTER nodes: 1
03

EXPLAIN ANALYZE: what it actually read

The plain plan carries estimates. EXPLAIN ANALYZE runs the query and records real row counts per operator, so a scan that produced 6,699 rows against another that produced 15 settles which query is cheaper. Row counts do not depend on the machine, unlike timings, which is why this lab compares rows.

main.pyPython
# Real row counts from the scans of two queries that return the same kind of rowswide = "SELECT * FROM bars WHERE symbol = 'KO'"narrow = "SELECT * FROM bars WHERE symbol = 'KO' AND date >= '2026-08-01'"print("wide scan rows:", scan_rows(plan_tree(con, wide, analyze=True)))print("narrow scan rows:", scan_rows(plan_tree(con, narrow, analyze=True)))print("cheaper:", cheaper_query(con, wide, narrow))
wide scan rows: 6699
narrow scan rows: 15
cheaper: b
A plan is a hint, not a promise

The optimizer can change a plan between DuckDB versions and as tables grow, and small tables may show a plan you would not see on the full data. Measure on data of the real size, compare row counts first because they are stable, and re-check plans after an upgrade.

04

What the tasks ask

  1. 1
    `operator_names`Walk the plan tree recursively, parents before children, with name_of and children_of.
  2. 2
    `scan_filters` and `scan_rows`Look only at scan nodes (is_scan): collect their Filters, or add up their rows_of.
  3. 3
    `cheaper_query`Analyse both queries with plan_tree(..., analyze=True), compare with scan_rows, answer "a", "b" or "same".

Key takeaways

  • Read plans from the leaves The scans at the bottom show what is read; everything above works on that.
  • Filters in the scan are cheap A condition pushed into the scan skips data early; one applied after an aggregate cannot.
  • Compare rows, then time Row counts are stable evidence. Next: data bigger than memory.
Quick check
In a plan, a FILTER node sits above a HASH_GROUP_BY and the scan below it shows no filters. What does that suggest?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • Walk the plan: operator_names25 pts
  • Filters in the scan: scan_filters25 pts
  • Rows read: scan_rows25 pts
  • Which query reads less: cheaper_query25 pts
Explorer · lab-7-1
▾ lab-7-1
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-7-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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