X-Original-To: pgsql-performance-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id CF7F83A65B5 for ; Sun, 12 Dec 2004 08:32:38 +0000 (GMT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 88887-04 for ; Sun, 12 Dec 2004 08:32:27 +0000 (GMT) Received: from junk.nocrew.org (junk.nocrew.org [213.242.147.30]) by svr1.postgresql.org (Postfix) with ESMTP id AC29B3A65AB for ; Sun, 12 Dec 2004 08:32:28 +0000 (GMT) Received: from tomas by junk.nocrew.org with local (Exim 3.35 #1 (Debian)) for pgsql-performance@postgresql.org id 1CdP9V-0000sP-00; Sun, 12 Dec 2004 09:32:25 +0100 To: pgsql-performance@postgresql.org Subject: Re: [GENERAL] Query is not using index when it should References: <80oeh2tm7x.fsf@junk.nocrew.org> <20041210182453.G92467@megazone.bigpanda.com> <80d5xgudg6.fsf@junk.nocrew.org> <20041211143213.GA2659@uio.no> From: tomas@nocrew.org (Tomas =?iso-8859-1?q?Sk=E4re?=) Date: 12 Dec 2004 09:32:25 +0100 In-Reply-To: <20041211143213.GA2659@uio.no> Message-ID: <806537udba.fsf@junk.nocrew.org> Lines: 38 User-Agent: Gnus/5.0808 (Gnus v5.8.8) Emacs/20.7 MIME-Version: 1.0 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0.007 tagged_above=0 required=5 tests=AWL X-Spam-Level: X-Archive-Number: 200412/150 X-Sequence-Number: 9525 "Steinar H. Gunderson" writes: > On Sat, Dec 11, 2004 at 03:17:13PM +0100, Tomas Skäre wrote: > > select c.* from cjm_object c > > inner join > > (select max(timestamp) as timestamp,objectid,field from cjm_object > > group by objectid,field) t > > using(timestamp,objectid,field) > > where 1=1 and data is not null > > order by objectid,field; > > Usually, SELECT max(field) FROM table is better written in PostgreSQL as > SELECT field FROM table ORDER field DESC LIMIT 1. Well, my subquery doesn't return just one row, but one for each objectid,field combination in the table. I could rewrite it to something like this: select c.* from cjm_object c where exists (select timestamp from cjm_object t where c.objectid=t.objectid and c.field=t.field order by timestamp desc limit 1) and data is not null order by objectid; But that seems to be even slower, even if it can use an index scan in the subquery. Also it doesn't give the same result set, but I haven't looked into what's wrong yet. > I don't see the point of "where 1=1", though... It's just because the actual query is generated by a program, and it's easier to always have "where 1=1" and then add optional conditions with "and ...". Tomas