Parameters and Prepared Statements
A parameterized query in SQL is a statement written with placeholders, such as $1 or ?, whose values are sent to the database separately from the SQL text. A prepared statement is such a statement that the database has already parsed and planned, ready to run many times with different values. Parameters are how every program should pass user input to a database: they stop injection through values, and they let the database reuse its work. In this lesson, we will use PREPARE and EXECUTE in SQL, write the same thing in Java, JavaScript and Python, and handle the one thing parameters can't do: table and column names.
In One Minute
- Placeholders differ by tool:
$1(PostgreSQL, Node'spg),?(JDBC, MySQL, SQLite),%s(Python's psycopg),@name(SQL Server). PREPARE name (types) AS ...parses a statement once;EXECUTE name (values)runs it.- Values are always data: quotes, semicolons and keywords inside them do nothing.
- Only values can be parameters, never table names, column names or keywords like
ASC. - For names, check the input against an allow-list of known names.
Syntax
PREPARE statement_name (data_type [, ...]) AS
SQL statement using $1, $2, ...;
EXECUTE statement_name (value [, ...]);
DEALLOCATE statement_name;| Database or library | Placeholder | Example |
|---|---|---|
PostgreSQL PREPARE, Node.js pg | $1, $2 | WHERE student_id = $1 |
| Java JDBC, MySQL, SQLite | ? | WHERE student_id = ? |
| Python psycopg | %s (or %(name)s) | WHERE student_id = %s |
SQL Server (sp_executesql, ADO.NET) | @name | WHERE student_id = @student_id |
PREPARE and EXECUTE
PREPARE student_payments (INTEGER, DATE) AS
SELECT payment_id, amount_usd, paid_on
FROM payments
WHERE student_id = $1 AND paid_on >= $2
ORDER BY payment_id;
EXECUTE student_payments (101, '2025-12-01');
EXECUTE student_payments (103, '2025-01-01');
SELECT name, parameter_types FROM pg_prepared_statements;PREPARE
payment_id | amount_usd | paid_on
------------+------------+------------
3 | 250.00 | 2025-12-03
4 | 550.00 | 2025-12-29
5 | 200.00 | 2026-01-05
(3 rows)
payment_id | amount_usd | paid_on
------------+------------+------------
6 | 225.00 | 2025-11-14
7 | 225.00 | 2025-12-19
(2 rows)
name | parameter_types
------------------+-----------------
student_payments | {integer,date}
(1 row)Explanation: PREPARE parses the statement and checks its tables and columns once. Each EXECUTE supplies new values: Srihitha's payments since December, then all of Navika's. pg_prepared_statements lists the session's prepared statements with their parameter types. A prepared statement lasts until the session ends or DEALLOCATE removes it.
From Java (JDBC)
JDBC's PreparedStatement uses ? placeholders, numbered from 1, with a set method per type:
static void search(Connection conn, String text) throws SQLException {
String sql = "SELECT course_id, title FROM courses"
+ " WHERE title ILIKE '%' || ? || '%' ORDER BY course_id";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, text);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
System.out.println(rs.getInt("course_id") + " "
+ rs.getString("title"));
}
}
}
}Calling search(conn, "java") and then search(conn, "x' OR '1'='1") against the Fee Tracker prints:
search 'java':
1 Java Basics
2 Java OOP
3 Java Collections
5 JavaScript Basics
search "x' OR '1'='1":
(end)Explanation: ps.setString(1, text) binds the first ?. The wildcards are joined to the value inside the SQL with ||, so the user's text is never pasted into the SQL string. The attack text matches nothing. try (...) closes the statement and result set automatically. SQL from Java covers connections and transactions.
From JavaScript (Node.js)
The pg library numbers its placeholders $1, $2, and takes the values as an array:
async function searchCourses(text) {
const { rows } = await pool.query(
"SELECT course_id, title FROM courses " +
"WHERE title ILIKE '%' || $1 || '%' ORDER BY course_id", [text]);
return rows;
}searchCourses('java') returns four rows and searchCourses("x' OR '1'='1") returns []:
[
{ course_id: 1, title: 'Java Basics' },
{ course_id: 2, title: 'Java OOP' },
{ course_id: 3, title: 'Java Collections' },
{ course_id: 5, title: 'JavaScript Basics' }
]
[]From Python
psycopg uses %s for every type, with the values in a tuple:
import psycopg
with psycopg.connect("host=127.0.0.1 port=5433 user=postgres dbname=postgres") as conn:
rows = conn.execute(
"SELECT payment_id, amount_usd FROM payments"
" WHERE student_id = %s AND paid_on >= %s ORDER BY payment_id",
(101, "2025-12-01"),
).fetchall()
for payment_id, amount in rows:
print(payment_id, amount)3 250.00
4 550.00
5 200.00Explanation: %s looks like Python's old string formatting, but psycopg sends the values separately; never build the string yourself with % or an f-string. SQL from Python goes further.
Names Can't Be Parameters
Parameters stand for values, not for parts of the SQL's structure. A table name, column name or keyword can't be a placeholder:
PREPARE list_any (TEXT) AS
SELECT * FROM $1;ERROR: syntax error at or near "$1"Explanation: The database must know which table to read when it parses the statement, before any value arrives, so $1 isn't allowed there. The same goes for ORDER BY $1 (it would sort by a constant, not a column) and for ASC/DESC.
When users choose a sort column, map their choice to a name from a fixed allow-list in your code:
// Column names can't be parameters, so check them against a fixed list.
const SORTABLE = { title: 'title', fee: 'fee_usd', level: 'level' };
async function listCourses(sortKey) {
const column = SORTABLE[sortKey];
if (!column) throw new Error(`cannot sort by ${sortKey}`);
const { rows } = await pool.query(
`SELECT title, fee_usd FROM courses ORDER BY ${column}, course_id LIMIT 3`);
return rows;
}listCourses('fee') sorts by fee_usd; anything not on the list is refused before it reaches SQL:
[
{ title: 'Git Basics', fee_usd: '250.00' },
{ title: 'SQL Basics', fee_usd: '400.00' },
{ title: 'Java Basics', fee_usd: '450.00' }
]
cannot sort by fee_usd; DROP TABLE coursesExplanation: Only the three names in SORTABLE can ever reach the SQL, so pasting column in is safe. Notice that pg returns NUMERIC values as strings ('250.00'), so they don't lose precision in JavaScript.
Inside the database, PL/pgSQL code that must build SQL with names uses format with %I, which quotes an identifier safely:
SELECT format('SELECT * FROM %I ORDER BY %I', 'courses', 'title') AS normal_name,
format('SELECT * FROM %I ORDER BY %I', 'courses', 'title; DROP TABLE courses') AS hostile_name; normal_name | hostile_name
--------------------------------------+------------------------------------------------------------
SELECT * FROM courses ORDER BY title | SELECT * FROM courses ORDER BY "title; DROP TABLE courses"
(1 row)Explanation: %I wraps a strange name in double quotes, so title; DROP TABLE courses becomes one (nonexistent) column name rather than a second statement. %L does the same for literal values.
Prepared Statements and Performance
Preparing a statement once and executing it many times skips the repeated parsing. PostgreSQL can also reuse a plan: for the first five executions it plans with the actual values, then may switch to one generic plan if that's no worse. Drivers often prepare statements for you behind the scenes. The safety benefit is the main one, though: use parameters even for queries that run once.
Common Mistakes
Concatenating inside a library call. query("... = '" + x + "'") is unsafe even with a "safe" library.
Putting quotes around placeholders. WHERE last_name = '$1' compares with the literal text $1. Write WHERE last_name = $1.
Trying to parameterize names. Use an allow-list.
Building IN (...) lists by hand. Pass an array instead: WHERE student_id = ANY($1) with [101, 103] in pg.
Interview Corner
What is a prepared statement?
A SQL statement with placeholders that the database parses (and can plan) once, then executes repeatedly with different parameter values. Values are sent separately from the SQL, which prevents injection.
Can you use a parameter for a table or column name?
No. Parameters stand for values only. For dynamic names, choose from an allow-list in the application, or use identifier quoting such as format('%I', name) in PL/pgSQL.
What placeholders do different databases use?
$1 in PostgreSQL and Node's pg, ? in JDBC, MySQL and SQLite, %s in Python's psycopg, and @name in SQL Server.
Practice
Challenge (module checkpoint, part 1): This Java code is injectable:
String sql = "SELECT course_id, title FROM courses WHERE title ILIKE '%"
+ text + "%'";
ResultSet rs = conn.createStatement().executeQuery(sql);The fixed Java and JavaScript versions are the search and searchCourses functions above. Write the same safe search in SQL with PREPARE, and run it with script and with the attack text ' OR ''='.
Show solution
PREPARE search_courses (TEXT) AS
SELECT course_id, title
FROM courses
WHERE title ILIKE '%' || $1 || '%'
ORDER BY course_id;
EXECUTE search_courses ('script');
EXECUTE search_courses (''' OR ''''=''');PREPARE
course_id | title
-----------+-------------------
5 | JavaScript Basics
(1 row)
course_id | title
-----------+-------
(0 rows)"script" finds JavaScript Basics. The attack text is searched for as ordinary characters and matches nothing. Part 2 of the checkpoint is in Row-Level Security.
Key Takeaways
| Language | Safe query |
|---|---|
| SQL | PREPARE p (INTEGER) AS ... WHERE student_id = $1; EXECUTE p (103); |
| Java | conn.prepareStatement("... WHERE student_id = ?") + ps.setInt(1, 103) |
| JavaScript | pool.query('... WHERE student_id = $1', [103]) |
| Python | conn.execute("... WHERE student_id = %s", (103,)) |
Was this tutorial helpful?