SQL PREPARE defines a server-side prepared statement, giving it a name, optional parameter types, and the SQL command to run. The database parses, rewrites, and plans the statement once, then stores the execution plan in memory. Subsequent EXECUTE calls reference the prepared statement by name, supplying actual parameter values. This reduces parsing overhead, can improve performance, and guards against SQL-injection when used with parameters. Prepared statements live only for the current session unless explicitly DEALLOCATEd or the session ends. Some dialects (PostgreSQL, SQL Server with sp_prepare, MySQL with PREPARE … FROM) differ slightly in syntax and scope, but the core idea is identical: separate preparation from execution.
statement_name
(identifier) - Name of the prepared statement (unique within the session)data_type
(type) - Optional list of parameter data types in positional ordersql_statement
(string) - Any SQL command that can be parameterized (SELECT, INSERT, etc.)EXECUTE, DEALLOCATE, BIND parameters, parameterized queries, prepared statements in client libraries
PostgreSQL 7.3 (2002); later adopted by other DBMSs
Prepared statements cut down repetitive parse and plan time, improve performance for frequently executed queries, and add a layer of SQL-injection protection by separating code from data.
Most DML commands (SELECT, INSERT, UPDATE, DELETE) are supported. Some dialects disallow DDL like CREATE TABLE; consult your database docs.
List parameter types in PREPARE, then supply values positionally in EXECUTE, for example EXECUTE my_stmt(10, 'active');
The database raises an error such as "prepared statement does not exist" because the cached plan has been removed.