Many times, I'm able to write a PL/PGSQL UDF in two ways:

  1. As a big query usually using WITH clauses and UNION (i.e. more declarative but also more complex to write/read)
  2. As multiple smaller queries (i.e. more procedural but also easier to write/read)

I'm aware that PG query planner will plan each smaller query in UDF individually, and I'm afraid that might have an impact on overall performance. What do you guys prefer?

Thank you.

1 Answer 1


If you're able to write it as a single query Q, the best alternative is to avoid writing the UDF in the first place, and embed Q as a subquery in the calling query. That's probably the best if performance is your main concern.

If code reuse, modularity, readability are more important than performance, IMO you can choose option 2.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.