Sobes.tech
Junior — Middle

What can cause PostgreSQL not to use an index when performing a search on a specific field?

sobes.tech AI

Answer from AI

PostgreSQL may not use an index when searching by a specific field for several reasons:

  • Low query selectivity: if the search condition returns a large percentage of rows, the planner may choose sequential scanning as it is more efficient.
  • Data types or operations incompatible with the index: for example, using functions or operations that do not support indexing (e.g., LIKE '%pattern'), or data type mismatches.
  • Lack of statistics or outdated statistics: if the table statistics are not updated (ANALYZE), the planner may make an incorrect decision.
  • Use of expressions not covered by the index: for example, searching by a computed field without a corresponding functional index.
  • Configuration parameters: for example, a too high value of random_page_cost can influence the plan choice.

Example: if you have an index on the name field, but the query uses WHERE LOWER(name) = 'abc', and the index is not functional on LOWER(name), the index will not be used.