Postgresql:过滤函数输出与将过滤参数传递给函数
Postgresql: Filter function output vs passing filter parameter to the function
以下查询在性能上是否存在差异?
1. foo() returns 一个未过滤的集合,然后被过滤:
create function foo() returns setof table1 as
$$
select * from table1
$$ language SQL;
select * from foo() where name = 'bar'
2。 foo() 接受一个参数和 returns 一个过滤集:
create function foo(varchar) returns setof table1 as
$$
select * from table1 where name =
$$ language SQL;
select * from foo('bar')
我假设数据库足够聪明,可以在计划最终查询之前 "inline" 该函数,因此它在执行时没有任何区别。但我不确定。
- 第一个 运行s 函数没有任何参数(可能获取更多数据),然后在字段上过滤数据。所以可能会花费更多。
- 带参数的第二个 运行s 函数(可能减少函数 运行 的数据)
- 没有函数体,纯属推测
将数百万(例如 5)行放入 table,尝试为列 name
(包括 'bar'
)使用至少 10-20 个不同的值。然后添加索引create index iixx on table1(name)
然后运行select count(*) from foo() where name = 'bar'
然后尝试第二个版本 select count(*) from foo1('bar')
你会看到不同
我找到了一个 wiki 页面来回答这个问题。
要内联函数并因此作为整个查询的一部分进行优化,必须满足多个条件。
如果函数声明为 Immutable
或 Stable
:
,则相关函数将被内联
create function foo() returns setof table1 as
$$
select * from table1
$$ language SQL stable;
Stable
更合适,因为该函数执行 table 查找。
以下查询在性能上是否存在差异?
1. foo() returns 一个未过滤的集合,然后被过滤:
create function foo() returns setof table1 as
$$
select * from table1
$$ language SQL;
select * from foo() where name = 'bar'
2。 foo() 接受一个参数和 returns 一个过滤集:
create function foo(varchar) returns setof table1 as
$$
select * from table1 where name =
$$ language SQL;
select * from foo('bar')
我假设数据库足够聪明,可以在计划最终查询之前 "inline" 该函数,因此它在执行时没有任何区别。但我不确定。
- 第一个 运行s 函数没有任何参数(可能获取更多数据),然后在字段上过滤数据。所以可能会花费更多。
- 带参数的第二个 运行s 函数(可能减少函数 运行 的数据)
- 没有函数体,纯属推测
将数百万(例如 5)行放入 table,尝试为列 name
(包括 'bar'
)使用至少 10-20 个不同的值。然后添加索引create index iixx on table1(name)
然后运行select count(*) from foo() where name = 'bar'
然后尝试第二个版本 select count(*) from foo1('bar')
你会看到不同
我找到了一个 wiki 页面来回答这个问题。
要内联函数并因此作为整个查询的一部分进行优化,必须满足多个条件。
如果函数声明为 Immutable
或 Stable
:
create function foo() returns setof table1 as
$$
select * from table1
$$ language SQL stable;
Stable
更合适,因为该函数执行 table 查找。