Re: array_except -- Find elements that are not common to both arrays

From: bricklen <bricklen(at)gmail(dot)com>
To: Merlin Moncure <mmoncure(at)gmail(dot)com>
Cc: "pgsql-performance(at)postgresql(dot)org" <pgsql-performance(at)postgresql(dot)org>
Subject: Re: array_except -- Find elements that are not common to both arrays
Date: 2011-09-30 03:27:44
Message-ID: CAGrpgQ-Zo6FOtc=NtY-4wXcnYqQRgcRLDR3BGQk2nAXpW46rzA@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-performance

On Thu, Sep 29, 2011 at 8:08 PM, Merlin Moncure <mmoncure(at)gmail(dot)com> wrote:
> *) Prefer union all to union
> *) prefer array constructor to array_agg when not grouping.
> *) perhaps consider not reusing 'except' name with different semantic
> meaning
>
> Well done
> merlin (on phone & in bed)

Hi Merlin,

Thanks for the tips. I have implemented suggestion 1 & 2, and that has
shaved about 1/2 of a second off of the generate_series example below
(3.52s -> 3.48s)

Do you have a suggestion for a better name? I considered array_unique,
array_distinct etc, but those don't really describe what is being
returned IMO. Something that conjures up the "return elements that are
not common to both arrays" would be nice.

create or replace function array_except(anyarray,anyarray) returns
anyarray as $$
select ARRAY(
(
select r.*
from (
(select unnest($1) except select unnest($2))
union all
(select unnest($2) except select unnest($1))
) as r (elements)
))
$$ language sql strict immutable;

select array_except('{this,is,a,test}'::text[],'{also,part,of,a,test}'::text[]);

select array_to_relation(arr)
from array_except( (select array_agg(n) from
generate_series(1,1000000,1) as n) , (select array_agg(n) from
generate_series(5,1000005,1) as n) ) as arr;

More improvement suggestions gladly accepted!

In response to

Responses

Browse pgsql-performance by date

  From Date Subject
Next Message Venkat Balaji 2011-09-30 05:22:30 Re: : Create table taking time
Previous Message Merlin Moncure 2011-09-30 03:08:19 Re: array_except -- Find elements that are not common to both arrays