Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A PL/pgSQL function that looks up orders by status is fast for the first few calls in a session and then suddenly becomes slow for rare status values. Explain what changed and how you would fix it.

PL/pgSQL prepares and caches a plan for each SQL statement in the function, and after five executions PostgreSQL may switch from custom plans, built for each actual parameter value, to a generic plan that ignores the value, if the generic plan looks no more expensive on average. A generic plan suited to common statuses, such as a sequential scan, is then used for rare statuses where an index would be far faster. We confirm it with auto_explain or PREPARE and EXPLAIN EXECUTE, and fix it with plan_cache_mode = force_custom_plan on the function, dynamic SQL with EXECUTE, or better statistics.

Why this question is asked

This bug is memorable because it seems to depend on time rather than input: the function is fast right after a deploy or a reconnect, and slow later in the same session. Interviewers ask it to see whether we understand plan caching, which affects not just PL/pgSQL but every prepared statement from Java. In this answer, we will recap how PL/pgSQL plans its queries, reproduce the switch to a generic plan, see why it hurts skewed data, diagnose it with the tools PostgreSQL gives us, and go through the fixes, ending with the same effect in JDBC.

1A Quick Recap: How PL/pgSQL Plans Its Queries

When a PL/pgSQL function runs a SQL statement for the first time in a session, it prepares it, much like a PREPARE statement, and keeps the prepared statement for later calls. The function's parameters become parameters of that statement. For each execution, PostgreSQL can either build a custom plan, made for the actual parameter values, or reuse a generic plan, made without knowing the values.

Custom plans are better informed but cost planning time on every call. Generic plans are planned once and reused. PostgreSQL decides with a simple rule: the first five executions use custom plans. From then on, it compares the estimated cost of the generic plan with the average estimated cost of the custom plans so far, and if the generic plan is not more expensive, it switches to the generic plan for the rest of the session.

2Reproducing the Slowdown

Suppose orders has 50 million rows, 98 percent of them with status 'DELIVERED' and a few hundred with status 'DISPUTED', and an index on status. The function returns orders with a given status.

SQL
CREATE FUNCTION orders_by_status(p_status text)
RETURNS SETOF orders LANGUAGE plpgsql STABLE AS $$
BEGIN
RETURN QUERY SELECT * FROM orders WHERE status = p_status ORDER BY created_at DESC LIMIT 50;
END $$;
-- In one session:
SELECT * FROM orders_by_status('DELIVERED'); -- calls 1 to 5: custom plans, about 3 ms each
SELECT * FROM orders_by_status('DISPUTED'); -- call 6: generic plan chosen, 2.8 s
-- A new session:
SELECT * FROM orders_by_status('DISPUTED'); -- 1 ms again (custom plan)
Step throughHow PostgreSQL chooses a plan for a cached statement
  1. Execution 1 to 5custom plan for each actual value
  2. Average the custom plan costsdominated by the common value
  3. Generic plan cost <= average?
    YesUse the generic plan from now onNoKeep building custom plans
  4. Rare value meets the generic planplan shape suits the common value
  5. 2.8 s instead of 1 msuntil the session ends

5 steps in order. Play them, or step through them one at a time.

The switch is decided on estimates from the first calls, then sticks for the session.

For 'DELIVERED', a good custom plan walks an index on created_at backwards and stops after 50 matching rows, because almost every row matches. For 'DISPUTED', a good custom plan uses the status index to fetch a few hundred rows and sort them. The generic plan cannot know which value it will get, so it is built from average estimates, and those averages are dominated by the common value. It picks the created_at walk. For 'DISPUTED', that walk has to read through millions of delivered orders to find 50 disputed ones.

3Diagnosing It

The plan inside a function is invisible to a normal EXPLAIN of the call. Two tools reveal it. auto_explain, a module shipped with PostgreSQL, logs the plans of slow statements, and with log_nested_statements turned on it includes statements run inside functions. Or we reproduce the switch by hand with PREPARE and EXPLAIN EXECUTE, running the statement six times to cross the threshold.

Java
LOAD 'auto_explain';
SET auto_explain.log_min_duration = '500ms';
SET auto_explain.log_nested_statements = on;
SET auto_explain.log_analyze = on;
SELECT * FROM orders_by_status('DISPUTED');
-- log: Limit -> Index Scan Backward using orders_created_idx ... Filter: (status = $1)
-- Rows Removed by Filter: 4127301
PREPARE q(text) AS SELECT * FROM orders WHERE status = $1 ORDER BY created_at DESC LIMIT 50;
EXPLAIN EXECUTE q('DISPUTED'); -- run it six times; the sixth shows Filter: (status = $1)
-- PostgreSQL 16 and later also offer EXPLAIN (GENERIC_PLAN) to show the generic plan directly.

Notice the giveaway: a generic plan shows the parameter as $1 instead of the literal value, and Rows Removed by Filter shows the millions of rows read for nothing.

4Fix 1: Force Custom Plans for This Function

