Search code examples
sqlpostgresqlpattern-matchingdbplyrsql-in

postgres match through two lists (list in list)


I'd like to know if there is a way to check if there is at least one string in list a which matches in list b.

> select 1 IN (1,2);
 ?column? 
----------
 t
(1 row)

In the case above I'm only checking 1 value against a list.

But if I try as below I got error.

=> select (1, 3) IN (1,2);
ERROR:  operator does not exist: record = integer
LINE 1: select (1, 3) IN (1,2);
                      ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.


=> select ANY((1, 3) IN (1,2));
ERROR:  syntax error at or near "ANY"
LINE 1: select ANY((1, 3) IN (1,2));

How do I perform this query??

Thanks in advance


Solution

  • You could use arrays instead of lists, and the overlaps operator:

    select array[1, 3] && array[1, 2];
    

    Yields

    true
    

    If you are starting from comma-delimited strings, you can use string_to_array() first:

    select string_to_array('1,3', ',') && string_to_array('1,2', ',')