Since 9.5 array_position() is not null
can also safely check for null
containment.
SELECT COUNT(*) FROM messages WHERE (array_position(recipient_ids, your_val) IS null)
array_position ( anycompatiblearray, anycompatible [, integer ] ) → integer
Returns the subscript of the first occurrence of the second argument in the array, or NULL
if it's not present. If the third argument is given, the search begins at that subscript. The array must be one-dimensional. Comparisons are done using IS NOT DISTINCT FROM
semantics, so it is possible to search for NULL
.
There's no operator in GIN index array_ops
that uses this function, so the price for using it in a query is that it won't benefit from the index. Demo at db<>fiddle:
select array_position(array[null],null) is not null;
<@
,&&
and @>
array operators as well as IN()
, SOME()
and ANY()
use regular =
that yields null
if there's null
on either side of the operator, which is why none of the examples below works, even though all might seem like they could/should:
select null=any(array[null,'']) as "any",
null=some(array[null,'']) as "some",
null=all(array[null,null]) as "all",
null in (null,'') as "in",
null in (select unnest(array[null,'']))as "in(2)",
array[null] <@ array[null,''] as "<@",
array[null] && array[null,''] as "&&";
any |
some |
all |
in |
in(2) |
<@ |
&& |
null |
null |
null |
null |
null |
FALSE |
FALSE |
WHERE 3 NOT IN recipient_ids
work?text[]
andint[]
array:select not(array[1,2,3] @> array[3]);
null
column is contained or not contained in an array, it will always say no. It took me like 20 minutes of debugging several containing methods to come to the conclusion that you cannot check if null is contained in an arraynull
containment in arrays.