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

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";
1
  • 1
    Both of our answers worked but since you provided better commenting and an online SQL tool I selected your answer. Mar 7, 2018 at 13:59
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]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.