Check Value in Array Using UbiqUbiq Reporting tool supports all the above SQL queries and makes it easy to visualize SQL results in different ways.
To query if the array field contains at least one element with the specified value, use the filter { <field>: <value> } where <value> is the element value. To specify conditions on the elements in the array field, use query operators in the query filter document: { <array field>: { <operator1>: <value1>, ... } }
PostgreSQL UNNEST() function This function is used to expand an array to a set of rows.
This should work:
select * from mytable where 'Journal'=ANY(pub_types);
i.e. the syntax is <value> = ANY ( <array> )
. Also notice that string literals in postresql are written with single quotes.
With ANY operator you can search for only one value.
For example,
SELECT * FROM mytable WHERE 'Book' = ANY(pub_types);
If you want to search multiple values, you can use @> operator.
For example,
SELECT * FROM mytable WHERE pub_types @> '{"Journal", "Book"}';
You can specify in which ever order you like.
Although perhaps not the most efficient approach, this worked for me:
select * from mytable
where array_to_string(pub_types, ',') like '%Journal%'
However, using the contains operater @>
(see Sudharsan Thumatti's answer above) is probably a more performant choice since it uses a B-Tree comparison function per PostgreSQL docs.
Depending on your normalization needs, it might be better to implement a separate table with a FK reference as you may get better performance and manageability.
Instead of IN
we can use ANY
with arrays casted to enum array, for example:
create type example_enum as enum (
'ENUM1', 'ENUM2'
);
create table example_table (
id integer,
enum_field example_enum
);
select
*
from
example_table t
where
t.enum_field = any(array['ENUM1', 'ENUM2']::example_enum[]);
Or we can still use 'IN' clause, but first, we should 'unnest' it:
select
*
from
example_table t
where
t.enum_field in (select unnest(array['ENUM1', 'ENUM2']::example_enum[]));
Example: https://www.db-fiddle.com/f/LaUNi42HVuL2WufxQyEiC/0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With