Search RU
Tasks / SQL / Reading EXPLAIN: Seq Scan vs index
Statement medium

Reading EXPLAIN: Seq Scan vs index

`analyze_plan(plan_text, *, seq_scan_row_limit=1000)` parses a PostgreSQL
textual `EXPLAIN` and returns a report:

```python
{
"seq_scans": [{"relation": str, "rows": int}],
"index_scans": [
{"type": str, "relation": str | None, "index": str | None, "rows": int}
],
"top_rows": int,
"warnings": [str],
}
```

Nodes:

- `seq_scans` — `Seq Scan on <relation>` only;
- `index_scans` — `Index Scan`, `Index Only Scan`, `Bitmap Heap Scan`,
`Bitmap Index Scan`; for `Bitmap Index Scan` the `index` field is filled and
`relation` is `None`;
- `rows` — the planner estimate from the first group `(cost=... rows=N ...)`,
not `actual rows`;
- `top_rows` — the estimated rows of the first plan node (for example `Limit`),
not of the deepest one;
- node order follows the plan.

Warnings:

- for every `Seq Scan` with `rows > seq_scan_row_limit` add a line with the table
name and the row count;
- exactly at the boundary (`rows == seq_scan_row_limit`) there is no warning;
- with `seq_scan_row_limit=0` any `Seq Scan` with `rows > 0` warns.

Boundaries:

- empty text, non-string — `ValueError`;
- a negative or non-integer limit — `ValueError`;
- the `QUERY PLAN`, `Planning Time`, `Execution Time` lines are not nodes;
- a plan without scan nodes is valid: the lists are empty and `top_rows` comes
from the first node.

Write tests for: an index plan, Seq Scan above the boundary and at the boundary,
`LIMIT` on top, `EXPLAIN ANALYZE` with a large actual row count, a Bitmap plan,
a nested loop, and invalid input.

sqlexplainindexseq-scanpostgresql
test_solution.py Python 3.14
AI mentor

The AI mentor is available after you log in: it sees your attempt history and does not spend resources on anonymous requests.

Log in and ask
Hints 1 of 3 unlocked · attempts: 0
Hint 1

How does the `rows` estimate differ from `actual rows`, and why is the warning
built from the estimate?

Hint 2 — unlocks after 1 attempt
Hint 3 — unlocks after 3 attempts