ProgrammingFullstack Developer

Tell us about parameterized queries and dynamic SQL. When to use each approach, what risks are associated with dynamic SQL and how to avoid them? Provide examples.

Pass interviews with Hintsage AI assistant

Answer.

Parameterized queries allow you to pass values into queries through special parameters rather than directly substituting variables. This enhances security and protects against SQL injection, as well as speeds up the execution of repeated queries through plan caching.

Dynamic SQL allows you to build and execute queries on the fly (e.g., using EXEC sp_executesql in MS SQL or PREPARE/EXECUTE in PostgreSQL). You must be very careful: directly substituting values into the query text can lead to SQL injections, syntax errors, and poor performance.

Example of a parameterized query (in Python with the psycopg2 library):

cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))

Example of dynamic SQL in PostgreSQL:

EXECUTE format('SELECT * FROM %I WHERE value = %L', tablename, value);

Trick question.

Question: Why is simply escaping quotes ('), as some old applications do, insufficient to protect against SQL injections?

Answer:

Escaping quotes will not protect against all types of injections, especially if an attacker inserts a SQL structure (e.g., "; DROP TABLE users;"). Moreover, it does not cover all the nuances of different data types and does not protect against bypassing filters through encoding or special characters. Always use parameterized queries.


History

In one payroll accounting system, dynamic SQL generated reports. Due to lack of parameterization support in an old framework, string concatenation was done manually. One user accidentally (or not) passed a fragment of SQL into the "surname" field, allowing access to others' salaries.

History

A small online store used dynamic SQL to filter products without proper validation. When attempting to specify a non-standard value, the user triggered an SQL parse error, temporarily "taking down" the output of all products.

History

In a CRM, the letter "O'Connor" caused an error in the application that built SQL queries through simple string concatenation. Due to an unescaped single quote, no card with that surname could be saved, which was only discovered a year later.