What is the question mark's significance in MySQL at "WHERE column = ?"?

Prepared statments use the '?' in MySQL to allow for binding params to the statement. Highly regarded as more secure against SQL injections if used properly. This also allows for quicker SQL queries as the request only has to be compiled once and can be reused.


The question mark represents a parameter that will later be replaced. Using parameterized queries is more secure than embedding the parameters right into the query.

SQL Server calls this parameterize queries, and Oracle calls it bind variables.

The usage varies with the language that you are executing the query from.

Here is an example of how it is used from PHP.

assuming that $mysqli is a database connection and people is a table with 4 columns.

$stmt = $mysqli->prepare("INSERT INTO People VALUES (?, ?, ?, ?)");

$stmt->bind_param('sssd', $firstName, $lastName, $email, $age);

The 'sssd' is a flag identifying the rest of the parameters, where s represents string and d represents digits.


? has no special meaning in MySQL WHERE = statements, only in prepared statements

The most common case where we see it is due to special meaning given to ? by several web frameworks like PHP and Rails.

? is just a syntax error at:

CREATE TABLE t (s CHAR(1));
SELECT * FROM t WHERE s = ?;

because it is unquoted, and in:

INSERT INTO t VALUES ('a');
INSERT INTO t VALUES ("?");
SELECT * FROM t WHERE s = '?';

it returns:

s
?

thus apparently without special meaning.

MySQL 5.0 prepared statements

MySQL 5.0 added the prepared statement feature which has similar semantics to the question mark in web frameworks.

Example from the docs:

PREPARE stmt1 FROM 'SELECT SQRT(POW(?,2) + POW(?,2)) AS hypotenuse';
SET @a = 3;
SET @b = 4;
EXECUTE stmt1 USING @a, @b;

Output:

hypotenuse
5

These also escape special characters as expected:

PREPARE stmt1 FROM 'SELECT ? AS s';
SET @a = "'";
EXECUTE stmt1 USING @a;

Output:

s
'

Rails example

In Rails for example, the question mark is replaced by an argument given by a variable of the library's programming language (Ruby), e.g.:

Table.where("column = ?", "value")

and it automatically quotes arguments to avoid bugs and SQL injection, generating a statement like:

SELECT * FROM Table WHERE column = 'value';

The quoting would save us in case of something like:

Table.where("column = ?", "; INJECTION")

Tags:

Mysql

Syntax