Received: from maia.hub.org (unknown [200.46.204.183]) by mail.postgresql.org (Postfix) with ESMTP id D1ADB632588 for ; Wed, 21 Apr 2010 17:16:30 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.183]) (amavisd-maia, port 10024) with ESMTP id 90759-06 for ; Wed, 21 Apr 2010 20:16:20 +0000 (UTC) X-Greylist: domain auto-whitelisted by SQLgrey-1.7.6 Received: from mail-qy0-f196.google.com (mail-qy0-f196.google.com [209.85.221.196]) by mail.postgresql.org (Postfix) with ESMTP id 1CF1D63342A for ; Wed, 21 Apr 2010 17:16:20 -0300 (ADT) Received: by qyk34 with SMTP id 34so2264159qyk.10 for ; Wed, 21 Apr 2010 13:16:19 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=gamma; h=domainkey-signature:mime-version:sender:received:date :x-google-sender-auth:received:message-id:subject:from:to :content-type; bh=MirSZHoPorATaad8zHvS/joBwwiahO9yg1N75wRbpQo=; b=ZRe7bIDykN8j/JYSF4CmcLl0sd5LcWYyiK0nQ78RuAUL81hiS8mCFPy3ay0+4cj5kg FS2N/P4lvh4X9bV9J6JfbWEOfbEBMlVOxRJRpYicFQhc7i2UXfdDiwsCljtNqBd7ubHb aXWR5AEpaMoupT6YxmO9zmUpsGi0rdVBj87q8= DomainKey-Signature: a=rsa-sha1; c=nofws; d=gmail.com; s=gamma; h=mime-version:sender:date:x-google-sender-auth:message-id:subject :from:to:content-type; b=LgrvLvW/rzEi2yEJyhopOOADD+ViP5Ez2K6iZijTeeQ/qwRMzQiwq7GEAPiw1mkUjX VuZBhdVqhug22FhzcDpqXJDYb3ZzeCgIBWAFUfXvuK81QmQgBSDfrHVhOF52Sgz+BcCa CDK+8NOOL0JpJXxNc1qdCx3HJS8I6PjePGmsE= MIME-Version: 1.0 Received: by 10.229.37.65 with HTTP; Wed, 21 Apr 2010 13:16:18 -0700 (PDT) Date: Wed, 21 Apr 2010 16:16:18 -0400 X-Google-Sender-Auth: 06811d64557cf30b Received: by 10.229.193.18 with SMTP id ds18mr2810259qcb.14.1271880978881; Wed, 21 Apr 2010 13:16:18 -0700 (PDT) Message-ID: Subject: Replacing Cursors with Temporary Tables From: Eliot Gable To: pgsql-performance@postgresql.org Content-Type: multipart/alternative; boundary=0016362845f4f15cf80484c4dd6d X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=0.812 tagged_above=-10 required=5 tests=BAYES_50=0.8, FREEMAIL_FROM=0.001, HTML_MESSAGE=0.001, T_TO_NO_BRKTS_FREEMAIL=0.01 X-Spam-Level: X-Archive-Number: 201004/279 X-Sequence-Number: 38529 --0016362845f4f15cf80484c4dd6d Content-Type: text/plain; charset=ISO-8859-1 I have previously discussed my very long PL/PGSQL stored procedure on this list. However, without getting into too many details, I have another performance-related question. The procedure currently uses cursors to return multiple result sets to the program executing the procedure. Basically, I do this: BEGIN; SELECT * FROM stored_proc(); FETCH ALL FROM cursor1; FETCH ALL FROM cursor2; FETCH ALL FROM cursor3; etc. COMMIT; However, there are some cases in the stored procedure where some of the result sets returned by these cursors are also needed as inputs to additional queries. To use them, I am currently doing: FOR temp IN cursorX LOOP -- Some code that pushes the current temp record onto the end of an array END LOOP; OPEN cursorX; MOVE FIRST FROM cursorX; Then, when I need to use the results in a query, I do something like: SELECT * FROM table1 INNER JOIN (SELECT * FROM unnest(result_array)) AS table2 ON ( blah blah ) WHERE blah This seems extremely inefficient to me. First, I'm not sure of the penalty for unnesting an array into a SET OF object. Second, the set of records returned from unnesting would not be indexed for the join which means a sequential scan. Third, building the array in the first place using array_append seems extremely inefficient. Fourth, opening the cursor twice seems like it would execute the query twice, though given the placement and context, it's probably got it cached somewhere (hopefully). I'm sure there are probably other things I am overlooking. Instead of doing things this way, I think using temporary tables is really what I want. I am thinking that instead of doing this cursor BS, I can do something like: CREATE TEMPORARY TABLE table2 WITH (OIDS=FALSE) ON COMMIT DROP AS ( SELECT * FROM blah blah blah -- whatever the cursor is defined as doing ); ALTER TABLE table2 ADD PRIMARY KEY (id); CREATE INDEX table2_blah_idx ON table2 USING btree (blah); ANALYZE table2; Then, when I need to use the results in another query, I could do: SELECT * FROM table1 INNER JOIN table2 ON ( blah blah ) WHERE blah This would use the indexes and the primary key appropriately. I could also ensure that the order of the information in the temporary table is such that it facilitates any joining, where clauses, or order by clauses on the additional queries. Finally, to get results into my application, I would then do: BEGIN; SELECT * FROM stored_procedure(); SELECT * FROM temp_table1; SELECT * FROM temp_table2; SELECT * FROM temp_table3; etc COMMIT; However, this is a fairly major re-write of how things are done. Before I spend the time to do all that re-writing, can anyone share some insight on where / how I might expect to gain performance from this conversion and also speak to some of the overhead (if any) in using temporary tables like this (building them, creating indexes on them, analyzing them, then dropping them on commit)? It is worth mentioning that the data being stored in these temporary tables is probably <1,000 records for all tables involved. Most will probably be <100 records. Some of these temporary tables will be joined to other tables up to 4 more times throughout the rest of the stored procedure. Most will be generated and then retrieved only from outside the stored procedure. Obviously, I would not create indexes on or analyze the temporary tables being retrieved only from outside the stored procedure. Indexes and primary keys will only be created on the tables that are joined to other tables and have WHERE conditions applied to them. I have done a lot of Googling on temporary tables and cursors in PostgreSQL, but I have found only very limited discussion as to performance differences with respect to how I'm planning on using them, and I am unsure about the quality of the information given that most of it is 4+ years out of date and posted on various expert exchanges and not on this pgsql-performance list. One final question: In this conversion to temporary table use, there are a couple of cases where I would prefer to do something like: prepare blah(blah blah) as select blah; Then, I want to call this prepared statement multiple times, passing a different argument value each time. The only reason to do this would be to save writing code and to ensure that updating the select statement in once place covers all places where it is used. However, I am concerned it might incur a performance hit by re-preparing the query since I assume that having this inside the PL/PGSQL procedure means it is already prepared once. Can anyone speak to this? I know that I could put it in a separate stored procedure, but then the question becomes, does that add extra overhead? Or, in different words, is it similar to the difference between an inlined function and a non-inlined function in C? I would greatly appreciate any insights to these questions/issues. Thanks in advance for any assistance anyone can provide. -- Eliot Gable "We do not inherit the Earth from our ancestors: we borrow it from our children." ~David Brower "I decided the words were too conservative for me. We're not borrowing from our children, we're stealing from them--and it's not even considered to be a crime." ~David Brower "Esse oportet ut vivas, non vivere ut edas." (Thou shouldst eat to live; not live to eat.) ~Marcus Tullius Cicero --0016362845f4f15cf80484c4dd6d Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable I have previously discussed my very long PL/PGSQL stored procedure on this = list. However, without getting into too many details, I have another perfor= mance-related question.

