1

I have a table books with rows as below:

The genres field is an array of enum that contains the book genre, and these are its possible values: ['adventure', 'horror', 'romance']

title genres
Deadlock {Horror}
Sunny Hills {Romance, Adventure}
Exiled Prince {Adventure}

I tried:

SELECT * FROM books
WHERE genres = ARRAY['Adventure']::book_genres_enum[];

But that only returns the 'Exiled Prince' book.
How do I formulate a query for all rows containing 'Adventure' in its genres array?

1 Answer 1

2

The simple query is with = ANY:

SELECT * FROM books
WHERE  'Adventure'::book_genres_enum = ANY(genres)

This works with any type of array. Nothing special about an enum type in this regard. See:

The explicit cast is optional. When passing 'Adventure' as untyped string literal, the data type is derived from context. (May not work with typed values.)

Index

If the table is big and you have a GIN index on books(genres), use array operators instead. This query is equivalent:

SELECT * FROM books
WHERE  genres @> '{Adventure}'::book_genres_enum[];

Why?

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

2 Comments

Thank you! I didn't know regular array operators worked with enum types.
@GashioLee: They do because they work with any type.

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.