How do I determine if NULL is contained in an array in Postgres? Currently using Postgres 9.3.3.
If I test with the following select it returns contains_null =
One more construction, like @Clodoaldo Neto proposed. Just more compact expression:
CREATE TEMPORARY TABLE null_arrays (
id serial primary key
, array_data int[]
);
INSERT INTO null_arrays (array_data)
VALUES
(ARRAY[1,2, NULL, 4, 5])
, (ARRAY[1,2, 3, 4, 5])
, (ARRAY[NULL,2, 3, NULL, 5])
;
SELECT
*
FROM
null_arrays
WHERE
TRUE = ANY (SELECT unnest(array_data) IS NULL)
;
i didn't want to use unnest
either, so i used a comparison of array_length
using array_remove
to solve a similar problem. Tested on 9.4.1, but should work in 9.3.3.
SELECT
ARRAY_LENGTH(ARRAY[1,null], 1) > ARRAY_LENGTH(ARRAY_REMOVE(ARRAY[1,null], NULL), 1)
OR ARRAY_LENGTH(ARRAY_REMOVE(ARRAY[1,null], NULL), 1) IS NULL
---------
t
select exists (
select 1
from unnest(array[1, null]) s(a)
where a is null
);
exists
--------
t
Or shorter:
select bool_or(a is null)
from unnest(array[1, null]) s(a)
;
bool_or
---------
t
Ideally you'd write:
SELECT
NULL IS NOT DISTINCT FROM ANY ARRAY[NULL,1,2,3,4,NULL]::int[];
but the parser doesn't recognise IS NOT DISTINCT FROM
as valid syntax for an operator here, and I can't find an operator alias for it.
You'd have to:
CREATE FUNCTION opr_isnotdistinctfrom(anyelement, anyelement)
RETURNS boolean LANGUAGE SQL IMMUTABLE AS $$
SELECT $1 IS NOT DISTINCT FROM $2;
$$;
CREATE OPERATOR <<>> (
PROCEDURE = opr_isnotdistinctfrom,
LEFTARG = anyelement,
RIGHTARG = anyelement
);
SELECT NULL <<>> ANY (ARRAY[NULL,1,2,3,4,NULL]::int[]);
which seems a bit gruesome, but should optimize out just fine.
It seems the following works fine in PostgreSQL 10.1.
CREATE TABLE my_table
(
...
my_set int[] NOT NULL,
...
);
SELECT
my_set
FROM
my_table
WHERE
array_position(my_set, NULL) IS NOT NULL;