Received: from maia.hub.org (maia-5.hub.org [200.46.204.29]) by mail.postgresql.org (Postfix) with ESMTP id 9705C1337B4F for ; Mon, 29 Nov 2010 11:27:10 -0400 (AST) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.29]) (amavisd-maia, port 10024) with ESMTP id 17630-08 for ; Mon, 29 Nov 2010 15:27:05 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by mail.postgresql.org (Postfix) with ESMTP id F0C321337B93 for ; Mon, 29 Nov 2010 11:27:02 -0400 (AST) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.2/8.14.2) with ESMTP id oATFR0sX025302; Mon, 29 Nov 2010 10:27:01 -0500 (EST) To: Jasen Betts cc: Jorge Arenas , pgsql-sql@postgresql.org Subject: Re: subselect and left join not working? In-reply-to: References: <749730.36457.qm@web113802.mail.gq1.yahoo.com> Comments: In-reply-to Jasen Betts message dated "29 Nov 2010 09:44:44 +0000" Date: Mon, 29 Nov 2010 10:27:00 -0500 Message-ID: <25301.1291044420@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.91 tagged_above=-5 required=5 tests=BAYES_00=-1.9, T_RP_MATCHES_RCVD=-0.01 X-Spam-Level: X-Archive-Number: 201011/82 X-Sequence-Number: 34820 Jasen Betts writes: > On 2010-11-29, Jorge Arenas 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