Full answer
Choices:
- Prefix search:
WHERE name LIKE 'lam%'can use a B-tree index (in PostgreSQL withtext_pattern_opsor 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);thenILIKE '%amp%'uses the index. Very short terms (one or two characters) still match many rows. - Word search: full-text search with stemming and ranking (
tsvectorin 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