Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres WHERE two arrays have a non-empty intersection

I have a table with a column tags of type varchar [].

I would like to select all rows where the tags contains at least one of a set of values.

Something like this:

-- Not real code
SELECT * 
FROM foo 
WHERE non_empty(set_intersection(tags, '{ "apples", "bananas", "cherries" }'))

What is the syntax for this?


I know I can do a series of ORs but that seems less elegant.

like image 657
sdgfsdh Avatar asked Mar 10 '20 09:03

sdgfsdh


People also ask

How to Compare two arrays in PostgreSQL?

The equality operators ( = , <> ) do an exact element-by-element comparison. The ordering operators ( > , < , >= , <= ) also compare each element in an array in order. Results are based on the first different pair of elements, not the sizes of the arrays.

What does the PostgreSQL Unnest () function do?

Unnest function generates a table structure of an array in PostgreSQL. Unnest array function is beneficial in PostgreSQL for expanding the array into the set of values or converting the array into the structure of the rows. PostgreSQL offers unnest() function.

Which of the following are built PostgreSQL functions for arrays?

array_to_string() function This function is used to concatenate array elements using supplied delimiter and optional null string.


Video Answer


1 Answers

You can use &&, the array overlap operator:

select *
from foo
where tags && ARRAY['apples', 'bananas', 'cherries']

From the documentation:

&&: overlap (have elements in common)

like image 181
GMB Avatar answered Oct 08 '22 22:10

GMB