Postgresql:过滤函数输出与传递过滤器参数到函数

时间:2017-05-10 07:54:13

标签: sql postgresql plpgsql

以下查询之间的性能是否存在差异?

1。 foo()返回一个未经过滤的集合,然后进行过滤:

create function foo() returns setof table1 as 
$$
   select * from table1
$$ language SQL;

select * from foo() where name = 'bar'

2。 foo()接受一个参数并返回一个过滤集:

create function foo(varchar) returns setof table1 as 
$$
   select * from table1 where name = $1
$$ language SQL;

select * from foo('bar')

我认为数据库足够聪明,可以内联"在规划最终查询之前的函数,以便它在执行中没有区别。但我不确定。

3 个答案:

答案 0 :(得分:1)

  1. 第一次运行没有任何参数的函数(可能获得更多数据),然后在字段上过滤数据。所以可能会花费更多。
  2. 第二个运行带参数的函数(可能减少函数运行中的数据)
  3. 没有功能的身体,这是纯粹的猜测

答案 1 :(得分:0)

将数百万(例如5)行放入表中,尝试为列name使用至少10-20个不同的值(包括'bar')。然后添加索引create index iixx on table1(name)

然后运行select count(*) from foo() where name = 'bar'

然后尝试第二个版本select count(*) from foo1('bar')

你会看到差异

答案 2 :(得分:0)

我找到了一个wiki页面来回答这个问题。

要内联的函数必须满足多个条件,因此最终会将其作为整个查询的一部分进行优化。

如果声明ImmutableStable,则会内联相关函数:

create function foo() returns setof table1 as 
$$
   select * from table1
$$ language SQL stable;

Stable更合适,因为该函数执行表查找。