2

Given this example:

Table:

CREATE TABLE public.animals
(
  name character varying(64),
  whitelist animal_whitelist[]
)

Custom enum type animal_whitelist:

CREATE TYPE public.animal_whitelist AS ENUM
  ('dog',
  'cat',
  'bird');

How can I select specifically to the white list.

In pseudo code this is what I would like to select.

  • Any rows where the animal_whitelist equals dog
  • Any rows where the animal_whitelist equals dog and cat
  • Any rows where the animal_whitelist equals dog or cat
  • Any rows where the animal_whitelist is not dog, cat, or bird
2
  • 3
    Start with the documentation: postgresql.org/docs/9.6/static/functions-array.html. Commented Mar 6, 2018 at 13:11
  • I have tried a lot of different things otherwise I wouldn't have posted here. It get's weird because it's an array of enums. Contains @> gets me close Commented Mar 6, 2018 at 13:13

2 Answers 2

7

Please, check this one:

    insert into animals ("name", "whitelist") values ('bobic', array['dog']::animal_whitelist[]);
insert into animals ("name", "whitelist") values ('barsic', array['cat']::animal_whitelist[]);
insert into animals ("name", "whitelist") values ('pet', array['dog', 'cat', 'bird']::animal_whitelist[]);
insert into animals ("name") values ('jim');


-- Any rows where the animal_whitelist equals dog
select * from animals where  array['dog']::animal_whitelist[] = "whitelist" ;

-- Any rows where the animal_whitelist equals dog and cat
select * from animals where  array['dog', 'cat']::animal_whitelist[] = "whitelist" ;

-- Any rows where the animal_whitelist equals dog or cat
select * from animals where  array['dog', 'cat']::animal_whitelist[] <@ "whitelist" ;

-- Any rows where the animal_whitelist is not dog, cat, or bird
select * from animals where not array['dog', 'cat', 'bird']::animal_whitelist[] && "whitelist";
Sign up to request clarification or add additional context in comments.

1 Comment

Both of our answers worked but since you provided better commenting and an online SQL tool I selected your answer.
1

I think I figured it out with some more experimentation

  1. SELECT * FROM animals WHERE whitelist @> ARRAY['dog'::whitelist]

  2. SELECT * FROM animals WHERE whitelist @> ARRAY['dog'::whitelist, 'cat'::whitelist] AND NOT whitelist @> ARRAY['bird'::whitelist]

  3. SELECT * FROM animals WHERE whitelist @> ARRAY['dog'::whitelist] OR whitelist @> ARRAY['cat'::whitelist]

  4. SELECT * FROM animals WHERE NOT whitelist @> ARRAY['dog'::whitelist, 'cat'::whitelist, 'bird'::whitelist]

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.