Video in progress
There is an index on the `email` column, but `WHERE email LIKE '%@gmail.com'` is slow. Why?
A B-tree index stores values sorted from the beginning, so it only helps when you search by a known prefix (LIKE 'ali%'). If the pattern starts with %, it doesn't know where to start and the whole table is read.
📖 Answer
Think of a phone book: you can quickly find everyone whose surname starts with "Ka", but to find everyone whose surname ends in "...ov" you'd have to flip through the whole book.
WHERE email LIKE 'ali%' -- can use the index
WHERE email LIKE '%@gmail.com' -- a B-tree doesn't help
WHERE email LIKE '%ali%' -- doesn't help either
One subtle point: whether a B-tree works for LIKE 'ali%' depends on the collation. Unless the database uses the C collation, you need to create the index with text_pattern_ops:
CREATE INDEX idx_users_email_pattern ON users (email text_pattern_ops);
If you often need to search inside the string (%ali%), PostgreSQL has a GIN index with the pg_trgm extension:
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX idx_users_email_trgm ON users USING gin (email gin_trgm_ops);
And if you specifically need to search by domain, a simpler way is to store the domain in its own column or build an expression index.
Sign up to mark studied questions and save your progress.