Thread: array_cat without duplicity

array_cat without duplicity

From
Ondřej Fafejta
Date:
Hi!

Postgresql: version 8.1.11

Is there a way to concatenate two arrays without duplicity?

This select return duplicity:

SELECT array_cat(ARRAY[1,2], ARRAY[2,3]);
 array_cat
-----------
 {1,2,2,3}

I need to get result without duplicity!
 {1,2,3}

Thx
Fafi

Re: array_cat without duplicity

From
Volkan YAZICI
Date:
On Wed, 19 Mar 2008, Ondřej Fafejta <ondrej.fafejta@kyberie.cz> writes:
> SELECT array_cat(ARRAY[1,2], ARRAY[2,3]);
> array_cat
> -----------
> {1,2,2,3}
>
> I need to get result without duplicity!
> {1,2,3}

I don't know any builtin way of achieving such a thing. But you may want
to use intarray contrib module or implement your own PL function to
remove duplicates from an array.


Regards.

Re: array_cat without duplicity

From
David Fetter
Date:
On Wed, Mar 19, 2008 at 03:05:06PM +0100, Ondřej Fafejta wrote:
> Hi!
>
> Postgresql: version 8.1.11
>
> Is there a way to concatenate two arrays without duplicity?
>
> This select return duplicity:
>
> SELECT array_cat(ARRAY[1,2], ARRAY[2,3]);
> array_cat
> -----------
> {1,2,2,3}
>
> I need to get result without duplicity!
> {1,2,3}

Here's a function in SQL that does what you want.

CREATE OR REPLACE FUNCTION array_undup(ANYARRAY)
RETURNS ANYARRAY
LANGUAGE SQL
AS $$
SELECT ARRAY(
    SELECT DISTINCT $1[i]
    FROM generate_series(
        array_lower($1,1),
        array_upper($1,1)
    ) AS i
);
$$;

SELECT array_undup(array_cat(ARRAY[1,2], ARRAY[2,3]));
 array_undup
-------------
 {1,2,3}
(1 row)

Cheers,
David.
--
David Fetter <david@fetter.org> http://fetter.org/
Phone: +1 415 235 3778  AIM: dfetter666  Yahoo!: dfetter
Skype: davidfetter      XMPP: david.fetter@gmail.com

Remember to vote!
Consider donating to Postgres: http://www.postgresql.org/about/donate