Skip to content
Advertisement

Compare two arrays and count number of the same strings

I would like to compare two arrays in two columns and in the third column return the number of the same strings within those two arrays.

|---------------------|------------------|------------------|
|      column 1       |     column 2     |     column 3     |
|---------------------|------------------|------------------|
|   [cat, dog, bird]  |   [cat, bird]    |          2       |
|---------------------|------------------|------------------|
|  [cat, bear, tiger] |      [tiger]     |          1       |
|---------------------|------------------|------------------|
|    [cat, tiger]     |  [tiger, cat]    |          2       |
|---------------------|------------------|------------------|

Advertisement

Answer

You can use unnest(). Assuming that the individual arrays have no duplicates:

with t as (
      select array['cat', 'dog', 'bird'] as column1, array['cat', 'bird'] as column2 union all
      select array['cat', 'bear', 'tiger'], array['tiger'] union all
      select array['cat', 'tiger'], array['tiger', 'cat']
     )
select t.*,
       (select count(*)
        from unnest(column1) el1 join
             unnest(column2) el2
             on el1 = el2
       ) as column3
from t;
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement