X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [64.117.224.130]) by svr1.postgresql.org (Postfix) with ESMTP id 18D1ED1C4C8 for ; Wed, 13 Aug 2003 00:52:55 +0000 (GMT) Received: from svr1.postgresql.org ([64.117.224.193]) by localhost (neptune.hub.org [64.117.224.130]) (amavisd-new, port 10024) with ESMTP id 38953-02 for ; Tue, 12 Aug 2003 21:51:24 -0300 (ADT) Received: from megazone.bigpanda.com (45.mufb.snfc.sffca01r18.dsl.att.net [12.103.249.45]) by svr1.postgresql.org (Postfix) with ESMTP id D00E0D1C47A for ; Tue, 12 Aug 2003 21:52:43 -0300 (ADT) Received: by megazone.bigpanda.com (Postfix, from userid 1001) id 9B22ED60F; Tue, 12 Aug 2003 17:52:47 -0700 (PDT) Received: from localhost (localhost [127.0.0.1]) by megazone.bigpanda.com (Postfix) with ESMTP id 90CB35C0D; Tue, 12 Aug 2003 17:52:47 -0700 (PDT) Date: Tue, 12 Aug 2003 17:52:47 -0700 (PDT) From: Stephan Szabo To: krystoffff Cc: Subject: Re: How to optimize this query ? In-Reply-To: <85898f7e.0308121021.4c66aae5@posting.google.com> Message-ID: <20030812174840.R27097-100000@megazone.bigpanda.com> MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII X-Virus-Scanned: by amavisd-new at postgresql.org X-Archive-Number: 200308/121 X-Sequence-Number: 14737 On 12 Aug 2003, krystoffff wrote: > Hi all > > I have to optmize this query, because it takes a while to run (about > 30s) > > Here are the tables (with the keys): > affiliate_lockout (6 rows) (member_id, affiliate_id) > lead (4490 rows) (id, ...) > member (6 rows) (id, ...) > member_exclusion (3 rows) (member_id, member_id_to_exclude) > purchase (10000 rows) (lead_id, member_id, ...) > I think you can possibly get better results in 7.3 and earlier by using NOT EXISTS. > Here is the query: > SELECT * > FROM lead > WHERE > (exclusive IS NULL OR (exclusive = 0 AND nb_purchases < 3)) AND > NOT EXISTS ( select lead_id from purchase where lead_id=lead.id and member_id=21101) > id NOT IN ( > SELECT lead_id > FROM purchase > WHERE member_id = 21101 AND NOT EXISTS ( select * from affiliate_lockout WHERE member_id=21101 and affiliate_locked_id=lead.affiliate_id) > ) AND affiliate_id NOT > IN ( > > SELECT affiliate_locked_id > FROM affiliate_lockout > WHERE member_id = 21101 > ) AND id NOT > IN ( > > SELECT lead_id > FROM purchase > INNER JOIN member_exclusion > WHERE purchase.member_id = member_exclusion.member_id_to_exclude AND > purchase.member_id = 21101 Doesn't this condition end up giving you a subset of the rows in the first one?