5

I'm using PostgreSQL 9.5. I want create an array with a fixed size, like this:

CREATE TABLE eco.test ( 
    id           text  NOT NULL,
    test_array   integer[3],
    CONSTRAINT pk_aircrafts PRIMARY KEY ( id )
 );

That is, I want the size of test_array will be 3.

But, I can make this:

INSERT INTO eco.test(id, test_array) VALUES ('1', '{1,2,3,4}')

And everything will be fine.

select * from eco.test;
id | test_array
'1'   {1,2,3,4}

How can I make a fixed size array?

1 Answer 1

10

Create a CHECK constraint that forces array_ndims(test_array) = 1 AND array_length(test_array, 1) = 3.

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

4 Comments

alternatively use cardinality() with 9.5
Is this still the best answer in 2021?
@elimisteve To my knowledge, yes.
As of Postgresql 16, still the same. You can check at postgresql.org/docs/current/arrays.html. As of today: "[...] However, the current implementation ignores any supplied array size limits, i.e., the behavior is the same as for arrays of unspecified length."

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.