Since PostgreSQL 12, the setting plan_cache_mode controls the choice. auto is the default behaviour we described, force_custom_plan always plans for the actual values, and force_generic_plan always reuses. We can attach the setting to just this function, so it applies whenever the function runs and nowhere else.

SQL
ALTER FUNCTION orders_by_status(text) SET plan_cache_mode = force_custom_plan;
SELECT * FROM orders_by_status('DISPUTED'); -- 1 ms on every call, however many calls came before

The cost is planning time on every call, typically a fraction of a millisecond for a query like this, which is a good trade for skewed data. This is usually the cleanest fix.

5Fix 2 and 3: Dynamic SQL or Better Statistics

EXECUTE in PL/pgSQL runs a query string that is planned fresh each time and never cached, so it always gets a custom plan. We pass values with USING, never by concatenating them into the string, which would open the door to SQL injection.

Statistics can also help. If the planner's estimates for rare values are poor, the custom-plan costs in the first five calls mislead the comparison. Raising the statistics target for the status column lets ANALYZE record more of its common values and their frequencies, so estimates are better. This improves custom plans and sometimes the decision itself, but it does not change the fact that a generic plan cannot fit both values, so for strongly skewed columns we still force custom plans.

Java
RETURN QUERY EXECUTE
'SELECT * FROM orders WHERE status = $1 ORDER BY created_at DESC LIMIT 50'
USING p_status; -- planned for the real value on every call
ALTER TABLE orders ALTER COLUMN status SET STATISTICS 1000;
ANALYZE orders;

6The Same Problem From JDBC

Java code hits the same switch without any PL/pgSQL. The PostgreSQL JDBC driver sends a PreparedStatement as an unnamed statement at first; after it has been executed prepareThreshold times on the same connection, five by default, the driver switches to a named server-side prepared statement, and from then on the server's own custom-versus-generic rule applies to it. With a connection pool, connections live for hours, so a query that was fast in testing can become slow in production for rare values after enough executions on one connection. The same fixes work: set plan_cache_mode for the application role or the session, or change prepareThreshold in the connection URL; check your driver version's defaults.

SQL
ALTER ROLE app SET plan_cache_mode = force_custom_plan; -- for every session of this role
# or in the JDBC URL
jdbc:postgresql://db:5432/shop?prepareThreshold=0 # never switch to server-side prepared statements

7Follow-up questions

Why does PostgreSQL use generic plans at all?

Planning costs time. For short queries run thousands of times per second with similar values, reusing one generic plan saves real CPU. The rule works well when data is evenly spread; it fails when a column is skewed and different values need different plan shapes.

Would partial indexes help here?

A partial index such as ON orders (created_at) WHERE status = 'DISPUTED' makes rare-status queries fast in a custom plan. A generic plan cannot use it, because it does not know the parameter will match the index's condition, so we still need custom plans for it.

Is the cache shared between sessions?

No. Each session has its own plan cache, which is why a new session or a reconnect makes the function fast again until it crosses the threshold. That pattern is a strong hint that plan caching is the cause.

8Conclusion

In this answer, we saw that PL/pgSQL caches a prepared plan for each statement, uses custom plans for the first five executions, and then may switch to a generic plan if it looks no more expensive on average. On skewed data the generic plan fits the common value and is very slow for rare ones. auto_explain with log_nested_statements, or PREPARE with EXPLAIN EXECUTE, shows the generic plan with $1 in it. We fix it with plan_cache_mode = force_custom_plan on the function, EXECUTE with USING, or better statistics, and the same switch happens with JDBC prepared statements after prepareThreshold executions.

What to say in the interviewAbout 90 seconds aloud

Open with

What changed is the plan, not the data. PL/pgSQL prepares each SQL statement in a function the first time it runs in a session and caches it. For the first five executions PostgreSQL builds a custom plan for the actual parameter value.

Then, if they want more

After that it compares the generic plan, which ignores the value, with the average cost of those custom plans, and if the generic one is not more expensive it uses it for the rest of the session.

With a skewed status column, the averages are dominated by the common statuses, so the generic plan is something like walking the created_at index, which is great for DELIVERED and terrible for a rare status like DISPUTED, where it reads millions of rows to find a few.

That is why it is fast at first, slow later, and fast again in a new session. To confirm, I would use auto_explain with log_nested_statements so plans inside functions are logged, and look for $1 in the filter, or reproduce it with PREPARE and EXPLAIN EXECUTE six times. The fix I would usually choose is ALTER FUNCTION ...

SET plan_cache_mode = force_custom_plan, which plans for the real value every call at a small planning cost. Alternatives are EXECUTE with USING, which is always planned fresh, or better statistics. I would also check the Java side, since JDBC prepared statements switch to server-side statements after prepareThreshold executions and hit the same issue.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 12, PostgreSQL 16
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A PL/pgSQL function that looks up orders by status is fast for the first few calls in a...": https://scrivio-interview-library.netlify.app/databases/stored-code/3c20d7c05a/