Prepared Statement
In one line
Prepared statements pre-compile SQL with placeholders — faster for repeated execution and immune to SQL injection.
In simple words
A prepared statement is a SQL query template with parameter placeholders (? or $1) that is pre-compiled by the database. You send the template once, then execute it multiple times with different parameter values.
Benefits:
- Performance — the query plan is compiled once and reused, avoiding re-parsing for each execution
- Security — parameters are sent separately from the SQL text, making SQL injection impossible
- Type safety — the database knows parameter types
The database parses, validates, and optimizes the query once. Subsequent executions skip these steps, just plugging in new parameter values. This is especially beneficial for queries executed in loops.
Example
// Node.js with prepared statements
const stmt = db.prepare("SELECT * FROM users WHERE age > ? AND city = ?");
// Execute multiple times with different params
const adults1 = stmt.all(18, "NYC");
const adults2 = stmt.all(21, "LA");
// SQL injection is impossible — params are data, not SQL
const malicious = stmt.all(18, "NYC; DROP TABLE users;");
// This safely searches for city = "NYC; DROP TABLE users;"The SQL template is compiled once. Parameters are sent as data, not SQL — injection is impossible. Repeated executions reuse the compiled plan.
Common confusions
Confused with: stored procedure
The difference: A prepared statement is a single SQL query template with parameters, pre-compiled for reuse. A stored procedure is a named block of SQL code stored in the database, can contain multiple statements, control flow, and business logic. Prepared statements are lightweight; stored procedures are full programs.
Related terms
Related Resources
Related Lessons
- SQL Security
Prepared statements.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.