Sobes.tech
Senior

Why are placeholders ($1, $2) used in SQL queries?

sobes.tech AI

Answer from AI

Placeholders like $1, $2 in SQL queries are used for parameterizing queries. This allows:

  • Prevent SQL injection: values are inserted separately from the query text, preventing malicious code injection.
  • Improve readability and maintainability of code: parameters are explicitly marked, making the query structure easier to understand.
  • Optimize execution: the database can cache the query plan and simply substitute different parameters.

Example of usage in C++ with the libpq library (PostgreSQL):

const char* query = "SELECT * FROM users WHERE id = $1 AND status = $2";
int userId = 42;
const char* status = "active";

// Prepare and execute the query with parameters userId and status
// Parameters are passed separately, not inserted directly into the string

Thus, placeholders ensure security and efficiency when working with a database.