Search code examples
postgresqlstored-proceduresviewprecompile

Stored procedure or view


I was comparing between running my complex select query in a view or a stored procedure.

I heard that when I put my query into stored procedure it will be pre-compiled, which it will reduce the timing of running because it will save the execution plan.

I didn't try both of them, but I am wondering which approach is better.

What is the best practice?


Solution

  • Static SQL statements in a PL/pgSQL function (you must be talking about a function, not a procedure, if you want to return data) can cache the execution plan for the duration of a database session. That can save you the effort of calculating an execution plan whenever the query is executed.

    However, if the query is expensive, the planning time will only be a tiny fraction of the query execution time, and the gain will be negligible. So it doesn't matter how you do it, and my advice is to choose what is most convenient from your application or database maintenance perspective.

    To see for yourself, run the query with EXPLAIN (ANALYZE). Then you get the query planning time and the execution time reported and can assess if reducing the former will have an impact on your overall performance.