I need a way to test if a value exists in a given array. So far I came up with something like this
select '{1,2,3}'::int[] @> (ARRAY[]::int[] || value_variable::int)
but I keep thinking there should be a simpler way to this, I just cant see it.
Edit: Just realized I could do this
select '{1,2,3}'::int[] @> ARRAY[value_variable::int]
This is much better and I believe will suffice, but if you have other ways to do it please share.
When looking for the existence of a element in an array, proper casting is required to pass the SQL parser of postgres. Here is one example query using array contains operator in the join clause:
For simplicity I only list the relevant part:
The join part of SQL shown
The following also works
I am just guessing that the extra casting is required because the parse does not have to fetch the table definition to figure the exact type of the column. Others please comment on this.
You can compare two arrays. If any of the values in the left array overlap the values in the right array, then it returns true. It's kind of hackish, but it works.
1
is in the right arraytrue
, even though the value4
is not contained in the right array4
) are in the right array, so it returnsfalse
Simpler with the
ANY
construct:The right operand of
ANY
(between parentheses) can either be a set (result of a subquery, for instance) or an array. There are several ways to use it:Important difference: Array operators (
<@
,@>
et al.) expect array types as operands and support GIN or GiST indices in the standard distribution of PostgreSQL, while theANY
construct expects an element type as left operand and does not support these indices. Example:None of this works for
NULL
elements. To test forNULL
:Watch out for the trap I got into: When checking if certain value is not present in an array, you shouldn't do:
but use
instead.
unnest
can be used as well. It expands array to a set of rows and then simply checking a value exists or not is as simple as usingIN
orNOT IN
.e.g.
id => uuid
exception_list_ids => uuid[]
select * from table where id NOT IN (select unnest(exception_list_ids) from table2)