The procedure currently uses cursors to retu= rn multiple result sets to the program executing the procedure. Basically, = I do this:

BEGIN;
SELECT * FROM stored_proc();
FETCH ALL FROM cursor1;
FE= TCH ALL FROM cursor2;
FETCH ALL FROM cursor3;
etc.
COMMIT;

= However, there are some cases in the stored procedure where some of the res= ult sets returned by these cursors are also needed as inputs to additional = queries. To use them, I am currently doing:

FOR temp IN cursorX LOOP
=A0 -- Some code that pushes the current te= mp record onto the end of an array
END LOOP;
OPEN cursorX;
MOVE FI= RST FROM cursorX;

Then, when I need to use the results in a query, I= do something like:

SELECT * FROM table1 INNER JOIN (SELECT * FROM unnest(result_array)) AS= table2 ON ( blah blah ) WHERE blah

This seems extremely inefficient= to me. First, I'm not sure of the penalty for unnesting an array into = a SET OF object. Second, the set of records returned from unnesting would n= ot be indexed for the join which means a sequential scan. Third, building t= he array in the first place using array_append seems extremely inefficient.= Fourth, opening the cursor twice seems like it would execute the query twi= ce, though given the placement and context, it's probably got it cached= somewhere (hopefully). I'm sure there are probably other things I am o= verlooking.

