4

Is there any way to add a constraint on a column that is an array to limit it's length? I want these arrays to be no longer than 6. And yes, I understand that often a new table is better than storing in an array but I am in a situation where an array makes more sense.

1 Answer 1

10

You can add a CHECK constraint to the table definition:

CREATE TABLE my_table (
    id  serial PRIMARY KEY,
    arr int[] CHECK (array_length(arr, 1) < 7),
    ...
);

If the table already exists, you can add the constraint with ALTER TABLE:

ALTER TABLE my_table ADD CONSTRAINT arr_len CHECK (array_length(arr, 1) < 7);
Sign up to request clarification or add additional context in comments.

1 Comment

Since 9.4 you can also use cardinality(arr) instead

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.