2

I have a roles field in a Users table of type Array. I need to be able to get all users that have both role 'admin' and role 'member'. FOr now I use this query:

select * from users where 'member' = ANY(roles) and 'admin' = ANY(roles);

I was wondering if there was a cleaner way to do this.

1 Answer 1

9

Use the array-contained-by operator @<:

select * from users where ARRAY['member','admin']::varchar[] <@ roles;

That'll let you index the lookup too.

(Correction per @bereal; I misread the question)

Or, if you meant that they must have both rights, use array-overlaps &&:

select * from users where ARRAY['member','admin']::varchar[] && roles;

Also, as your input turns out to be varchar[] (you didn't show your table definition), you must cast the array input to varchar[] too, as there's no implicit cast between array types.

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

4 Comments

As far as I understand, that will be equal to 'member' = ANY(roles) OR 'admin' = ANY(roles), so rather <@ aka "is contained by".
Using that method, I get: ERROR: operator does not exist: text[] && character varying[]
@yossarian There's no implicit cast from text[] to varchar[] so you have to cast explicitly; see edit.
@yossarian You should rewrite your question to I need to be able to get all users that have both role 'admin' and role 'member'

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.