Search code examples
sqlarrayspostgresqlaggregate-functionsset-returning-functions

Find duplicated values on array column


I have a table with a array column like this:

my_table
id   array
--   -----------
1    {1, 3, 4, 5}
2    {19,2, 4, 9}
3    {23,46, 87, 6}
4    {199,24, 93, 6}

And i want as result what and where is the repeated values, like this:

value_repeated    is_repeated_on
--------------    -----------
4                 {1,2}
6                 {3,4}

Is it possible? I don't know how to do this. I don't how to start it! I'm lost!


Solution

  • Use unnest to convert the array to rows, and then array_agg to build an array from the ids

    It should look something like this:

    SELECT v AS value_repeated,array_agg(id) AS is_repeated_on FROM 
    (select id,unnest(array) as v from my_table) 
    GROUP by v HAVING Count(Distinct id) > 1
    

    Note that HAVING Count(Distinct id) > 1 is filtering values that don't appear even once