Prepared Statement
Prepared Statement with Go/pgx!
1. What is a prepared statement?
In PostgreSQL (and many other databases), a prepared statement means:
- The database parses, plan, and optimizes the SQL query once.
- After that, the statement can be reused multiple times with different parameters.
Example:
-- prepared statement (parse + plan once)
PREPARE get_user (int) AS
SELECT name FROM users WHERE id = $1;-- reused state multiple times
EXECUTE get_user(1);
EXECUTE get_user(2);In Go/pgx, when you code:
row := pool.QueryRow(ctx, "SELECT name FROM users WHERE id=$1", userID)pgx can automatically use the prepared statement mechanism for you (depending on the configuration).
2. If not using prepared statement
Each time you query:
- PostgreSQL receives the SQL in string form.
- Parse the SQL string → into a syntax tree (AST).
- Plan → the DB computes an execution plan (which index to use, which join strategy, etc).
- Optimize
- Execute with parameters.
⇒ Step 2–4 consume CPU and time, especially when the query is repeated thousands of times per second.
3. If using prepared statement
The parse/plan step runs only once, when preparing the statement.
Get 0x48core’s stories in your inbox
Join Medium for free to get updates from this writer.
For subsequent executions, the database only needs to bind the parameters and execute the existing plan.
Lower CPU usage (less overhead from parse/plan).
Lower latency (queries return faster).
4. Real-world example
A case where a query runs repeatedly, for example in an API:
SELECT name FROM users WHERE id=$1;- If not prepared, the DB has to parse + plan again for each request → overhead.
- If prepared, the DB only needs to bind
$1 = userIDand execute immediately → more efficient.
5. Trade-off
- Prepared statements consume memory for caching.
- If a query runs one or twice, the benefit it negligible.
- But for hot paths, where queries run many times per second, performance improves significantly.





