两条查询返回同样的答案,一条一眨眼,另一条要等一杯咖啡的时间。SQL 不规定怎样得到答案,所以差别藏在 DuckDB 选定的计划里:读了什么、先过滤了什么、怎样连接。读计划就是找出原因的方法,查询比预期慢时随时都用得上。
用通俗的话说这个想法
我们在哪里。 SQL 技能里关于索引和计划的主题用的是成本模拟器。这里读的是 DuckDB 自己的计划,并把它当作数据。下一个主题讨论查询结果装不进内存时怎么办。
定义查询计划
数据库为回答查询而选定的算子树,数据从叶子处的扫描流向结果。EXPLAIN 只显示不执行;EXPLAIN ANALYZE 会执行并记录每个算子产生了多少行。
计划是一棵可读的树
# 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']
从下往上读:扫描读取 bars,然后聚合对行分组,再由投影整理输出。扫描框里列出了 Filters:日期条件被交给了读取器,因此它可以在产生任何一行之前就跳过数据。DuckDB 无法下推进扫描的条件(例如针对聚合结果的 HAVING)会作为更靠上的独立 FILTER 节点出现,在工作做完之后才起作用。
# 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
EXPLAIN ANALYZE:它实际读了什么
普通的计划里是估计值。EXPLAIN ANALYZE 会执行查询并记录每个算子的真实行数,所以一个产生 6,699 行的扫描和另一个产生 15 行的扫描,就能判定哪条查询更省。行数与机器无关,不像耗时那样会变,这就是本实验比较行数的原因。
# 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
计划只是线索,不是保证
优化器可能在 DuckDB 版本之间、也可能随着表变大而改变计划,小表上看到的计划也可能与完整数据上的不同。要用真实规模的数据来测,先比较稳定的行数,并在升级之后重新检查计划。
任务要求
- 1`operator_names`用
name_of和children_of递归遍历计划树,先父后子。 - 2`scan_filters` 与 `scan_rows`只看扫描节点(
is_scan):收集它们的Filters,或把rows_of加起来。 - 3`cheaper_query`用
plan_tree(..., analyze=True)分析两条查询,用scan_rows比较,回答 "a"、"b" 或 "same"。
快速检查
在某个计划中,
FILTER 节点位于 HASH_GROUP_BY 之上,而它下面的扫描没有显示任何过滤条件。这说明什么?请选择一个答案。
实验:评分内容
4 个任务 · 100 分- 遍历计划:
operator_names25 分 - 扫描中的过滤条件:
scan_filters25 分 - 读取的行数:
scan_rows25 分 - 哪条查询读得更少:
cheaper_query25 分