Sub topic 12
How the planner inlines SQL functions
This chapter assumes you can write a basic SQL function with CREATE FUNCTION, you know the three volatility categories, and you can read EXPLAIN output. You should also have a table with an index to experiment on.
What inlining is
Normally a function is a black box to the planner. The planner sees a call, guesses a cost and a result size, and leaves it alone. At run time the executor starts the function, runs its body as a separate query, and returns the result.
A SQL function can be an exception. In some cases the planner replaces the call with the body of the function, after substituting the actual arguments for the parameters. This is called inlining. The replacement happens during planning, so the outer query is optimized as if you had written the body yourself.
Inlining matters for three reasons:
- An index on a column can be used when the function body is a condition on that column.
- Constants are folded at plan time. An
IMMUTABLEfunction called with constant arguments can be evaluated once, before the query runs. - Row estimates come from the real expressions and the table statistics. They do not come from a default guess for an opaque call.
A function that is not inlined still works, but it can be much slower inside a WHERE clause or a join.
Scalar functions
For a function that returns a single value, the planner tries inlining each time it simplifies an expression that contains a call. It gives up if any of these conditions fails:
- The language is
sql. - The body is a single
SELECTthat returns one expression. It has noFROM,WHERE, aggregates, window functions, sub-selects or set-returning calls. - The function is not
SECURITY DEFINER. - The function has no
SETclause, which includesSET search_path. - If the function is
STRICT, the expression itself must be strict. Otherwise inlining could change the result for NULL arguments. - The declared volatility must be honest. An
IMMUTABLEfunction whose body calls something mutable is not inlined. ASTABLEfunction whose body calls a volatile function is not inlined either. - Arguments must be safe to substitute. If a parameter appears in the body more than once, its argument must be neither volatile nor expensive. A volatile argument also blocks inlining when the parameter is never used.
Here is an example. The table is built so that only about 0.5% of rows match.
CREATE TABLE orders (
id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id int,
ordered_at timestamptz,
total numeric
);
INSERT INTO orders (customer_id, ordered_at, total)
SELECT (g % 500) + 1,
now() - (g || ' minutes')::interval,
g % 2000
FROM generate_series(1, 100000) AS g;
CREATE INDEX orders_total_idx ON orders (total);
ANALYZE orders;
CREATE FUNCTION is_big_order(p_total numeric)
RETURNS boolean
LANGUAGE sql
IMMUTABLE
AS $$
SELECT p_total >= 1990;
$$;
EXPLAIN (VERBOSE, COSTS OFF)
SELECT id FROM orders WHERE is_big_order(total);The plan should use orders_total_idx with an index condition like total >= 1990. The function name does not appear anywhere in the plan. The planner replaced the call with the comparison, and it matched the comparison to the index.
Now create a copy of the function that the planner is not allowed to inline:
CREATE FUNCTION is_big_order_sd(p_total numeric)
RETURNS boolean
LANGUAGE sql
IMMUTABLE
SECURITY DEFINER
SET search_path = pg_catalog
AS $$
SELECT p_total >= 1990;
$$;
EXPLAIN (VERBOSE, COSTS OFF)
SELECT id FROM orders WHERE is_big_order_sd(total);This plan shows a Seq Scan with Filter: is_big_order_sd(total). The function is called once for each of the 100,000 rows. The planner also cannot know what the function does, so it uses a default selectivity guess for the filter.
Set-returning functions
A set-returning function that appears in the FROM clause can also be inlined. The planner turns the call into a subquery, which it can then flatten into the outer query. The conditions are close to the scalar ones, with two differences:
- The function must not be
VOLATILE. A volatile function is supposed to run with its own snapshot, and inlining would break that. UseSTABLEorIMMUTABLE. - The function must not be
STRICT. Strictness for a set-returning function would mean returning zero rows on a NULL argument, and the planner cannot enforce that after inlining.
The body must be a single SELECT. A set-returning call in the select list is not inlined.
The recent_orders function from the earlier chapter qualifies:
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
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 (COSTS OFF)
SELECT * FROM recent_orders(42, 5) WHERE total > 1500;The plan shows a scan of orders with the customer_id = 42 condition inside it. There is no Function Scan node. If you add STRICT to the definition and run the query again, a Function Scan on recent_orders node appears.
Note that the WHERE total > 1500 in the outer query is applied after the inner LIMIT 5. Inlining does not change the meaning of the query. The planner will not push that condition below the LIMIT.
How the decision is made
Checking whether inlining happened
You do not need to guess. Run EXPLAIN (VERBOSE) and look at the plan:
| What you see | What it means |
|---|---|
| The body's expression in a `Filter` or `Index Cond` | The call was inlined (scalar function). |
| The function name in a `Filter` or `Output` line | The call was not inlined. |
| No `Function Scan` node for a function in `FROM` | The set-returning function was inlined. |
| `Function Scan on name` | The set-returning function was not inlined. |
The planner does not tell you which condition failed. You find it by going through the list above. The usual causes are a SET clause, SECURITY DEFINER, STRICT on a set-returning function, a VOLATILE set-returning function, or a body with more than one statement.
Common problems
Pinning search_path turns inlining off. Adding SET search_path = ... is the standard way to secure a function, but it counts as a SET clause and blocks inlining. If you need both security and speed, create the schema objects you reference so that no SET is required, or accept the call overhead for that function. Do not remove the SET from a SECURITY DEFINER function to get inlining. A SECURITY DEFINER function is never inlined anyway.
A wrong volatility label blocks inlining and hides bugs. If you mark a function IMMUTABLE but its body uses now(), the planner will not inline it. If it did, it could fold the value into a plan and reuse stale results. Fix the label instead of working around the symptom.
STRICT is not free. A scalar STRICT function can still be inlined when its body is strict, as in p_total >= 1990. A body that handles NULL itself, for example with COALESCE, is not strict. Then STRICT blocks inlining. If the function must handle NULL, leave STRICT off and write the NULL logic in the body.
Repeated parameters can duplicate work. If a parameter appears twice in the body and the argument is an expensive expression, the planner declines to inline instead of evaluating the expensive expression twice.
Multi-statement bodies are never inlined. If you wrap an extra statement around a single SELECT, even one that does nothing, the planner stops inlining. A procedure is never inlined, because a CALL runs as a statement of its own.
PL/pgSQL is never inlined. A function written in plpgsql is always a black box to the planner. This is one of the main reasons to choose SQL for small expression helpers and set-returning wrappers over a query.
Exercise
You have a STABLE function orders_for(p_customer int) that returns SETOF orders from a single SELECT ... WHERE customer_id = p_customer. A teammate adds STRICT and SET search_path = public to it, and a query that joins to orders_for(c.id) becomes much slower. Explain why, and name the cheapest change that restores the old plan.
Show answer
Both additions block inlining of a set-returning function. A STRICT set-returning function cannot be inlined because the planner cannot enforce the strictness once the body is merged into the outer query, and a SET clause also prevents inlining. The join now shows a Function Scan that runs the body separately for each call, with no index use or good row estimate from the outer query. The cheapest fix is to remove STRICT and SET search_path. If the function is not SECURITY DEFINER, the SET is usually unnecessary.
Exercise
Which of these scalar functions can the planner inline? (a) SELECT $1 * 2 with LANGUAGE sql IMMUTABLE. (b) SELECT coalesce($1, 0) with LANGUAGE sql IMMUTABLE STRICT. (c) SELECT max(v) FROM t WHERE k = $1 with LANGUAGE sql STABLE.
Show answer
Only (a). In (b), coalesce is not strict, so the body is not strict and STRICT blocks inlining. In (c), the body has a FROM clause and an aggregate, so it is not a plain expression and runs as a separate query on every call.