liveBook · Manning

Index scan

As explained in PostgreSQL Mistakes and How to Avoid Them

An index scan is a query execution method that retrieves matching rows by traversing a database index.

An index scan retrieves matching rows by traversing a PostgreSQL index. A direct predicate on an indexed column can be fast, while applying a function or incompatible cast to that column can force a sequential scan instead. section 2.7

A timestamp predicate that changes the plan

For indexed payment timestamps, `WHERE tstamp = '2023-10-18 03:40:34.000'` produces an `Index Scan`. Rewriting the predicate as `date_trunc('s', tstamp) = '2023-10-18 03:40:34'` produces a `Seq Scan`, because the expression no longer matches the ordinary index. Move the transformation to the comparison value and use a range instead: `tstamp >= '2023-10-18 03:40:34'::timestamptz AND tstamp < '2023-10-18 03:40:34'::timestamptz + INTERVAL '1 s'`.

Use index scans deliberately:

  • Select only required columns: selecting indexed columns alone may enable an Index-Only Scan, while additional columns require table reads through an Index Scan. section 2.9

How PostgreSQL Mistakes and How to Avoid Them covers it

How deep it goes
Explains predicate matching, table reads, and plan inspection, but does not develop broader PostgreSQL planner internals.
Examples
Uses timestamped payments, date_trunc predicates, EXPLAIN output, expression indexes, and Python psycopg fetch comparisons.
What you can do after
Diagnose index use with EXPLAIN, rewrite timestamp predicates as ranges, and choose narrower projections or matching expression indexes.
How it connects
Connects index scans to sequential scans, Index-Only Scans, expression indexes, predicates, and EXPLAIN query plans.

Also explained in

Compare how 3 books explain index scan →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of PostgreSQL Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.