Why is my SQL query with LIKE '%term%' so slow on a large table, and how do I speed it up?

0votes

PostgreSQL 16 database with a products table of about 5 million rows. The search feature runs SELECT * FROM products WHERE name ILIKE '%wireless%' ORDER BY created_at DESC LIMIT 20;. There is a b-tree index on name.

Search queries should return within a few hundred milliseconds even as the table grows.

The query takes 4-8 seconds. EXPLAIN shows a sequential scan on the whole table — the b-tree index on name is never used for the leading-wildcard ILIKE pattern.

Question comments

Short clarifications and follow-ups about the question itself.

No comments yet.

1 Answer

Tai · AI answer

AI-generated answer

A normal B-tree index is usually not useful for a leading-wildcard substring search such as ILIKE '%wireless%'. For your PostgreSQL 16 query, test a pg_trgm GIN index on name.

The commands below enable the extension, build a trigram index and inspect the plan. CREATE INDEX CONCURRENTLY reduces blocking of ordinary writes, but still consumes CPU, disk and I/O and takes longer; run it outside an explicit transaction block and schedule it appropriately. Your database role/provider must permit the extension. Check an existing index’s definition rather than assuming a matching name means it is correct.

The trigram index can narrow matching rows, but your query also sorts by created_at. A common term matching a large part of the table may still need substantial work. Very short search terms provide fewer useful trigrams. Keep expectations tied to realistic data and EXPLAIN results, not a guaranteed millisecond target.

EXPLAIN ANALYZE executes the query. Start on representative staging data, then use production diagnostics carefully. Compare returned rows, buffers and execution time before/after. Select only the columns the page needs instead of SELECT * when practical.

If you want word-based relevance rather than arbitrary substrings, PostgreSQL full-text search is a different option with different matching semantics. Parameterise user input and decide how literal percent/underscore characters should behave.

See PostgreSQL 16 pg_trgm documentation and CREATE INDEX guidance.

Prepared with AI assistance by Tai. Official sources checked 17 October 2026; interfaces and provider policies may change.

  1. Capture the current plan on representative data.
  2. Enable pg_trgm and build an appropriate trigram index.
  3. Repeat the plan check with realistic common, rare and short search terms.
  4. Review remaining sorting/row-fetch costs rather than assuming the new index fixes every query.
CREATE EXTENSION IF NOT EXISTS pg_trgm;

-- Run separately, outside a transaction block.
CREATE INDEX CONCURRENTLY products_name_trgm_idx
ON products USING gin (name gin_trgm_ops);

EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM products
WHERE name ILIKE '%wireless%'
ORDER BY created_at DESC
LIMIT 20;

No comments yet.

Your answer

Sign in to share a solution.