Sub topic 14
COST, ROWS and parallel safety
This chapter covers three function properties that tell the planner how a function behaves: COST, ROWS and PARALLEL. They never change what a function returns. They change the query plan, and a wrong PARALLEL label can change results or cause errors.
It assumes you can write a SQL function with CREATE FUNCTION, know the three volatility categories, and can read basic EXPLAIN output.
Why the planner needs hints
The planner can look inside a function only if it inlines the function. Otherwise the function is a black box, and the planner must guess three things about it:
- How expensive one call is.
- For a set-returning function, how many rows one call returns.
- Whether it is safe to run in a parallel worker process.
PostgreSQL has defaults for all three. They are often fine, but they are the same for every function, so a very cheap or very heavy function gets the wrong plan.
| Property | What it estimates | Default |
|---|---|---|
| `COST` | Cost of one call, in units of `cpu_operator_cost` | 100 for SQL and PL/pgSQL, 1 for C and internal functions |
| `ROWS` | Rows returned per call (set-returning functions only) | 1000 |
| `PARALLEL` | Where the function may run in a parallel query | `UNSAFE` |
COST
COST is a number of cpu_operator_cost units. That setting defaults to 0.0025, so the default function cost of 100 is about 0.25 in plan cost units. Only the ratio to other costs matters, so you do not need to calibrate it.
The planner uses COST mainly to order the conditions in a WHERE clause. Within one scan node it tests cheaper conditions first, so expensive calls run on fewer rows. It also affects the cost of a plan that evaluates the function in a scan or a join.
CREATE FUNCTION add_tax(price numeric, rate numeric DEFAULT 0.20)
RETURNS numeric
LANGUAGE sql
IMMUTABLE
COST 5
AS $$
SELECT price * (1 + rate);
$$;Here a cost of 5 says the function is cheap. Because this function is simple, the planner will probably inline it. After inlining, the body is part of the query and COST has no effect.
You can change the value later without redefining the function:
ALTER FUNCTION add_tax(numeric, numeric) COST 5;You can read the stored values from the catalog:
SELECT proname, procost, prorows, proparallel
FROM pg_proc
WHERE proname IN ('add_tax', 'recent_orders');In proparallel, s means safe, r means restricted and u means unsafe. prorows is 0 for functions that do not return a set.
ROWS
ROWS applies only to set-returning functions. The default estimate of 1000 rows is wrong for most functions. A function that returns the last five orders of one customer is estimated at 1000 rows, so the planner may pick a hash join or a sequential scan where a nested loop with an index would be much faster.
-- Assumes a table orders(id int, customer_id int, ordered_at timestamptz, total numeric)
CREATE FUNCTION recent_orders(p_customer_id int, p_limit int DEFAULT 10)
RETURNS TABLE (order_id int, ordered_at timestamptz, total numeric)
LANGUAGE sql
STABLE
ROWS 10
AS $$
SELECT o.id, o.ordered_at, o.total
FROM orders AS o
WHERE o.customer_id = p_customer_id
ORDER BY o.ordered_at DESC
LIMIT p_limit;
$$;
EXPLAIN SELECT * FROM recent_orders(42, 5);The Function Scan node in the plan now shows rows=10 instead of rows=1000. The estimate is a fixed number per function, not per call, so pick a typical value rather than an exact one. An estimate that is roughly right is enough to get a sensible join strategy.
ALTER FUNCTION recent_orders(int, int) ROWS 10;Some set-returning SQL functions are inlined as subqueries. In that case the planner estimates rows from the real query, and ROWS is ignored.
Parallel safety
A parallel query splits work across worker processes. The leader process starts workers, a Gather node collects their rows, and each worker runs part of the plan. Workers are restricted: they cannot do many things that a normal session can do.
Every function carries one of three labels:
PARALLEL UNSAFE: the function cannot run in a worker or in the leader during a parallel query. If a query contains such a call, the planner will not use any parallel plan for the whole query.PARALLEL RESTRICTED: the function may appear in a parallel query, but only the leader runs it. The part of the plan that calls it cannot be below theGathernode.PARALLEL SAFE: the function may run in workers.
The default is UNSAFE. A user-defined function therefore blocks parallelism until you label it.
Choosing a label
The rules from the PostgreSQL documentation are:
- Label a function
UNSAFEif it writes to the database, uses sequences (nextval), or makes persistent changes to settings. - Label a function
RESTRICTEDif it touches temporary tables, client connection state, cursors, prepared statements, or other backend-local state. - Otherwise, a function that only reads data and computes values can be
SAFE.
Of the functions in earlier chapters, add_tax and full_name are SAFE. recent_orders and get_balance only read tables, so they are SAFE. create_customer inserts a row and uses a sequence through serial, so it must stay UNSAFE.
ALTER FUNCTION recent_orders(int, int) PARALLEL SAFE;A worked example
The following script builds a table and a function that is expensive enough for parallelism to matter. The SET clause stops the planner from inlining the function. We want a real function call so the label has an effect.
CREATE TABLE readings AS
SELECT g AS id, random() * 100 AS value
FROM generate_series(1, 2000000) AS g;
ANALYZE readings;
CREATE FUNCTION slow_score(x double precision)
RETURNS double precision
LANGUAGE sql
IMMUTABLE
SET search_path = pg_catalog
AS $$
SELECT sqrt(abs(sin(x)) * 100 + ln(x + 1));
$$;
EXPLAIN SELECT sum(slow_score(value)) FROM readings;With the default PARALLEL UNSAFE, the plan is a plain Seq Scan with no Gather node. Now change the label and look again:
ALTER FUNCTION slow_score(double precision) PARALLEL SAFE;
EXPLAIN SELECT sum(slow_score(value)) FROM readings;The plan should now contain Gather and Partial Aggregate nodes above a Parallel Seq Scan. Whether the planner picks a parallel plan also depends on table size and on settings such as max_parallel_workers_per_gather, parallel_setup_cost, parallel_tuple_cost and min_parallel_table_scan_size. If you see no Gather, check those first.
Inlining and parallel labels
When the planner inlines a SQL function, the function call disappears and the body is analyzed as part of the query. The planner then looks at the operators and functions in the expanded expression, not at the label on the outer function. Labels matter for calls that stay as calls. Inlining does not happen if the function:
- has a
SETclause, - is
SECURITY DEFINER, - is not simple enough, for example a body with several statements.
So a label on a function that is always inlined does nothing, and a label on a function that is not inlined can decide whether the query is parallel.
Practical guidance
- Leave
COSTalone until a plan shows a problem. Raise it for functions that are heavy, such as ones that run subqueries over big tables, and lower it for trivial ones that are not inlined. - Set
ROWSon every set-returning function that is not inlined and that returns a number of rows far from 1000. - Label read-only, non-inlined functions
PARALLEL SAFEwhen queries over large tables call them. - Re-check labels when a function body changes. Adding a write, a
nextvalcall or a temp table lookup changes the correct label. - You can set all three in
CREATE FUNCTIONorCREATE OR REPLACE FUNCTION, or change them later withALTER FUNCTION.
Exercise
A function top_products(n int) returns the best-selling n products. It only reads tables and always returns about 20 rows. It is called in FROM and uses SECURITY DEFINER. Write the ALTER FUNCTION statement that gives the planner the right row estimate and lets it run in workers, and explain why the SECURITY DEFINER setting makes these labels matter.
Show answer
ALTER FUNCTION top_products(int) ROWS 20 PARALLEL SAFE; A SECURITY DEFINER function is never inlined, so the planner treats it as a black box. It must rely on the declared ROWS value instead of the default 1000, and on the PARALLEL label instead of looking inside the body, which would otherwise leave the default PARALLEL UNSAFE.
Exercise
A function writes a row to an audit table and returns the new id. A colleague marks it PARALLEL SAFE so that a big report query can go parallel. What is wrong, and what should the label be?
Show answer
The function modifies the database, so it must be PARALLEL UNSAFE. PostgreSQL does not verify labels, so the wrong label can cause errors in workers or wrong results. The report query should call a separate read-only function, or avoid the write inside the query.