0

In PostgreSQL, what is the best way to call the same function multiple times in the same query?

Example:

SELECT a.id, 
       sum_one(a.id) AS "Sum_one",
       sum_two(a.id) AS "Sum_two",
       (sum_one(a.id )+sum_two(a.id)) AS "Sum_three"
  FROM a

Where sum_one() and sum_two() are functions. I repeat the call of sum_one() and sum_two(). This will slow down queries in large databases.

I want to avoid the following statement.

(sum_one(a.id )+sum_two(a.id)) AS "Sum_three"

How can I do it that in PostgreSQL?

2 Answers 2

3

You should set your function volatility to Stable.

More about function volatility.

CREATE OR REPLACE FUNCTION myFunc(prm_MyParam integer)
  RETURNS numeric AS
$BODY$
BEGIN
  {...}

END;$BODY$
  LANGUAGE plpgsql STABLE;
Sign up to request clarification or add additional context in comments.

Comments

1

Use a subquery:

SELECT
    "Sum_one",
    "Sum_two",
    ("Sum_one" + "Sum_two") AS "Sum_three"
FROM (
    SELECT sum_one("A"."id") AS "Sum_one", sum_two("A"."id") AS "Sum_two" FROM A
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.