使用案例 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"