Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find records based on enum value in postgresql

Let’s say I have a BOOKS table with the records below below:

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

Record 1

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

title: 'Deadlock'
genres: ['Horror']

Record 2

title: 'Sunny Hills'
genres: ['Romance', 'Adventure']

Record3

title: 'Exiled Prince'
genres: ['Adventure']

I did something like this:

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

With the query above, I’m only able to get the ‘Exiled Prince’ book. With the records above, how do I formulate a query that can get all the records that has Adventure in its genre?

>Solution :

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.

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

Index

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

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

Why?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading