Re: simple SQL query

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: "Kevin Duffy" <KD(at)wrinvestments(dot)com>
Cc: "Andreas Joseph Krogh" <andreak(at)officenet(dot)no>, pgsql-sql(at)postgresql(dot)org, "Oliveiros Cristina" <oliveiros(dot)cristina(at)marktest(dot)pt>
Subject: Re: simple SQL query
Date: 2008-10-30 02:30:59
Message-ID: 3038.1225333859@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

"Kevin Duffy" <KD(at)wrinvestments(dot)com> writes:
> Can someone explain why the NULL ISINs in Security is causing
> so much grief? I do not get it.

NULL generally is taken as "unknown" in SQL comparisons. So if you have
any nulls in the output of the sub-select, what the upper select sees
is a situation like

where 42 NOT IN (1,2,3, ..., NULL, ...)

Now, if it finds 42 in the subquery output, it can say definitively that
the result of NOT IN is FALSE, because 42 clearly *is* in the output.
However, if it doesn't find a match, then what does that NULL represent?
It's unknown, and therefore whether it's equal to 42 is unknown, and so
the result of the NOT IN is unknown. And WHERE treats an unknown result
the same as FALSE, so you don't get an output row from the upper query.

NOT IN is generally pretty evil and best avoided: the funny behavior
with nulls makes it not only a trap for novices, but hard for the system
to optimize. Consider recasting as NOT EXISTS instead.

regards, tom lane

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message gherzig 2008-10-30 10:26:34 Re: trying to repair a bad header block
Previous Message Scott Marlowe 2008-10-30 01:25:18 Re: trying to repair a bad header block