I want to use a column of arrays as a condition in postgres. The condition is applied on a column composed of text value.
This is the column made out of arrays (after be transformed with string_to_array.
And this is the tax_role column.
I’tried a mix of ANY
and IN
but I get this error message.
Here’s my script :
select
*
from tax_role
where tax_role_2021.address_num IN ANY
(SELECT string_to_array(corporate_data.address_num, '-') FROM corporate_data
where lower(corporate_data.name) LIKE '%some_name%'); -- this is the query that return the arrays
But it doesn’t seem to work.
2
Answers
The error you’re encountering is due to the misuse of the
IN
andANY
clauses together.In PostgreSQL, when you’re comparing against an array, you can use the
ANY
keyword, but it’s not used in conjunction withIN
. Instead, you can use it like this:Try this modified script:
This script will compare each
address_num
intax_role_2021
against the arrays returned by the subquery. If there’s a match, the row fromtax_role
will be included in the result set.The problem is a little unclear when considering the use of IN or ANY. It depends on your use case.
If you want to check that an address number is in a specific set you should use the
IN
keyword, or if you want to match with any of its occurrences, you should opt for theANY
keyword. But do not use both at the same time.Your subquery to convert a string to an array seems perfect so there is no issue in that.
I believe that in your case, the keyword
IN
will be used, try modifying Joaquin’s query with IN keyword. It should work then.