How to get distinct array elements with postgres?

后端 未结 3 724
忘掉有多难
忘掉有多难 2021-01-14 00:23

I have an array with duplicate values in postgres. For example:

SELECT cardinality(string_to_array(\'1,2,3,4,4\', \',\')::int[]) as foo
=> \"foo\"=>\"5         


        
3条回答
  •  無奈伤痛
    2021-01-14 00:28

    I prefer this syntax (about 5% faster)

    create or replace function public.array_unique(arr anyarray)
    returns anyarray as $body$
        select array( select distinct unnest($1) )
    $body$ language 'sql';
    

    using:

    select array_unique(ARRAY['1','2','3','4','4']);
    

提交回复
热议问题