Re: CURSOR slowes down a WHERE clause 100 times?

From: Richard Huxton <dev(at)archonet(dot)com>
To: Niccolo Rigacci <niccolo(at)rigacci(dot)org>
Cc: pgsql-performance(at)postgresql(dot)org
Subject: Re: CURSOR slowes down a WHERE clause 100 times?
Date: 2005-07-07 09:14:50
Message-ID: 42CCF28A.3010403@archonet.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-performance

Niccolo Rigacci wrote:
>>
>>I get the results in about 108 seconds (8060 rows).
>>
>>If I issue the SELECT alone (without the CURSOR) I get the
>>same results in less than 1 second.
>
>
> By trial and error I discovered that adding an "ORDER BY
> toponimo" clause to the SELECT, boosts the CURSOR performances
> so that they are now equiparable to the SELECT alone.
>
> Is there some documentation on how an ORDER can affect the
> CURSOR in a different way than the SELECT?

I think you're misunderstanding exactly what's happening here. If you
ask for a cursor, PG assumes you aren't going to want all the results
(or at least not straight away). After all, most people use them to work
through results in comparatively small chunks, perhaps only ever
fetching 1% of the total results.

So - if you ask for a cursor, PG weights things to give you the first
few rows as soon as possible, at the expense of fetching *all* rows
quickly. If you're only going to fetch e.g. the first 20 rows this is
exactly what you want. In your case, since you're immediately issuing
FETCH ALL, you're not really using the cursor at all, but PG doesn't
know that.

So - the ORDER BY means PG has to sort all the results before returning
the first row anyway. That probably means the plans with/without cursor
are identical.

Of course, all this assumes that your configuration settings are good
and statistics adequate. To test that, try fetching just the first row
from your cursor with/without the ORDER BY. Without should be quicker.

--
Richard Huxton
Archonet Ltd

In response to

Responses

Browse pgsql-performance by date

  From Date Subject
Next Message Niccolo Rigacci 2005-07-07 10:06:58 Re: CURSOR slowes down a WHERE clause 100 times?
Previous Message Niccolo Rigacci 2005-07-07 08:13:27 Re: CURSOR slowes down a WHERE clause 100 times?