STABLE functions

From: Joachim Wieland <jwieland(at)kawo2(dot)rwth-aachen(dot)de>
To: pgsql-bugs(at)postgresql(dot)org
Subject: STABLE functions
Date: 2003-03-24 22:17:11
Message-ID: 20030324221711.GA6011@mcknight.de
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

Hi there,

I'm using 7.3.2 and encounter the problem that a SELECT query that uses
a function with a constant argument is quite slow. The function is
declared STABLE. Here's an example:

SELECT ... FROM table WHERE col = f('xyz');

From what I read in the docs

( http://www.postgresql.org/docs/view.php?version=7.3&idoc=0&file=sql-createfunction.html )

I thought that this function is only executed once when declared as
STABLE, however the time of the query seems to indicate that it is
executed for each row of "table".

Below is a small script that generates some SQL commands that should show
the problem. It creates a table, inserts some rows and defines a
function that should just take some time when executed.

In my opinion

SELECT s FROM test WHERE s = f_test('abc');

should (roughly) be as fast as

SELECT f_test('abc');

but it isn't.

-----8<------------------

#!/bin/sh

echo "CREATE TABLE test (s varchar(300));"

for i in `seq 0 1000`; do
echo "INSERT INTO test VALUES ('$i');"
done

cat << EOF
CREATE OR REPLACE FUNCTION f_test(VARCHAR(200)) RETURNS int AS '
DECLARE
r RECORD;
v VARCHAR(200);
a ALIAS FOR \$1;
BEGIN
IF a IS NULL THEN
RETURN NULL;
END IF;
FOR r IN SELECT * FROM test LOOP
v = r.s;
END LOOP;
RETURN 1;
END;
' LANGUAGE plpgsql STABLE STRICT;

EOF

-----8<------------------

Thanks,
Joachim

--
*****PGP key available - send e-mail request****
If you fail to plan, plan to fail.

Browse pgsql-bugs by date

  From Date Subject
Next Message William.Jiang 2003-03-25 01:10:28 POSTMASTER crashed when I execute a function
Previous Message Diego Cattelan 2003-03-24 20:20:58 R: Bug #917: SERVICE DENIAL ON XP