Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed size array in PostgreSQL 9.5

Tags:

postgresql

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?

like image 542
user7198142 Avatar asked Jan 05 '23 23:01

user7198142


1 Answers

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

like image 179
Laurenz Albe Avatar answered Jan 07 '23 12:01

Laurenz Albe