Re: subselect and left join not working?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Jasen Betts <jasen(at)xnet(dot)co(dot)nz>
Cc: Jorge Arenas <jorge(dot)arenas(at)kamarble(dot)com>, pgsql-sql(at)postgresql(dot)org
Subject: Re: subselect and left join not working?
Date: 2010-11-29 15:27:00
Message-ID: 25301.1291044420@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Jasen Betts <jasen(at)xnet(dot)co(dot)nz> writes:
> On 2010-11-29, Jorge Arenas <jorge(dot)arenas(at)kamarble(dot)com> wrote:
>> select zona_id from zonas where zona_id not in (select zona_id from usuarios
> ####### ####### #######
>> where per_id =2)

> select 'FRED' from from usuarios where per_id =2

> what'shappening is your not in subquery is being 'corrupted' by the
> surrounding query, the expression zona_id is being replaced with the
> value from the main query. so the inner query return multiple copies
> of the value from the outer query and the not-in fails.

That explanation is nonsense, and so is the proposed fix.

What I suspect is really going on is that the subselect yields one or
more NULL values. If there's a NULL then NOT IN can never return TRUE,
only FALSE (if the tested value is definitely present) or NULL (meaning
it might match one of the NULLs, because NULL means "unknown" in this
context). Newbies get caught by that all the time :-( ... it's not one
of SQL's better features.

regards, tom lane

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Jorge Arenas 2010-11-30 04:29:52 Re: subselect and left join not working?
Previous Message Jasen Betts 2010-11-29 09:44:44 Re: subselect and left join not working?