I have a table in postgres with a value
column that contains string arrays. My objective is to find all arrays that contain any of the following strings: {'cat', 'dog'}
id value
1 {'dog', 'cat', 'fish'}
2 {'elephant', 'mouse'}
3 {'lizard', 'dog', 'parrot'}
4 {'bear', 'bird', 'cat'}
The following query uses ANY()
to check if 'dog' is equal to any of the items in each array and will correctly return rows 1 and 3:
select * from mytable where 'dog'=ANY(value);
I am trying to find a way to search value
for any match in an array of strings. For example :
select * from mytable where ANY({'dog', 'cat'})=ANY(value);
Should return rows 1, 3, and 4. However, the above code throws an error. Is there a way to use the ANY() clause on the left side of this equation? If not, what would be the workaround to check if any of the strings in an array are in value
?
You can use
&&
operator to find out whether two array has been overlapped or not. It will return true only if at least one element from each array match.Schema and insert statements:
Query:
Output:
db<>fiddle here
Query#2 (match array element using wildcard characters)
To compare array elements using wildcard characters you can use unnest() parse every element of both arrays and compare them using Like operator.
Output:
db<>fiddle here