用例 3 — SELECT 语句中的函数调用 - AWS 规范性指导

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

用例 3 — SELECT 语句中的函数调用

在子where句中调用函数会降低查询性能,而VOLATILE在调用该函数时不使用select关键字:

Select * from tab_name where FieldName = FunctionName(parameters);

如果在调用函数时使用该select语句,则会运行索引扫描:

Select * from tab_name where FieldName = ( select FunctionName(parameters) );

pnr_number字段在rnr_expiry_date表中有一个索引。比较where子句中的值时使用索引。

explain analyze select * from perf_user.rnr_expiry_date where pnr_number= 'EE9F41'; "Index Scan using rnr_expiry_date_idx3 on rnr_expiry_date (cost=0.29..8.31 rows=1 width=72) (actual time=0.020..0.021 rows=1 loops=1)" " Index Cond: ((pnr_number)::text = 'EE9F41'::text)" "Planning Time: 0.063 ms" "Execution Time: 0.038 ms"

当调用不带select关键字的函数时,即使该字段上有可用的索引,也会执行顺序扫描。

explain analyze select * from perf_user.rnr_expiry_date where pnr_number= perf_user.return_data(); "Seq Scan on rnr_expiry_date (cost=0.00..27084.00 rows=1 width=72) (actual time=0.112..135.917 rows=1 loops=1)" " Filter: ((pnr_number)::text = (perf_user.return_data())::text)" " Rows Removed by Filter: 99999" "Planning Time: 0.053 ms" "Execution Time: 136.803 ms"

使用select关键字调用函数时会执行索引扫描。

explain analyze select * from perf_user.rnr_expiry_date where pnr_number= (select perf_user.return_data() ); "Index Scan using rnr_expiry_date_idx3 on rnr_expiry_date (cost=0.55..8.57 rows=1 width=72) (actual time=0.058..0.061 rows=1 loops=1)" " Index Cond: ((pnr_number)::text = ($0)::text)" " InitPlan 1 (returns $0)" " -> Result (cost=0.00..0.26 rows=1 width=32) (actual time=0.021..0.022 rows=1 loops=1)" "Planning Time: 0.147 ms" "Execution Time: 0.111 ms"