1

I am looking to validate argument input to check, for example, that the _product_ids::BIGINT[] is not null, or does not contain null (or optionally, does not contain only null), or is not empty.

Here is what I have:

IF (
  _product_ids IS NULL -- Is null
  OR -1 = ANY(_product_ids) IS NULL -- Contains null
  OR COALESCE(ARRAY_LENGTH(_product_ids, 1) < 1, TRUE) -- Is empty
) THEN
  RAISE EXCEPTION 'INPUT IS INVALID';
END IF;

I would like to tweak 'Contains null' so that it'll return true only if there is only nulls. Additionally, I would like to know if there is a way to check for null and empty array at the same time.

PostgresSQL 9.6 is used.

1 Answer 1

1

The expression may look like this:

_product_ids is null -- is null
or cardinality(_product_ids) = 0 -- is empty
or (select bool_and(e is null) from unnest(_product_ids) e) -- contains only nulls
Sign up to request clarification or add additional context in comments.

2 Comments

Should I be concerned about performance of unnest if the size of the array is expected to be below <= 16?
Surely the expression is more expensive than a simple compare with any() but I don't think the difference if very significant.

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.