Search code examples
arrayspostgresqlgroup-byany

PostgreSQL: Compare Two Arrays Is Any One Value Exists In Second Array


I am trying to join two tables and each table having one array column. And my intension is to compare two arrays if any value of the first array exists in the second array.

I am writing where clause like below

any(table1.array1) = any(table2.array2)

But it is not working for me.


Solution

  • Operator && should do the trick. This will return if any of elements in Array1 is present in Array2. Refer to PostgreSQL document here: Array Operators

    select array[1,2,3] && array[2,4,5], array[1,2,3] && array[4,5, 6], array[1,2,3] && array[1]
    Output: true, false, true
    

    If you are looking if all the elements present in second array, you should use @> or <@