"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.
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.
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.
Name a result, then filter it
# 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 │ └─────────┴────────────┴────────┘
- 1The inner query makes the
retcolumn. - 2The outer
WHEREcan finally see it.
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.
# 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 │ └────────────┴─────────┘
# 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,)]
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.
# 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 │ └─────────┴────────────┴────────┘
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.
What the tasks ask
- 1`big_down_days`A CTE that computes the return with
lag, filtered by the outer query. - 2`above_own_average` and `days_both_up`A scalar subquery for the average, and
IN (SELECT ...)for the second symbol's dates. - 3`best_day_per_symbol`Two chained CTEs: returns on all history, then the date filter, then the best per symbol.
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