PostgreSQL PREPARE can't CALL stored procedures, but you can still bind and prepare CALL myproc($1)
Tom Kyte's classic advice — "use bind variables" — isn't Oracle-specific. For OLTP, you should define the operation once and pass changing data as parameters, rather than constructing new executable SQL for every request.
This improves security, as recommended by OWASP's SQL Injection Prevention Cheat Sheet, and lets the database recognize and reuse a stable operation. At the service level it fits Martin Fowler's Remote Facade: expose well-defined, coarse-grained operations with explicit arguments.
Bind values, reuse operations, validate and authorize inputs, and monitor statement cardinality and observability.
The solution has been known for decades, yet in many applications changing inputs still become a new SQL string on every request. While looking at HammerDB's PostgreSQL driver, I found this comment in the connection-pool driver code:
PostgreSQL does not support prepared statements for stored procedures
HammerDB's PostgreSQL interface implemented prepared-statement support before PQprepare() existed in the PostgreSQL C API, so it relies on SQL PREPARE together with PQexecPrepared(). That works for function calls expressed as SELECT, but not for procedures, because SQL PREPARE does not accept CALL.
Today, though, "prepared statement" names two different interfaces in PostgreSQL. SQL PREPARE genuinely cannot prepare a CALL — but the extended query protocol can. Let's test that distinction with a procedure that does almost nothing, so the surrounding work is more visible.
The problem is not the number of procedure calls itself. It is turning changing inputs into thousands of distinct SQL texts that monitoring, caches, and logging must process.
What changing literals actually cost
The controlled tests below reproduce three consequences of not using bind variables:
-
Fragmented and evicted statistics: on PostgreSQL 16, 20,000 unique literal calls overflow
pg_stat_statements' default capacity, leaving only 4,751 recorded outer calls. The inner SQL still records all 20,000 executions under one identity. - Prepared-statement cache churn: on PostgreSQL 19 with PgBouncer 1.26.1, 400 literal SQL shapes cycle through a 200-entry cache, causing 2,400 server preparations for 2,000 calls. Bound SQL needs one preparation.
- Larger audit-log storage and retained input data: on PostgreSQL 19 with pgAudit, changing synthetic literals makes compressed audit messages 65.7 times larger than repeating the same literal. Turning parameter logging off does not hide values embedded in SQL text.
SQL PREPARE really does reject CALL
Here is my procedure:
postgres=> CREATE PROCEDURE public.bench_proc(integer)
LANGUAGE plpgsql AS $$
BEGIN
NULL;
END;
$$
;
CREATE PROCEDURE
Calling it works:
postgres=> CALL public.bench_proc(42);
CALL
Preparing a SELECT also works:
postgres=> PREPARE select_demo(integer) AS SELECT $1
;
PREPARE
postgres=> EXECUTE select_demo(42)
;
?column?
----------
42
(1 row)
But this does not:
postgres=> PREPARE sql_call(integer) AS
CALL public.bench_proc($1)
;
ERROR: syntax error at or near "CALL"
The documentation for SQL PREPARE lists SELECT, INSERT, UPDATE, DELETE, MERGE, and VALUES as its supported statements. CALL is not on that list.
Preparing the same call without SQL PREPARE
SQL PREPARE/EXECUTE is handy for testing from psql, but it is not parameter binding at the wire level: EXECUTE arguments are expressions embedded in the query text. It gives you plan reuse without making interpolated input safe.
Applications handling user input should use out-of-line parameters instead: values bound as data, never interpolated into SQL text. That eliminates injection through the bound values — though it doesn't protect unrelated string concatenation or dynamic SQL inside a routine.
The extended query protocol separates preparing a statement (Parse), supplying values (Bind), and executing it (Execute) into distinct protocol messages rather than SQL command strings. Since PostgreSQL 17, psql can prepare (\parse), bind (\bind), and execute (\g):
postgres=> CREATE PROCEDURE public.bench_echo(IN value integer, OUT result integer)
LANGUAGE plpgsql AS $$
BEGIN
result := value;
END;
$$
;
CREATE PROCEDURE
postgres=> CALL public.bench_echo($1, NULL) -- is the OUT-parameter placeholder
postgres-> \parse prepared_call
postgres=> \bind_named prepared_call 42
postgres=> \g
result
--------
42
(1 row)
postgres=> \bind_named prepared_call 99
postgres=> \g
result
--------
99
(1 row)
In the same session, I can inspect the prepared statement:
postgres=> SELECT name, statement, parameter_types, from_sql
FROM pg_prepared_statements
WHERE name = 'prepared_call'
;
name | statement | parameter_types | from_sql
---------------+----------------------------------+-----------------+----------
prepared_call | CALL public.bench_echo($1, NULL) | {integer} | f
(1 row)
from_sql = false is the useful detail. This is a server-side prepared statement, created through the frontend/backend protocol rather than the SQL PREPARE command.
Three pgbench modes, one procedure
Now I can compare the submission paths without replacing the procedure with a function. My pgbench script is:
\set a random(1, 1000000000)
CALL public.bench_proc(:a);
I run it with the three -M modes:
for protocol in simple extended prepared
do
echo '
\set a random(1, 1000000000)
CALL public.bench_proc(:a);
' | pgbench -n -M "${protocol}" -c 10 -T 15 -f /dev/stdin --random-seed=42
done
Here is the difference:
| pgbench mode | SQL submitted | Values bound separately? | Reuse preparation across iterations? |
|---|---|---|---|
simple |
CALL public.bench_proc(684288445) |
❌ | ❌ |
extended |
CALL public.bench_proc($1) |
✅ | ❌ |
prepared |
CALL public.bench_proc($1) |
✅ | ✅ , per connection |
Parameter binding is not the same as preparation reuse. In extended mode, pgbench submits a new unnamed statement each time: stable SQL text, but the server still parses and analyzes it. In prepared mode, pgbench uses PQprepare then PQsendQueryPrepared — no PREPARE ... AS CALL is ever generated. And reusing parsed state doesn't guarantee a single generic plan for every execution.
A TPS comparison answers a protocol-cost question but doesn't isolate the effect of many distinct SQL strings. For that I need a fixed-literal control on the same simple protocol. (An anonymous DO $$ ... $$ block isn't an equivalent control — its body is a quoted string, not an outer parameter position, and pgbench's extended/prepared modes fail on it with bind message supplies 1 parameters, but prepared statement ... requires 0.)
The SQL inside the procedure is already parameterized
Static SQL inside PL/pgSQL has its own SPI preparation and plan caching, reused regardless of whether the outer call contains literals. One qualification: a cached prepared statement doesn't mean one plan forever — PostgreSQL can pick custom plans from current parameter values and rebuild after invalidation. The claim is narrower: changing outer literals does not defeat the routine's internal statement cache.
To keep that visible, my cardinality test uses this procedure:
CREATE PROCEDURE public.cardinality_proc(IN p_value integer)
LANGUAGE plpgsql AS $$
BEGIN
PERFORM p_value + 1;
END;
$$;
Every test executes the same tiny static statement inside it. There are no application tables or writes. I track nested statements as well as top-level calls, so I can compare their statistics separately.
Change only the number of literal variants
This is the pgbench script for the controlled test:
\set ordinal :ordinal + 1
\set value 100000000 + ((:client_id * :per_client + :ordinal - 1) % :distinct)
CALL public.cardinality_proc(:value);
It generates deterministic values, not random collisions. The values always have nine decimal digits, so increasing diversity does not increase the length of the literal SQL.
For 20,000 calls across eight clients, I set per_client=2500, start ordinal=0, and vary distinct:
| Case | Protocol | Distinct argument values | What changes? |
|---|---|---|---|
| Fixed literal | simple |
1 | The same literal SQL repeats |
| Ten literals | simple |
10 | Ten literal SQL strings cycle |
| Unique literals | simple |
20,000 | Every call has different literal SQL |
| Bound values | extended |
20,000 | Values change but SQL stays CALL public.cardinality_proc($1)
|
The first three cases use the same protocol, script, client count, arithmetic, procedure, and SQL length. The fourth asks whether binding the values avoids multiplying the identities without requiring named preparation reuse.
I ran the tests on native ARM64 Docker with PostgreSQL 16.16 and 19.0, using pg_stat_statements and Percona's pg_stat_monitor 2.4.1, one extension at a time, with compute_query_id = on and track = all so inner SQL is visible.
First consequence: one procedure becomes many monitoring identities
Start below the statistics capacity, with 1,000 successful calls in each case:
| PostgreSQL | Observer | Fixed literal | Ten literals | 1,000 unique literals | 1,000 bound values |
|---|---|---|---|---|---|
| 16.16 | pg_stat_statements |
1 | 10 | 1,000 | 1 |
| 16.16 |
pg_stat_monitor 2.4.1 |
1 | 10 | 1,000 | 1 |
| 19.0 | pg_stat_statements |
1 | 1 | 1 | 1 |
| 19.0 |
pg_stat_monitor 2.4.1 |
1 | 1 | 1 | 1 |
The numbers are distinct outer query IDs, not execution counts; all cases completed 1,000 calls, and the inner SQL kept one query ID with 1,000 calls in every case.
The cardinality effect is real and reproducible — on PostgreSQL 16. On 19, it disappears.
What changed between PostgreSQL 16 and 19
PostgreSQL computes a queryId by "jumbling" the analyzed query tree — fingerprinting it while ignoring constant values — so that WHERE x = 1 and WHERE x = 2 share one identity. But through PostgreSQL 17, this normalization only applied to optimizable statements (SELECT/INSERT/UPDATE/DELETE/MERGE). Utility statements — including CALL — were fingerprinted with their literal text intact, so CALL p(1) and CALL p(2) produced different query IDs and different pg_stat_statements entries.
PostgreSQL 18 extended the jumble to cover utility statements, recording their constants as ignorable locations exactly like DML. The regression test now expects CALL sum_one(3) and CALL sum_one(199) to merge into a single CALL sum_one($1) entry — which is precisely what my 19.0 rows show: 1,000 unique literal calls collapse to one outer identity, matching the bound-parameter case.
So the monitoring-cardinality problem from literal CALLs is already fixed upstream as of PostgreSQL 18 — for pg_stat_statements and anything else keyed on queryId. What is not fixed:
Older supported versions. PostgreSQL 16 and 17 remain in support for years, and on them every literal CALL is a distinct identity — the fragmentation and eviction I measured on 16.16 is the behavior those versions will keep.
Anything keyed on raw text rather than queryId. Audit logs, pgAudit output, connection-pooler prepared-statement caches (the PgBouncer churn above happens on 19.0), and any monitoring or Query Store implementation that hashes the SQL string itself still see 20,000 different statements. Normalization helps the query-ID consumers but it does nothing for text consumers.
The parse cost itself. Even with a shared query ID, each literal call is still parsed and analyzed independently — binding remains the only way to make the text identical before it reaches the parser.
In other words: PostgreSQL 18+ repaired the observability symptom for queryId-based tools, but the underlying inefficiency — and the injection exposure — of interpolating values into SQL text is unchanged. The bind-parameter fix is still the right one. It just no longer has the query-ID explosion as its headline justification on current versions.
Second consequence: the statistics stop retaining the whole workload
Now execute 20,000 calls, with pg_stat_statements.max = 5000, its default capacity. Reset statistics before every case and query the outer and inner statements separately:
SELECT count(DISTINCT queryid) AS query_ids, sum(calls) AS retained_calls
FROM pg_stat_statements
WHERE toplevel
AND query LIKE 'CALL public.cardinality_proc%';
SELECT count(DISTINCT queryid) AS query_ids, sum(calls) AS retained_calls
FROM pg_stat_statements
WHERE NOT toplevel
AND query LIKE '%p_value%';
SELECT dealloc FROM pg_stat_statements_info;
Here is PostgreSQL 16.16:
| Case | Successful procedure calls | Outer IDs still present | Outer calls still recorded | Inner IDs | Inner calls recorded | Deallocation counter |
|---|---|---|---|---|---|---|
| Fixed literal | 20,000 | 1 | 20,000 | 1 | 20,000 | 0 |
| Ten literals | 20,000 | 10 | 20,000 | 1 | 20,000 | 0 |
| Unique literals | 20,000 | 4,751 | 4,751 | 1 | 20,000 | 61 |
| Bound values | 20,000 | 1 | 20,000 | 1 | 20,000 | 0 |
All three repetitions produced these counts. There were no failed transactions. The 20,000 distinct outer identities exceed the 5,000-entry capacity. The extension evicts entries, taking their counters with them. Only 4,751 of the outer calls remain represented at the end: 76.2% of those executions are no longer in the retained outer-call statistics.
That is not lost database work. The procedure ran 20,000 times, and the frequently executed inner statement still records all 20,000 executions. It is lost monitoring history, caused here by literal diversity in the outer CALL.
The exact retained-entry count is not a PostgreSQL guarantee: eviction works in batches, and other monitored statements consume entries too. The reproducible consequence is the overflow, deallocation, and incomplete outer-call counters. The extension documentation describes discarding statistics when the maximum number of distinct statements is exceeded.
Increasing pg_stat_statements.max delays that threshold. It does not turn distinct literal identities into one statement.
pg_stat_monitor: 20,000 identities for one logical operation
With its default storage limits, pg_stat_monitor retained all 20,000 unique calls in this test. But on PostgreSQL 16.16, it retained them as 20,000 outer query identities, compared with one for the bound-value case.
| PostgreSQL 16.16, pg_stat_monitor 2.4.1 | Outer query IDs | Outer calls recorded | Inner query IDs | Inner calls recorded |
|---|---|---|---|---|
| Fixed literal | 1 | 20,000 | 1 | 20,000 |
| Ten literals | 10 | 20,000 | 1 | 20,000 |
| Unique literals | 20,000 | 20,000 | 1 | 20,000 |
| Bound values | 1 | 20,000 | 1 | 20,000 |
The visible outer query texts totalled 780,000 bytes in the unique-literal case, versus 32 bytes in the bound-value case. There are also many more identities for a collector, dashboard, or exporter to retrieve and aggregate.
pg_stat_monitor has time buckets, so a query can have more than one statistics row across bucket boundaries. The tables count DISTINCT queryid, rather than treating every row as a distinct statement.
PostgreSQL 19.0 grouped the literal variants in both extensions: one outer query ID with all 20,000 calls, and one inner query ID with all 20,000 executions. However, other components in the PostgreSQL ecosystem may still suffer.
PostgreSQL 19: PgBouncer's prepared-statement cache still distinguishes literal texts
Normalizing a statistics entry does not make every other component recognize those statements as one operation. PgBouncer 1.26.1, for example, tracks protocol-level named prepared statements using their query text and parameter-type information, not PostgreSQL's normalized query ID.
Its per-server prepared-statement cache has a default capacity of 200. I tested transaction pooling with one backend connection and that capacity, on PostgreSQL 19.0.
For each case, the client creates 400 named statements, then executes every name five times: 2,000 procedure calls. Only the number of literal SQL shapes changes:
| Case | Client-side prepared names | Distinct SQL shapes | Successful calls | Server Parse messages |
|---|---|---|---|---|
| Same literal in every statement | 400 | 1 | 2,000 | 1 |
| Ten literal variants | 400 | 10 | 2,000 | 10 |
| 400 literal variants | 400 | 400 | 2,000 | 2,400 |
| Values bound to the same SQL | 400 | 1 | 2,000 | 1 |
PgBouncer can share one server-side preparation between many client names when their SQL matches. With 400 different literal statements, however, the working set exceeds the 200-entry cache. Cycling through all 400 statements repeatedly evicts the ones needed next.
The 2,400 server Parse messages include the initial 400 preparations and 2,000 subsequent preparations during execution. After the run, the server cache contains 200 statements.
PostgreSQL 19's pg_stat_statements still groups each case under one query ID. That does not protect PgBouncer's different, exact-text cache from churn. Statistics aggregation is not preparation deduplication.
PostgreSQL 19: pgAudit logs the literals even when parameter logging is off
Another consequence applies directly to literal calls, without a prepared-statement cache. pgAudit 19.0 can suppress separately bound parameter values, but those settings do not remove values already embedded in SQL text.
I enabled function auditing with these settings:
pgaudit.log = function
pgaudit.log_parameter = off
pgaudit.log_statement = on
The latter two are their defaults. For this test I used a text-argument procedure and 1,000 calls with 1 KiB synthetic values, deliberately amplifying the cost of recording values in the SQL text. The procedure returns the input length and its MD5 so the runner can verify that the bound-value case executed the same changing data, rather than skipping it.
| Case | Distinct logged statement texts | Total statement-text bytes | Gzipped audit-message bytes |
|---|---|---|---|
| One repeated literal value | 1 | 1,068,000 | 9,077 |
| 1,000 different literal values | 1,000 | 1,068,000 | 596,096 |
| The same 1,000 values, separately bound | 1 | 44,000 | 3,100 |
The first two cases use the same simple protocol and identical argument lengths. They emit the same uncompressed statement-text volume, but the changing literal values make the emitted audit messages much less compressible: 65.7 times the compressed size of the fixed-literal control in this deliberately high-entropy test.
The gzip figures compress the emitted AUDIT: message payloads joined with newlines, not the surrounding PostgreSQL JSON log envelopes. The statement-text column counts only the SQL field. These are byte measurements, not measurements of disk latency, CPU usage, or billed log-ingestion cost.
With bound parameters, the SQL text remains CALL public.rawtext_audit_proc($1,NULL,NULL). The default parameter suppression can then keep the input data out of the audit record. With literals, all 1,000 values remain visible inside the statement despite pgaudit.log_parameter = off.
The consequence is both log volume and data retention. An operator who suppresses parameter logging has not suppressed values concatenated into SQL. This is expected pgAudit behavior. If the audit policy requires recording input values, that policy still needs to be met. Binding is not an excuse to omit required audit data.
Also, pgaudit.log_statement_once deduplicates entries for a statement/substatement during an execution. It does not turn thousands of separately executed literal statements into one cross-execution record.
What this establishes
The consequence is not just that "prepared mode avoids parsing." Different literals can multiply monitoring identities, expand recorded text, and evict useful statistics. A constant-literal simple-protocol control shows that diversity itself matters in PostgreSQL 16. In PostgreSQL 19, it also prevents PgBouncer's exact-text preparation reuse and makes pgAudit records larger or less compressible.
Binding values avoids this multiplication, even though extended-mode control still parses and analyzes each call. Named preparation reuse is not necessary for this benefit.
For known operations, prefer an explicit operation with a defined argument contract over building executable expressions from request inputs. SQL bindings are one application of this general principle.
Practical rules for database and service code:
- Bind changing values. Never build SQL literals from request data such as names, dates, or amounts. Parameters represent values—not table names, columns, or keywords. Keep structural choices fixed, or restrict them to a strict, application-owned allow-list.
- Reuse request preparation when needed. Binding and named-statement reuse are separate capabilities. Keep SQL text and parameter types stable to enable exact-text cache reuse.
- Validate and authorize arguments. Enforce types, ranges, and payload limits, and verify caller permissions. Use least-privileged accounts. Preventing values from altering SQL syntax does not make them valid or authorized.
- Make observability part of the contract. Monitor statement-identity cardinality, cache capacity, and log volume. Determine which input values the audit policy requires you to retain. Suppressing parameter logs does not remove literals already embedded in statement text.
I wrote this after encountering the HammerDB issue and opening PostgreSQL TPROC- C: use bind parameters for stored-procedure CALLs #977. It will be addressed by Add PQprepare() support for native prepared statements.
You can—and should—call stored procedures using bind variables, such as CALL myproc($1), through the extended protocol, not with PREPARE.