Received: from localhost (unknown [200.46.208.211]) by mail.postgresql.org (Postfix) with ESMTP id 2BB3B634131 for ; Fri, 22 May 2009 18:05:36 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by localhost (mx1.hub.org [200.46.208.211]) (amavisd-maia, port 10024) with ESMTP id 49504-06 for ; Fri, 22 May 2009 18:05:30 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from smtp206.iad.emailsrvr.com (smtp206.iad.emailsrvr.com [207.97.245.206]) by mail.postgresql.org (Postfix) with ESMTP id 0FE19633F5D for ; Fri, 22 May 2009 18:05:34 -0300 (ADT) Received: from relay30.relay.iad.mlsrvr.com (localhost [127.0.0.1]) by relay30.relay.iad.mlsrvr.com (SMTP Server) with ESMTP id C70C81B403A for ; Fri, 22 May 2009 17:05:33 -0400 (EDT) Received: by relay30.relay.iad.mlsrvr.com (Authenticated sender: ejones-AT-engineyard.com) with ESMTPSA id 71B3C1B400D; Fri, 22 May 2009 17:05:33 -0400 (EDT) Cc: PostgreSQL SQL List Message-Id: <2B64F21F-E180-4F61-82D6-A5252055EEC6@engineyard.com> From: Erik Jones To: emilu@encs.concordia.ca In-Reply-To: <4A17106F.7040302@encs.concordia.ca> Content-Type: text/plain; charset=US-ASCII; format=flowed; delsp=yes Content-Transfer-Encoding: 7bit Mime-Version: 1.0 (Apple Message framework v930.3) Subject: Re: left join where not null vs. inner join Date: Fri, 22 May 2009 14:05:32 -0700 References: <4A17106F.7040302@encs.concordia.ca> X-Mailer: Apple Mail (2.930.3) X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200905/103 X-Sequence-Number: 32595 On May 22, 2009, at 1:51 PM, Emi Lu wrote: > Two tables, each contains more than hundreds of thousands records. > Is there any efficiency differences between (1) and (2)? > > (1) T1 inner join T2 using (c1, c2) > > > (2) T1 left join T2 using (c1, c2) where c2 is not null Yes, stick with the first. In the second you're asking the db to generate a result set with tuples for every row in T1 and then filter it down to where there are only matching T2 rows whereas in the first it does the filtering as it goes. The LEFT JOIN ... WHERE X NOT NULL construct is typically used as an alternative to a NOT IN or NOT EXISTS (). So, this: SELECT * FROM t1 WHERE id NOT IN (SELECT some_id FROM T2); becomes SELECT t1.* FROM t1 LEFT JOIN t2 ON (t1.id = t2.some_id) WHERE t2.id IS NULL; Basically, it's used in the opposite case of what you're asking about. Erik Jones, Database Administrator Engine Yard Support, Scalability, Reliability 866.518.9273 x 260 Location: US/Pacific IRC: mage2k