Indexing the condition lower(f) LIKE '%foo%'

All we need is an easy explanation of the problem, so here it is.

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.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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:


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

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply