5

I am working with a PostgreSQL DB, and use an array of an enum type as one of the columns.

CREATE TYPE my_type_enum AS ENUM ('value1', 'value2', 'value3');
ALTER TABLE "my_table" ADD COLUMN IF NOT EXISTS "my_column" my_type_enum ARRAY;

The enum gives me to add only valid values that it contains, but I also can add a null elements to it.

So, to prevent saving null elements to DB, I added a filter in the app, but I wonder if there is a definition in PostgreSQL not to allow adding null elements to array?

P.S. I saw here suggestion to add function as part of the column definition, but this is not what I asked.

2 Answers 2

4

You can add a check constraint to prevent elements with NULL values.

alter table my_table
  add constraint no_null_element 
  check (cardinality(my_column) = cardinality(array_remove(my_column, null)));

A cleaner solution would be a normalized one-to-many relationship with a foreign key column defined as not null

Sign up to request clarification or add additional context in comments.

1 Comment

It will be faster and use less RAM to define the check as CHECK (array_position(my_column, NULL) IS NULL). Then you're not allocating a new array in memory and populating it with values just to perform a check.
-2

another way

IF array_length(arrayname, 1) > 0 THEN transactions END IF;

Comments

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.