Skip site navigation (1) Skip section navigation (2)

Re: [GENERAL] Query is not using index when it should

From: tomas(at)nocrew(dot)org (Tomas =?iso-8859-1?q?Sk=E4re?=)
To: pgsql-performance(at)postgresql(dot)org
Subject: Re: [GENERAL] Query is not using index when it should
Date: 2004-12-12 08:32:25
Message-ID: 806537udba.fsf@junk.nocrew.org (view raw or flat)
Thread:
Lists: pgsql-generalpgsql-performancepgsql-sql
"Steinar H. Gunderson" <sgunderson(at)bigfoot(dot)com> 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

In response to

pgsql-performance by date

Next:From: Josh BerkusDate: 2004-12-13 02:48:27
Subject: Re: Query is not using index when it should
Previous:From: Tom LaneDate: 2004-12-11 18:06:23
Subject: Re: LIMIT causes SEQSCAN in subselect

pgsql-sql by date

Next:From: Michael FuhrDate: 2004-12-13 02:12:11
Subject: Re: Insert successful but data not found
Previous:From: Bruno Wolff IIIDate: 2004-12-11 19:01:05
Subject: Re: filtering

pgsql-general by date

Next:From: ra ghuDate: 2004-12-12 13:02:19
Subject: problem in connecting to postgreserver
Previous:From: Elnaz ShafipourDate: 2004-12-12 06:56:24
Subject: Re: relation "sql_features" does not exist

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group