0

I don't know how work with loops and arrays in PostgreSQL but i want make table with array which only accepts the given values.
('Icelandic','English','Polish','Danish','Norwegian','Swedish','French','German','Spanish')
How write this condition in shorter and prettier form?

 CREATE TABLE Test(
        UUID UUID NOT NULL PRIMARY KEY ,
        Name varchar(40) NOT NULL UNIQUE , --
        Languages text[] NOT NULL CHECK (
        Languages[1] IN (
        'Icelandic','English','Polish','Danish','Norwegian',
         'Swedish','French','German','Spanish'
            )
        AND
            Languages[2] IN (
        'Icelandic','English','Polish','Danish','Norwegian',
         'Swedish','French','German','Spanish'
            )
        AND
            Languages[3] IN (
        'Icelandic','English','Polish','Danish','Norwegian',
         'Swedish','French','German','Spanish'
            )
        AND
            Languages[4] IN (
        'Icelandic','English','Polish','Danish','Norwegian',
         'Swedish','French','German','Spanish'
            )
        AND
            Languages[5] IN (
        'Icelandic','English','Polish','Danish','Norwegian',
         'Swedish','French','German','Spanish'
            )     AND
            Languages[5] IN (
        'Icelandic','English','Polish','Danish','Norwegian',
         'Swedish','French','German','Spanish'
            )
        AND
            Languages[6] IN (
        'Icelandic','English','Polish','Danish','Norwegian',
         'Swedish','French','German','Spanish'
            )
        AND
            Languages[7] IN (
        'Icelandic','English','Polish','Danish','Norwegian',
         'Swedish','French','German','Spanish'
            )     AND
            Languages[8] IN (
        'Icelandic','English','Polish','Danish','Norwegian',
         'Swedish','French','German','Spanish'
            )
        AND
            Languages[9] IN (
        'Icelandic','English','Polish','Danish','Norwegian',
         'Swedish','French','German','Spanish'
            ) )
    
    );

1 Answer 1

3

A better solution would be to use the @> or <@ operators as described here https://www.postgresql.org/docs/12/functions-array.html

...CHECK (languages <@ ARRAY['Icelandic','English','Polish','Danish','Norwegian','Swedish','French','German','Spanish'])

However I suggest you use the common two-or-three letter language codes, instead of the full names. It's just more useful during migrations.

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

1 Comment

Thanks for sollution and hint about langues codes ;)

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.