1

Our system uses postgres for its database.

We have queries that can select rows from a database table where an array field in the table contains a specific value, e.g.:

Find which employee manages the employee with ID 123.

staff_managed_ids is a postgres array field containing an array of the employees that THIS employee manages.

This query works as expected:

select *
from employees
where 123=any(staff_managed_ids)

We now need to query where an array field contains a postgres NULL. We tried the following query, but it doesn't work:

select *
from employees
where NULL=any(staff_managed_ids)

We know the staff_managed_ids array field contains NULLs from other queries.

Are we using NULL wrongly?

2 Answers 2

2

NULL can not be compared using =. The only operators that work with that are IS NULL and IS NOT NULL.

To check for nulls, you need to unnest the elements:

select e.*
from employees e
where exists (select *
              from unnest(e.staff_managed_ids) as x(staff_id)
              where x.staff_id is null);
Sign up to request clarification or add additional context in comments.

Comments

0

if all your id values are positive, you could write something like this:

select *
from employees
where (-1 < all(staff_managed_ids)) is null;

how this works is that -1 should be less than all values, however comparison with null will make the whole array comparison expression null.

1 Comment

Thanks for your answer - although it's more compact, we couldn't guarantee that every existing id would be > -1, so the answer from @a_horse_with_no_name is more apt in our case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.