σμ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 1 · Querying data in place›Topic 1.4·~45 minIntermediate

QUALIFY and friendly SQL

Skill positionModule 1 of 3 · Topic 4 of 4
1.4 QUALIFY and friendly SQL
—Lab score— / 100Total XP—Streak—
Lecture0% read

3 min readCode examples: 4

  1. 01The idea in plain words
  2. 02Rank inside a group with QUALIFY
  3. 03Wide tables, grouped summaries, one formula for many columns
  4. 04What the tasks ask

"The three busiest days of every stock" takes a subquery in plain SQL, a second subquery to filter it, and a lot of repeated column names. In DuckDB it is one query with one extra clause. DuckDB's SQL keeps everything standard SQL has and adds shortcuts that research queries use all the time.

01

The idea in plain words

Where we are. Topic 3 joined two tables on time. This one makes single-table analysis shorter: rank within a group, spread a column wide, summarise by month, apply one formula to many columns. The next topic hands results to pandas, Polars and Arrow.

DefinitionFriendly SQL

DuckDB's extensions to standard SQL that remove boilerplate without changing what a query means: QUALIFY, PIVOT, GROUP BY ALL, FILTER, COLUMNS, SELECT * EXCLUDE, FROM first, and more. Most other databases do not have them, so a query that relies on them is DuckDB-specific.

02

Rank inside a group with QUALIFY

QUALIFY is to window functions what HAVING is to aggregates: it filters on their result, so the window and the filter sit in one query with no subquery. Put a tie-breaker in the window's ORDER BY so the answer does not change from run to run.

main.pyPython
# The busiest day of every stock, with no subqueryprint(con.sql("""    SELECT symbol, date, volume    FROM bars    QUALIFY row_number() OVER (PARTITION BY symbol ORDER BY volume DESC, date) = 1    ORDER BY symbol"""))
┌─────────┬────────────┬────────────┐
│ symbol  │    date    │   volume   │
│ varchar │    date    │   int64    │
├─────────┼────────────┼────────────┤
│ AAPL    │ 2000-09-29 │ 8846193721 │
│ JNJ     │ 2023-08-21 │  151319484 │
│ JPM     │ 2012-05-11 │  291205984 │
│ KO      │ 2009-09-18 │  179920213 │
│ XOM     │ 2010-06-25 │  189442014 │
└─────────┴────────────┴────────────┘
03

Wide tables, grouped summaries, one formula for many columns

PIVOT spreads the values of a column into columns of their own, a closing-price table with one column per stock. GROUP BY ALL saves repeating the grouping columns, FILTER counts only some rows inside an aggregate, arg_max(a, b) returns a at the row where b is largest, and COLUMNS('regex') applies one expression to every column whose name matches.

main.pyPython
# One column per stocknames, rows = closes_pivot(con, "2026-08-19")print(names)for row in rows:    print(row)
['date', 'AAPL', 'JNJ', 'JPM', 'KO', 'XOM']
(datetime.date(2026, 8, 19), 316.83, 273.41, 357.26, 90.35, 164.77)
(datetime.date(2026, 8, 20), 311.3, 267.37, 351.55, 90.5, 166.15)
(datetime.date(2026, 8, 21), 309.35, 270.24, 351.58, 91.1, 165.11)
main.pyPython
# Per month: up days, the date of the highest close, and the day countfor row in month_summary(con, "KO")[-3:]:    print(row)
(datetime.date(2026, 6, 1), 9, datetime.date(2026, 6, 10), 21)
(datetime.date(2026, 7, 1), 10, datetime.date(2026, 7, 29), 22)
(datetime.date(2026, 8, 1), 9, datetime.date(2026, 8, 21), 15)
main.pyPython
# One average, written once, applied to four columns; and a few other shortcutsprint({name: round(value, 2) for name, value in price_means(con).items()})print(con.sql("FROM bars SELECT * EXCLUDE (open, high, low) WHERE symbol = 'KO' ORDER BY date DESC LIMIT 2"))1
{'open': 61.84, 'high': 62.41, 'low': 61.28, 'close': 61.86}
┌─────────┬────────────┬────────┬──────────┐
│ symbol  │    date    │ close  │  volume  │
│ varchar │    date    │ double │  int64   │
├─────────┼────────────┼────────┼──────────┤
│ KO      │ 2026-08-21 │   91.1 │ 15534719 │
│ KO      │ 2026-08-20 │   90.5 │ 14928006 │
└─────────┴────────────┴────────┴──────────┘
  1. 1FROM can come first, and EXCLUDE drops columns without listing the rest.
Shortcuts are not portable

A query written with QUALIFY, PIVOT or COLUMNS will not run on PostgreSQL or most other engines, and a pivot's column list is decided by the data. If a query must travel, or its columns must be fixed, use the standard forms (a subquery for QUALIFY, conditional aggregates for PIVOT).

04

What the tasks ask

  1. 1
    `busiest_days`row_number() over each symbol with QUALIFY ... <= n.
  2. 2
    `closes_pivot` and `month_summary`PIVOT ... ON symbol; then FILTER, arg_max and GROUP BY ALL by month.
  3. 3
    `price_means`A single avg(COLUMNS('regex')) for four columns, returned as a dict.

Key takeaways

  • QUALIFY is HAVING for windows Rank within a group and keep the top rows in one query.
  • Say each thing once GROUP BY ALL, COLUMNS, FILTER and EXCLUDE cut repetition.
  • Know what is DuckDB-only These shortcuts do not run elsewhere. Next: Python integration.
Quick check
You want the three highest-volume days of each symbol. Which clause filters on row_number() OVER (PARTITION BY symbol ORDER BY volume DESC)?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • QUALIFY: busiest_days25 pts
  • PIVOT: closes_pivot25 pts
  • FILTER, arg_max, GROUP BY ALL: month_summary25 pts
  • COLUMNS: price_means25 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