Received: from localhost (postgresql.org [64.49.215.8]) by postgresql.org (Postfix) with ESMTP id 687B7475E45 for ; Tue, 3 Dec 2002 14:01:38 -0500 (EST) Received: from l2.socialecology.com (unknown [4.42.179.131]) by postgresql.org (Postfix) with ESMTP id D05C14758E1 for ; Tue, 3 Dec 2002 14:01:37 -0500 (EST) Received: from 4.42.179.151 (broccoli.socialecology.com [4.42.179.151]) by l2.socialecology.com (Postfix) with SMTP id 486A92739AB for ; Tue, 3 Dec 2002 11:01:37 -0800 (PST) X-Mailer: UserLand Frontier 8.0.5 (Macintosh OS) (mailServer v1.1..142) Mime-Version: 1.0 Message-Id: <57018518.1173209203@[4.42.179.151]> X-authenticated-sender: erics X-GSgroup: private Date: Tue, 03 Dec 2002 11:01:33 -0800 To: pgsql-sql@postgresql.org From: eric soroos Subject: Query for filtering records Content-Type: text/plain; charset=us-ascii X-Virus-Scanned: by AMaViS new-20020517 X-Archive-Number: 200212/37 X-Sequence-Number: 10625 I'm having trouble subtracting groups from other groups. I've got a data model that has the following essential features: create table contacts (num int, properties....); create table groups (groupNum int, contactNum int); Where not all contacts will be in a group, some groups will contain most contacts, and there will be something like hundreds of groups and tens of thousands of contacts. I allow people to build groups using criteria, which I need to programatically translate to sql. One somewhat common pattern is: Select all contacts in group a, who have property b, and who aren't in groups c,d,e,f... My first shot was subqueries: select num, p1,p2 ... from contacts inner join groups using (contacts.num=groups.contactNum) where groups.groupNum=a and contact.p3=b and not num in (select contactNum from groups where groupNum=c) and not num in (select contactNum from groups where groupNum=d) and not num in (select contactNum from groups where groupNum=e) and not num in (select contactNum from groups where groupNum=f) This is .... slow. agonizingly so. With an inner join, I'm not convinced that the subtraction is actually correct., but it is much faster. Unfortunatley, faster incorrect answers are rarely helpful. Outer joins seem even worse than subselects for speed, but it does appear to give the correct answer. (example with a single join.) select num from contacts left outer join groups on (contacts.num=groups.contactNum and groups.groupNum=b) where dl_groupDonor._groupNum is null and p3=c I've got to be missing something here, because this is much slower from the (slow) procedural system that I'm porting from. I've been avoiding using union / intersect since I don't really ever know what columns are going to be in the query. perhaps I should revisit that decision and try to work around it. eric