A table of 33,493 daily bars answers a question about one stock in the blink of an eye. A table of 33 billion ticks does not, if the database has to read all of it every time. The difference between a query that takes a millisecond and one that takes a minute is usually how many rows it has to look at.
The idea in plain words
Where we are. Topics 1 to 8 were about what a query says. This one is about how the database carries it out, and why two queries with the same answer can cost very different amounts. The lab simulates the costs in Python so you can count them. The next topic designs the tables themselves.
A sorted copy of one or more columns, each entry pointing back to its row. Looking up a key by binary search costs about log2(n) steps instead of n, and rows with nearby keys sit next to each other.
Scan or index, counted
Ask for the busiest days, those with a volume of at least two billion shares. A scan reads all 33,493 rows to find 85. The index finds the first one with a binary search of about 16 steps and then reads 85 neighbours. The answers are identical, the work is 330 times smaller.
# The same 85 rows, found two ways; Meter counts the rows each one readsrows = load_rows()index = build_index(rows, VOLUME)scan, probe = Meter(), Meter()a = full_scan(scan, rows, VOLUME, 2_000_000_000, 10 ** 12)b = index_range(probe, index, rows, 2_000_000_000, 10 ** 12)print(len(a), len(b), "same rows:", a == b)print("scan reads", scan.rows, "| index reads", probe.rows)1
85 85 same rows: True scan reads 33493 | index reads 101
- 1About 330 times fewer reads for the index here.
When the index stops paying
Fetching rows through an index is not free: each match is a jump to a different place in the table, which is slower than reading rows in order. The lab charges a factor of 4 per fetched row. So when a large share of the table matches, a plain scan is cheaper, and the planner must estimate the number of matches before it picks. With a factor of 4, the break-even is around a quarter of the table.
# The planner's choice as the share of matching rows growsn = len(rows)for share in (0.0005, 0.01, 0.1, 0.2, 0.3): print(f"{share:6.2%} of the rows match -> {choose_plan(n, int(n * share))}")
0.05% of the rows match -> index 1.00% of the rows match -> index 10.00% of the rows match -> index 20.00% of the rows match -> index 30.00% of the rows match -> scan
Multi-column indexes read left to right
An index on (symbol, date) is sorted by symbol first and by date inside each symbol. It serves symbol = 'KO', and symbol = 'KO' AND date BETWEEN a AND b, because those rows are one contiguous run. It cannot serve date = '2026-08-21' alone: that date is scattered through every symbol's run. So column order matters. Put the equality columns first, then the one range column.
# Which leading columns of an index on (symbol, date, close) can each query use?index_columns = [SYMBOL, DATE, CLOSE]print(usable_prefix(index_columns, {SYMBOL}, {DATE}), "symbol = X and date in a range")print(usable_prefix(index_columns, {DATE}, set()), "date = Y alone")print(usable_prefix(index_columns, {SYMBOL}, {CLOSE}), "symbol = X and close in a range (date is skipped)")
2 symbol = X and date in a range 0 date = Y alone 1 symbol = X and close in a range (date is skipped)
What a real engine prints
Every database can show its plan. EXPLAIN prints the steps without running them. DuckDB is a column store built for scanning and aggregating, so it often prefers a fast scan and skips blocks whose minimum and maximum rule them out, rather than following an index. Row stores such as PostgreSQL lean on B-tree indexes much more. Read the plan, do not assume it.
# EXPLAIN shows the plan DuckDB chose for a one-day lookup on KOimport duckdbdb = duckdb.connect()db.execute("CREATE TABLE ko AS SELECT * FROM read_csv_auto('data/KO.csv')")print(db.sql("EXPLAIN SELECT date, close FROM ko WHERE date = '2026-08-21'").fetchall()[0][1])
╭─ Seq Scan ─────────────────────────╮ │ Table: memory.main.ko │ │ Type: Sequential Scan │ │ Projections: date, close │ │ Filters: date = '2026-08-21'::DATE │ │ ~1 row │ ╰────────────────────────────────────╯
Every index is another copy to store and to keep sorted on each insert, so too many of them slow writes and bloat the database. Add one for a query you actually run, check with the plan that it is used, and remove it if it is not.
What the tasks ask
- 1`full_scan` and `index_range`The same rows both ways, with the exact read counts: every row for the scan, the descent plus the matches for the index.
- 2`usable_prefix`Walk the index columns left to right: equality columns, then at most one range column.
- 3`choose_plan`Compare the scan cost with the index cost and pick the cheaper, scan on a tie.
(symbol, date). Which query can use it best?Lab · what's graded
4 tasks · 100 pts- The full scan:
full_scan25 pts - The index lookup:
index_range25 pts - The leading prefix:
usable_prefix25 pts - The planner's choice:
choose_plan25 pts