← Back to SQL, page 22

sql-0436 · Medium mid

Searching product names with LIKE '%term%' is slow on a large table. What are the options?

A leading wildcard prevents B-tree index use, so every row is scanned. In PostgreSQL, a trigram GIN index (pg_trgm) supports LIKE and ILIKE with leading wildcards and similarity search; full-text search suits word-based queries; SQLite offers FTS5. For prefix-only searches, LIKE 'term%' can use a suitable B-tree index.

Full answer

Choices:

  • Prefix search: WHERE name LIKE 'lam%' can use a B-tree index (in PostgreSQL with text_pattern_ops or the C collation; in SQLite with matching case sensitivity settings).
  • Substring search: CREATE EXTENSION pg_trgm; CREATE INDEX ON products USING gin (name gin_trgm_ops); then ILIKE '%amp%' uses the index. Very short terms (one or two characters) still match many rows.
  • Word search: full-text search with stemming and ranking (tsvector in PostgreSQL, FTS5 in SQLite) suits descriptions and multi-word queries.
  • Typo tolerance: trigram similarity() or % operator finds 'lmap' for 'lamp'.
  • External search engines when relevance tuning, facets and synonyms grow important.

Measure with EXPLAIN before and after; trigram indexes are large and slow writes somewhat. The PostgreSQL statements here are illustrative and were not run.

Key points

  • Leading wildcards block B-tree use
  • Trigram GIN indexes serve substring search
  • Full-text search suits word queries
  • Prefix LIKE can use B-trees
  • Measure index size and write cost

Common mistakes

  • Adding a plain B-tree and expecting '%term%' to use it
  • Using LIKE for relevance-ranked search

Follow-ups

  • How does pg_trgm split a word into trigrams?
  • When would you move to a search engine?

Tips

  • Separate prefix, substring and word search