Received: from localhost (maia-1.hub.org [200.46.204.191]) by postgresql.org (Postfix) with ESMTP id ABCCF9FBA5E for ; Thu, 15 Feb 2007 11:44:48 -0400 (AST) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.191]) (amavisd-new, port 10024) with ESMTP id 42674-01 for ; Thu, 15 Feb 2007 11:44:34 -0400 (AST) X-Greylist: from auto-whitelisted by SQLgrey-1.7.4 Received: from mail.metronet.co.uk (mail.metronet.co.uk [213.162.97.75]) by postgresql.org (Postfix) with ESMTP id E8B509FB940 for ; Thu, 15 Feb 2007 11:44:34 -0400 (AST) Received: from server3.office.archonet.com (84-51-143-99.archon037.adsl.metronet.co.uk [84.51.143.99]) by smtp.metronet.co.uk (MetroNet Mail) with ESMTP id 8484A76273; Thu, 15 Feb 2007 15:44:33 +0000 (GMT) Received: from [192.168.1.36] (dell36.office.archonet.com [192.168.1.36]) by server3.office.archonet.com (Postfix) with ESMTP id 3C11A274033; Thu, 15 Feb 2007 15:44:33 +0000 (GMT) Message-ID: <45D47FE1.5010209@archonet.com> Date: Thu, 15 Feb 2007 15:44:33 +0000 From: Richard Huxton User-Agent: IceDove 1.5.0.9 (X11/20061220) MIME-Version: 1.0 To: philippe Cc: pgsql-performance@postgresql.org Subject: Re: Slow query with 'or' clause References: <1171550213.45d470056249c@ssl0.ovh.net> In-Reply-To: <1171550213.45d470056249c@ssl0.ovh.net> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=0.284 tagged_above=0 required=5 tests=AWL, BAYES_50, FORGED_RCVD_HELO, HOT_NASTY X-Spam-Level: X-Archive-Number: 200702/170 X-Sequence-Number: 23224 philippe wrote: > explain analyse > select count(*) from client_contact > left join client_company using(cli_id) > where (cli_mail = 'xxx@xxx.xx') OR > (lower(cli_nom) = 'xxxxxx' and zipcode = '10001'); > > QUERY PLAN > ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- > Aggregate (cost=37523.98..37523.99 rows=1 width=0) (actual > time=3871.086..3871.087 rows=1 loops=1) > -> Merge Left Join (cost=0.00..36719.10 rows=321952 width=0) (actual > time=3871.058..3871.058 rows=0 loops=1) This is the root of the problem - it's expecting to match over 320000 rows rather than 0. I'm guessing there's a lot of correlation between cli_mail and cli_nom (you're expecting them to match the same clients) but the planner doesn't know this. If this is a common query, you could try an index on zipcode - that might cut down the other side. However, I have to ask why you're using a left-join? Do you really have rows in client_contact without a matching cli_id in client_company? -- Richard Huxton Archonet Ltd