Instead of doing things this way, I think using temporary tables is rea= lly what I want. I am thinking that instead of doing this cursor BS, I can = do something like:

CREATE TEMPORARY TABLE table2 WITH (OIDS=3DFALSE)= ON COMMIT DROP AS (
=A0 SELECT * FROM blah blah blah -- whatever the cursor is defined as doing=
);
ALTER TABLE table2 ADD PRIMARY KEY (id);
CREATE INDEX table2_b= lah_idx ON table2 USING btree (blah);
ANALYZE table2;

Then, when = I need to use the results in another query, I could do:

SELECT * FROM table1 INNER JOIN table2 ON ( blah blah ) WHERE blah
<= br>This would use the indexes and the primary key appropriately. I could al= so ensure that the order of the information in the temporary table is such = that it facilitates any joining, where clauses, or order by clauses on the = additional queries. Finally, to get results into my application, I would th= en do:

BEGIN;
SELECT * FROM stored_procedure();
SELECT * FROM temp_table= 1;
SELECT * FROM temp_table2;
SELECT * FROM temp_table3;
etc
CO= MMIT;

However, this is a fairly major re-write of how things are don= e. Before I spend the time to do all that re-writing, can anyone share some= insight on where / how I might expect to gain performance from this conver= sion and also speak to some of the overhead (if any) in using temporary tab= les like this (building them, creating indexes on them, analyzing them, the= n dropping them on commit)? It is worth mentioning that the data being stor= ed in these temporary tables is probably <1,000 records for all tables i= nvolved. Most will probably be <100 records. Some of these temporary tab= les will be joined to other tables up to 4 more times throughout the rest o= f the stored procedure. Most will be generated and then retrieved only from= outside the stored procedure. Obviously, I would not create indexes on or = analyze the temporary tables being retrieved only from outside the stored p= rocedure. Indexes and primary keys will only be created on the tables that = are joined to other tables and have WHERE conditions applied to them.

I have done a lot of Googling on temporary tables and cursors in Postgr= eSQL, but I have found only very limited discussion as to performance diffe= rences with respect to how I'm planning on using them, and I am unsure = about the quality of the information given that most of it is 4+ years out = of date and posted on various expert exchanges and not on this pgsql-perfor= mance list.

One final question:

In this conversion to temporary table use, t= here are a couple of cases where I would prefer to do something like:
prepare blah(blah blah) as select blah;

Then, I want to call this = prepared statement multiple times, passing a different argument value each = time. The only reason to do this would be to save writing code and to ensur= e that updating the select statement in once place covers all places where = it is used. However, I am concerned it might incur a performance hit by re-= preparing the query since I assume that having this inside the PL/PGSQL pro= cedure means it is already prepared once. Can anyone speak to this? I know = that I could put it in a separate stored procedure, but then the question b= ecomes, does that add extra overhead? Or, in different words, is it similar= to the difference between an inlined function and a non-inlined function i= n C?

I would greatly appreciate any insights to these questions/issues.
<= br>Thanks in advance for any assistance anyone can provide.


-- <= br>Eliot Gable

"We do not inherit the Earth from our ancestors:= we borrow it from our children." ~David Brower

"I decided the words were too conservative for me. We're not b= orrowing from our children, we're stealing from them--and it's not = even considered to be a crime." ~David Brower

"Esse oporte= t ut vivas, non vivere ut edas." (Thou shouldst eat to live; not live = to eat.) ~Marcus Tullius Cicero
--0016362845f4f15cf80484c4dd6d--