Question Details

No question body available.

Tags

sql postgresql

Answers (4)

March 30, 2026 Score: 4 Rep: 28,324 Quality: Medium Completeness: 40%

Use parameters - all rdbms/frameworks support them - don't build up strings.

That said, this topic has been covered in great details... it shouldn't be hard to find the information you need already available.

https://cheatsheetseries.owasp.org/cheatsheets/SQLInjectionPreventionCheatSheet.html

https://learn.microsoft.com/en-us/sql/relational-databases/security/sql-injection?view=sql-server-ver17

How to prevent SQL Injection in this code?

...

March 30, 2026 Score: 1 Rep: 28,324 Quality: Low Completeness: 10%

Or alternatively don't allow that level of dynamic query building... its a bit of an anti-pattern with SQL. In most circumstances its better to have a bunch of static queries/procs targeting different tables instead of a generic one.

March 30, 2026 Score: 1 Rep: 568,362 Quality: Low Completeness: 10%

I agree with you for most situations, but there are always exceptions. Either way, yes, the untrusted input should only be used to choose which query to run, instead of becoming part of the query itself.

March 30, 2026 Score: 0 Rep: 568,362 Quality: Medium Completeness: 60%

As the other answer wrote, use query parameters.

However...

Query parameters only work in place of SQL values. For instance in the case of LIKE '%{customer_name}%', the string value that is the right-side operand of the expression is a value to SQL.

Parameters always behave as values. Thus you cannot use a query parameter for a table name, or a column name, or a full expression in WHERE {condition}, etc. Parameters are not simply string substitution. That would be no better than interpolating variables as you're currently doing. What makes parameters a defense against SQL injection is the fact that they are always treated as a constant value.

So what do you do for the other cases, like identifiers, expressions, or SQL keywords?

Allowlisting — that is, a fixed string that you specify in your code. If you use only these predetermined strings, not untrusted content, to be copied into your SQL query, then you can make it safe.