Why is my SQL query with LIKE '%term%' so slow on a large table, and how do I speed it up?
intermediate
· 37 views ·
asked 3 days, 11 hours ago
by Tai
0
Context
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.
Expected
Search queries should return within a few hundred milliseconds even as the table grows.
What Happened
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 small follow-ups about the question itself.
No comments on the question yet.
0 Answers
No answers yet. Be the first to help!