我有一个STABLE函数get_value_by_id(id)
,它只从id
索引的表中获取值。
我在函数上运行EXPLAIN ANALYZE
,并在函数内部的同一SELECT
语句上运行。
SELECT * FROM table where id = $id.
SELECT
的总运行时间总是更好。这是为什么 ?
应该避免在这种情况下使用函数吗?
编辑:
添加解释分析的结果:
"Function Scan on get_value_by_id (cost=0.25..0.26 rows=1 width=1640) (actual time=0.187..0.189 rows=1 loops=1)" "Total runtime: 0.231 ms"
"Index Scan using id_index on table (cost=0.29..8.31 rows=1 width=255) (actual time=0.023..0.026 rows=1 loops=1)" " Index Cond: (id = 10000)" "Total runtime: 0.073 ms"
EDIT2 添加功能
CREATE OR REPLACE FUNCTION get_value_by_id(my_id integer)
RETURNS table1 AS
$BODY$
DECLARE
result table1;
BEGIN
SELECT val1, val2, val3 INTO result
FROM table1
WHERE id = my_id;
RETURN result;
END;
$BODY$
LANGUAGE plpgsql STABLE
COST 100;
ALTER FUNCTION get_value_by_id(integer)
OWNER TO my_user;
SQL函数的结果:
"Function Scan on get_value_by_id_sql (cost=0.25..0.26 rows=1 width=1640) (actual time=0.324..0.326 rows=1 loops=1)"
"Total runtime: 0.421 ms"