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

From: tomas@nocrew.org (Tomas Skäre)
Subject: Re: [GENERAL] Query is not using index when it should
Date: ,
Msg-id: 806537udba.fsf@junk.nocrew.org
(view: Whole thread, Raw)
In response to: Re: [GENERAL] Query is not using index when it should  ("Steinar H. Gunderson")
List: pgsql-performance

Tree view

Re: [GENERAL] Query is not using index when it should  (Stephan Szabo, )
 Re: [GENERAL] Query is not using index when it should  ( (Tomas Skäre), )
  Re: [GENERAL] Query is not using index when it should  ("Steinar H. Gunderson", )
   Re: [GENERAL] Query is not using index when it should  (Michael Fuhr, )
   Re: [GENERAL] Query is not using index when it should  ( (Tomas Skäre), )

"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


pgsql-performance by date:

From: tomas@nocrew.org (Tomas Skäre)
Date:
Subject: Re: [GENERAL] Query is not using index when it should
From: "Rosny"
Date:
Subject: Re: TableSpace Design issues on Postgres 8.0 beta 5