Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL check if array contains any element from left-hand array

I know that in PostgreSQL you can run a query like:

SELECT (1 = ANY('{1,3,4,7}'::int[])) AS result to check if the right-hand array contains the element 1. I was wondering if there is an easy way to check if the right-hand array contains any element from the left-hand array. Something like:

SELECT ('{2,3}'::int[] = ANY('{1,3,4,7}'::int[])) AS result

Is there an easy way to do this without iterating over the left-hand loop myself?

like image 447
Lander Avatar asked Feb 13 '14 00:02

Lander


People also ask

How do you check if a value is present in an array Postgres?

To check if an array contains a specific value, use the IN operator with UNNEST . To check if an array contains a value matching a condition, use the EXISTS operator with UNNEST .

How do I query an array in PostgreSQL?

Using unnest() expands an array to multiple rows. The non-array columns get repeated for each row.

How do you check if array is empty in Postgres?

IF array_length(id_clients, 1) > 0 THEN query := query || format(' AND id = ANY(%L))', id_clients); END IF; This excludes both empty array and NULL. Or use cardinality() in Postgres 9.4 or later.


1 Answers

Sure, use the && array-overlaps operator:

SELECT ARRAY[1,2] && ARRAY[1,3,4,7]; 

See array functions and operators.

like image 117
Craig Ringer Avatar answered Sep 21 '22 13:09

Craig Ringer