How do I index the following statement with an un-anchored search pattern
SELECT somefield
FROM sometable
WHERE lower(somefield2) like '%foo%';
Some rows have more than 2k bytes.
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It only takes a minute to sign up.
Sign up to join this communityHow do I index the following statement with an un-anchored search pattern
SELECT somefield
FROM sometable
WHERE lower(somefield2) like '%foo%';
Some rows have more than 2k bytes.
The length aside, a btree index would not help that query. You could create a hash index but that would also only help if the query wants an exact match for the whole column. not for a substring pattern. To do what you want first, add the pg_trgm
extension:
CREATE EXTENSION pg_trgm;
Then create a trigram index:
CREATE INDEX trgm_idx ON sometable
USING GIN (somefield2 gin_trgm_ops); -- can also be GIST
A trigram index can help find matches for SQL's LIKE
and ILIKE
and regex patterns.
For more information see the docs on pg_trgm