Re: [SQL] Simple way to get missing number

From: Steve Crawford <scrawford(at)pinpointresearch(dot)com>
To: emilu(at)encs(dot)concordia(dot)ca
Cc: pgsql-sql(at)postgresql(dot)org, "pgsql-general(at)postgresql(dot)org >> \"pgsql-general(at)postgresql(dot)org\"" <pgsql-general(at)postgresql(dot)org>
Subject: Re: [SQL] Simple way to get missing number
Date: 2012-04-24 18:56:06
Message-ID: 4F96F746.1090909@pinpointresearch.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general pgsql-sql

On 04/24/2012 11:10 AM, Emi Lu wrote:
> I got it and thank you very much for everyone's help!!
>
> It seems that "left join where is null" is faster comparing with
> "except". And my final query is:
>
> select num as missing
> from generate_series(5000, #{max_id}) t(num)
> left join t1 on (t.num = t1.id)
> where t1.id is null;
>

BTW, there are many options. Two more of them include EXISTS:

select allnumbers from generate_series(1,15) as allnumbers where not
exists (select 1 from fooo where fooo.anumber=allnumbers.allnumbers);

And IN:

select allnumbers from generate_series(1,15) as allnumbers where
allnumbers not in (select anumber from fooo);

They all give you the same result. The "right" choice will depend on the
size of your table, how it is indexed, how fully it is populated and
even on your version of PostgreSQL. (Apologies for the funky field/table
naming.)

Cheers,
Steve

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Vick Khera 2012-04-24 19:39:24 Re: how robust are custom dumps?
Previous Message Lonni J Friedman 2012-04-24 18:21:10 Re: pg_basebackup issues

Browse pgsql-sql by date

  From Date Subject
Next Message Andreas 2012-04-24 20:01:31 generic crosstab ?
Previous Message Andreas 2012-04-24 18:39:28 How to group by similarity?