Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I have a simple list of ~25 words. I have a varchar field in PostgreSQL, let's say that list is
['foo', 'bar', 'baz']
. I want to find any row in my table that has any of those words. This will work, but I'd like something more elegant.
select *
from table
where (lower(value) like '%foo%' or lower(value) like '%bar%' or lower(value) like '%baz%')
PostgreSQL also supports full POSIX regular expressions:
select * from table where value ~* 'foo|bar|baz';
The ~*
is for a case insensitive match, ~
is case sensitive.
Another option is to use ANY:
select * from table where value like any (array['%foo%', '%bar%', '%baz%']);
select * from table where value ilike any (array['%foo%', '%bar%', '%baz%']);
You can use ANY with any operator that yields a boolean. I suspect that the regex options would be quicker but ANY is a useful tool to have in your toolbox.
–
–
–
–
–
–
–
–
–
All currently supported versions (9.5 and up) allow pattern matching in addition to LIKE
.
Reference: https://www.postgresql.org/docs/current/functions-matching.html
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.