SteelReed

Search

Search posts, questions…

SQL & Query TuningQuestion 21 / 37

Junior

Why does a query still do a Seq Scan despite an index, and is a Seq Scan always bad?

Short answer

There are two groups of reasons: the index cannot be used (a function wrapping the column, implicit casts, LIKE '%abc', wrong composite column order), or the planner chooses not to (too many rows returned, small table, wrong statistics). A Seq Scan is not bad when reading most of the table.

Index not usedCannot be usedPlanner skips itFunction on column, cast,LIKE '%abc', wrong orderToo many rows, small table,bad statistics

3 points to say:

  1. Never wrap the column in a function or arithmetic in WHERE; parameter types must match column types.
  2. When a function is unavoidable: an expression index; for special cases, partial indexes and trigram.
  3. A Seq Scan is right when reading most of the table; compare estimated vs actual rows with EXPLAIN ANALYZE.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.