← Back to SQL, page 19

sql-0361 · Medium mid

An index on email exists, yet a lookup by email still scans the whole table. Give likely reasons.

The predicate probably does not match the index: wrapping the column in a function (lower(email)), comparing with a different type that forces a cast on the column, using a leading-wildcard LIKE, or a collation mismatch. Rewrite the predicate to compare the bare column, or create an expression index that matches it.

Full answer

Typical mismatches:

  • Function on the column: WHERE lower(email) = 'a@x.com' cannot use an index on email. Create an index on lower(email) or store emails normalised.
  • Implicit cast: comparing a text column with a number, or a varchar with a parameter typed differently by a driver, may cast the column side.
  • Leading wildcard: LIKE '%@x.com' cannot use a B-tree; a trigram index (PostgreSQL pg_trgm) can.
  • LIKE prefix in PostgreSQL with a non-C collation needs a text_pattern_ops index.
  • In SQLite, LIKE is case-insensitive by default and only uses an index under specific collation settings.
  • Low selectivity or a tiny table: the planner may prefer a scan legitimately.

Use EXPLAIN to see the chosen plan and test the rewritten predicate; the fix is whichever form lets the bare indexed expression appear on one side of the comparison.

Key points

  • Functions on the column block plain indexes
  • Expression indexes match function predicates
  • Implicit casts can disable index use
  • Leading wildcards need trigram indexes
  • Small tables may scan legitimately

Common mistakes

  • Adding a second identical index
  • Ignoring driver parameter types

Follow-ups

  • How would you enforce case-insensitive unique emails?
  • What is a sargable predicate?

Tips

  • Check the predicate against the index definition