Difficulty: Intermediate
Why is a query like WHERE title LIKE '%keyword%' slow on a large table, and what would you use instead?
A leading wildcard ('%keyword%') makes a normal B-tree index useless, because a B-tree is sorted by the beginning of the string and the database cannot know where in that sorted order a value containing "keyword" somewhere in the middle would sit. It has to read every row and test each string, which is a full table scan. The fix is an index built for substring or word search: a trigram index (PostgreSQL pg_trgm) for substring matching, or a full-text index (tsvector with GIN, MySQL FULLTEXT, or a search engine like Elasticsearch/OpenSearch) for word-based search.
Think of a B-tree on title like a phone book sorted by name.
LIKE 'Data%' is a prefix search: jump to "Data" and read forward until the prefix stops matching. Fast.LIKE '%Data%' could match "Big Data Engineer" or "Database Admin". Those are scattered across the entire sorted order, so there is nowhere to jump to.In PostgreSQL, even prefix LIKE only uses a plain B-tree when the column uses the C collation, or when the index is created with text_pattern_ops. ILIKE and lower(title) LIKE need an index on the matching expression.
pg_trgm splits text into three-character chunks. "data" becomes trigrams like "dat" and "ata". A GIN index over those trigrams lets PostgreSQL find candidate rows containing all the trigrams of the search term, then recheck them. It supports LIKE, ILIKE and regex, and similarity search for typos. It is best for short fields like names, company titles and SKUs. Search terms shorter than three characters get little help.
Full-text search tokenises text into normalised words (lexemes), removes stop words, and stems words so "running", "runs" and "run" match. It builds an inverted index: word to list of rows.
| Approach | Good at | Weak at |
|---|---|---|
LIKE '%x%' (no index) | Tiny tables, ad-hoc queries | Anything large |
pg_trgm GIN | Substrings, fuzzy and typo matching | Long documents, relevance ranking |
tsvector GIN | Word matching, stemming, ranking | Partial-word matches, Indian names and mixed scripts without tuning |
| Elasticsearch / OpenSearch | Relevance, facets, synonyms, autocomplete at scale | Extra system to run and keep in sync |
A job board searching "react developer bangalore" across lakhs of listings wants ranking, stemming and filters, so it uses full-text search in PostgreSQL for moderate scale or a dedicated engine for large scale. Searching a company name in an admin panel is a trigram job. MySQL offers FULLTEXT indexes queried with MATCH ... AGAINST.
lower(title)) without an expression index, which also forces a scan.to_tsvector inside the WHERE clause without a matching index or stored generated column.dev:*) or trigrams.| LIKE 'data%' | LIKE '%data%' | |
|---|---|---|
| Where matches sit in the index | One contiguous range | Scattered everywhere |
| Plan with a B-tree | Index range scan | Sequential scan |
| Rows examined | Only matching range | Every row |
| Right index | B-tree (text_pattern_ops) | Trigram GIN or full-text |
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX idx_jobs_title_trgm ON jobs USING gin (title gin_trgm_ops);
-- Now uses a Bitmap Index Scan on idx_jobs_title_trgm
EXPLAIN SELECT id, title FROM jobs WHERE title ILIKE '%backend%';
-- Typo-tolerant search ranked by similarity
SELECT title, similarity(title, 'bakend enginer') AS score
FROM jobs
WHERE title % 'bakend enginer'
ORDER BY score DESC
LIMIT 10;
The GIN trigram index makes leading-wildcard LIKE and ILIKE indexable, and the % operator adds fuzzy matching for misspelled search terms.
ALTER TABLE jobs ADD COLUMN search tsvector
GENERATED ALWAYS AS (
setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
setweight(to_tsvector('english', coalesce(description, '')), 'B')
) STORED;
CREATE INDEX idx_jobs_search ON jobs USING gin (search);
SELECT id, title, ts_rank(search, q) AS rank
FROM jobs, websearch_to_tsquery('english', 'react developer -intern') q
WHERE search @@ q
ORDER BY rank DESC
LIMIT 20;
A generated tsvector column stays in sync automatically, title matches are weighted above description matches, and websearch_to_tsquery accepts Google-style input such as quoted phrases and minus to exclude.
LIKE Wildcard, B-tree Index, Full-Text Search, pg_trgm, GIN Index