Re: how to remove a for-loop from programming language and put it into the query?

From: Sam Mason <sam(at)samason(dot)me(dot)uk>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: how to remove a for-loop from programming language and put it into the query?
Date: 2010-07-05 15:56:22
Message-ID: 20100705155622.GP7584@samason.me.uk
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Mon, Jul 05, 2010 at 12:44:55PM -0300, Pedro Zorzenon Neto wrote:
> Em 05-07-2010 12:22, Sam Mason escreveu:
> > SELECT DISTINCT ON (hardware_id) hardware_id, diag_value, ts
> > FROM diagnose_logs
> > WHERE ts <= '2009-12-25 23:59:59'
> > ORDER BY hardware_id, ts DESC;
>
> It worked ok! your solution solves what I need. The process time went
> from 60 to 20 seconds. nice!

Always nice when less code is faster!

> Can you help me to discover why the "Seq Scan" in explain analyse? I
> tried to create some indexes to change seq scan to index scan, but
> couldn't do it.

It's because the only way PG knows how to do a DISTINCT ON is to sort
the whole table and then pull out the appropriate values. Sorting the
whole of a table is generally going to be faster than referring to an
index for every row and hence PG won't use an index.

I'm not sure if that's changed more recently, but for 7.4 I'm pretty
sure that's the case anyway.

--
Sam http://samason.me.uk/

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Edmundo Robles L. 2010-07-05 19:26:35 OFFTOPIC -- pgpool list is down?????
Previous Message Zeeshan.Ghalib 2010-07-05 15:47:48 Re: Out of memory on update of a single column table containg just one row.