官术网_书友最值得收藏!

Costs

It is possible to provide hints to the executor about the cost of a function. PostgreSQL query optimizer is a cost-based optimizer, which means it will carefully evaluate the cost of each operation and choose the execution path with the lowest cost. Explaining the cost system and the optimizer is out of the scope of this book, but it is important to know that functions can have a cost estimation.

There are two properties that provide this cost estimation:

  • COST is a positive number indicating how many CPU operations the function will use
  • ROWS is an estimation of the rows returned from a RETURNS SETOF (or RETURNS TABLE) function

The COST property is the more straightforward one: it expresses how many CPU operations the whole execution of the function will use. CPU operations have a cost of cpu_operator_cost each, which is, by default, 1/40 the cost of performing a sequential read from disk. If not specified, the COST for a PL/pgSQL or any non-C language is set to 100.

If the function returns a result set, COST is intended to be the cost of a single tuple from the function result set. Moreover, it is possible to provide the optimizer with a hint about how many tuples a function will return by specifying a positive ROWS number.

As a simple example, a function that performs a simple limited tag query can be declared to have a ROWS property set to the limit itself:

testdb=> CREATE FUNCTION get_ten_tags()
RETURNS SETOF tag AS $code$
BEGIN
RETURN QUERY SELECT *
FROM tags
LIMIT 10;
END $code$ LANGUAGE plpgsql
ROWS 10; -- it is clear this function cannot return more rows

Tuning cost properties can quickly become a complicated task, so it is recommended to add these properties only when they are really needed and to check the impact on query execution carefully.

主站蜘蛛池模板: 大邑县| 柳林县| 安阳市| 都兰县| 和林格尔县| 合川市| 临澧县| 通辽市| 宝坻区| 宁强县| 霍州市| 屯门区| 阳江市| 平陆县| 彭泽县| 镇沅| 治多县| 获嘉县| 锡林浩特市| 区。| 磴口县| 滨海县| 图们市| 鞍山市| 苍山县| 巴青县| 聂荣县| 扎兰屯市| 闽清县| 凤山县| 南投县| 德令哈市| 南昌市| 白玉县| 河南省| 泾阳县| 镇雄县| 九江县| 墨脱县| 平罗县| 临洮县|