Search code examples
sqlpostgresqlquery-performancestored-functions

postgresql with function wrap sql so slow?


first sql explain analyse:

explain  analyse  select * from ttq.ttq_post;
Seq Scan on ttq_post  (cost=10000000000.00..10000000014.71 rows=171 width=547) (actual time=0.005..0.027 rows=176 loops=1)
Planning Time: 0.033 ms
Execution Time: 0.041 ms

but if use function wrap the same sql
eg:

create or replace function ttq.test_fn_slow() 
  returns  setof ttq.ttq_post 
  language  sql 
  stable 
as $$
select * from ttq.ttq_post;
$$

and exec blow function:

explain  analyse  select ttq.test_fn_slow();

result:

ProjectSet  (cost=0.00..5.27 rows=1000 width=32) (actual time=0.063..0.175 rows=176 loops=1)
  ->  Result  (cost=0.00..0.01 rows=1 width=0) (actual time=0.001..0.001 rows=1 loops=1)
Planning Time: 0.013 ms
Execution Time: 0.192 ms

why use function wrap so slow?

try use "immutable" replace "stable" but the result is same!


Solution

  • The additional cost must be due to the fact that you are using the set returning function in the SELECT clause rather than in the FROM clause.

    Note that the processing of set returning functions in the SELECT clause changed in PostgreSQL v10, so your version may have an influence on this behavior.