1

I want to reuse an expensive function call in PostgreSQL:

SELECT name,
  expensive_function(bar) as bars,
  array_length(bars) as total
FROM foos
GROUP BY name

but of course bars isn't a column so the following error is raised:

ERROR:  column "bars" does not exist

Is there a syntax or trick that will make this work?

3
  • Can you give some scope to reuse. Commented Mar 6, 2014 at 20:11
  • postgresql.org/about/news/1296 Commented Mar 6, 2014 at 20:12
  • @JustKim Reuse meaning run the function once per row and use the resultant value for multiple return columns on that row. Commented Mar 6, 2014 at 20:19

1 Answer 1

2

A common table expression (CTE) would work:

WITH subqry AS
  ( SELECT expensive_function(bar) AS bars
    FROM   foos )
SELECT bars,
       array_length(bars)
FROM   subqry;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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