The full answer
Use the database's full-text search: store a processed form of the text (words reduced to their stems, without stop words), put a full-text index on it, and query with the full-text operators, which also rank results. LIKE '%word%' can't use a normal index, doesn't understand word forms and can't rank.
PostgreSQL
ALTER TABLE articles
ADD COLUMN search tsvector
GENERATED ALWAYS AS (
setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
setweight(to_tsvector('english', coalesce(body, '')), 'B')
) STORED;
CREATE INDEX idx_articles_search ON articles USING GIN (search);
SELECT id, title, ts_rank(search, q) AS rank
FROM articles, websearch_to_tsquery('english', 'database optimization -oracle') AS q
WHERE search @@ q
ORDER BY rank DESC
LIMIT 20;
The generated column stays current automatically; the GIN index makes matching fast; title words are weighted above body words; websearch_to_tsquery accepts search-box syntax (quotes, or, -). "optimize" matches "optimization" through stemming.
MySQL
ALTER TABLE articles ADD FULLTEXT INDEX ft_articles (title, body);
SELECT id, title, MATCH(title, body) AGAINST ('database optimization') AS score
FROM articles
WHERE MATCH(title, body) AGAINST ('database optimization' IN NATURAL LANGUAGE MODE)
ORDER BY score DESC;
SQL Server has full-text catalogs and indexes with CONTAINS and FREETEXT.
For partial words and typos: trigram indexes (PostgreSQL's pg_trgm) support fast ILIKE '%abc%' and similarity search on short fields such as names.
Challenges and considerations
- Relevance: ranking needs tuning: field weights, recency, and popularity often matter as much as word matches.
- Languages: stemming and stop words are language-specific; mixed-language content needs a configuration per language or a simple one. Product codes and names may be mangled by stemming, so index them separately.
- Write cost: full-text indexes make inserts and updates slower and take space.
- Features: typo tolerance, synonyms, faceting and autocomplete are limited in databases.
- Meaning: keyword search misses results that use different words for the same idea; semantic (vector) search with embeddings, often combined with keyword search, handles that.
- Highlighting and snippets: showing matched words in context (
ts_headlinein PostgreSQL) is slow on long documents, so run it only on the page of results being shown. - Testing: build a small set of real searches with the results users expect, and re-run it whenever you change weights, dictionaries or the query parser, so relevance doesn't silently get worse.
- Scale: for very large or search-heavy applications, a dedicated engine such as Elasticsearch, OpenSearch or Solr, kept in sync from the database, offers more control at the cost of running another system.
Last updated 16 October 2026
Sources