以下查询之间的性能是否存在差异?
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')
我认为数据库足够聪明,可以内联"在规划最终查询之前的函数,以便它在执行中没有区别。但我不确定。
答案 0 :(得分:1)
答案 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页面来回答这个问题。
要内联的函数必须满足多个条件,因此最终会将其作为整个查询的一部分进行优化。
如果声明Immutable
或Stable
,则会内联相关函数:
create function foo() returns setof table1 as
$$
select * from table1
$$ language SQL stable;
Stable
更合适,因为该函数执行表查找。