Security

Common SQL Injection Mistakes and How to Fix Them

The coding mistakes that still cause SQL injection: string-built queries, unsafe ORM raw queries, dynamic column names, IN lists and stored procedures, with fixed code.

The Debuggers · Updated · 9 min read

SQL injection happens when text from a user ends up inside a SQL statement as code rather than as data. It has been understood for more than twenty years, and parameterised queries prevent it completely, yet it still appears in the OWASP Top 10 under Injection. The reason is rarely that developers have never heard of it. It is that a handful of specific coding patterns keep slipping past review.

This guide goes through those patterns with the vulnerable code and the fix side by side. The examples use Node.js and Python, but the same mistakes and fixes apply in every language.

How an injection works

Take a login query built with string concatenation:

const sql = "SELECT * FROM users WHERE email = '" + email + "' AND password_hash = '" + hash + "'";

If someone types ' OR '1'='1' -- as the email, the database receives:

SELECT * FROM users WHERE email = '' OR '1'='1' --' AND password_hash = '...'

The quote closes the string, OR '1'='1' is always true, and -- turns the rest into a comment. The query now returns every user. The same trick can read other tables with UNION SELECT, or change data if the driver allows several statements at once.

Mistake 1: building the query as a string

Concatenation, template literals, f-strings and String.format all have the same problem: by the time the database sees the query, it cannot tell which parts you wrote and which parts the user typed.

// Vulnerable
const rows = await db.query(`SELECT * FROM orders WHERE customer_id = ${req.query.id}`);

The fix is a parameterised query. You send the SQL with placeholders and the values separately, and the database driver keeps them apart. The placeholder style depends on the driver.

// node-postgres: $1, $2 ...
const { rows } = await pool.query("SELECT * FROM orders WHERE customer_id = $1", [req.query.id]);

// mysql2: ?
const [rows] = await conn.execute("SELECT * FROM orders WHERE customer_id = ?", [req.query.id]);
# psycopg (PostgreSQL): %s is a placeholder here, not Python string formatting
cur.execute("SELECT * FROM orders WHERE customer_id = %s", (customer_id,))

# Vulnerable: an f-string builds the SQL before the driver sees it
cur.execute(f"SELECT * FROM orders WHERE customer_id = {customer_id}")

The Python case catches people out because both lines look similar. The difference is whether the value is passed as a second argument.

Mistake 2: escaping instead of parameterising

Hand-written escaping, such as replacing ' with '', fails in ways that are easy to miss. It does nothing when the value sits outside quotes:

// "Escaped", but a number has no quotes to escape
const sql = "SELECT * FROM orders WHERE id = " + escape(req.query.id);
// id = "1 OR 1=1" still returns every order

It can also be undone by character set tricks and differences between databases. Parameters avoid the whole question, because the value is never part of the SQL text.

Mistake 3: dynamic column and table names

Parameters can only stand in for values. You cannot write ORDER BY $1 or SELECT * FROM $1. So when a user can choose a sort column or a report table, developers often fall back to concatenation.

The fix is an allowlist that maps what the user sends to names you wrote yourself:

const SORT_COLUMNS = { newest: "created_at", price: "total", name: "customer_name" };
const DIRECTIONS = { asc: "ASC", desc: "DESC" };

const column = SORT_COLUMNS[req.query.sort] ?? "created_at";
const direction = DIRECTIONS[req.query.dir] ?? "DESC";

const { rows } = await pool.query(
  `SELECT * FROM orders WHERE customer_id = $1 ORDER BY ${column} ${direction}`,
  [customerId]
);

The user's input never reaches the SQL. Only one of your fixed strings does.

Mistake 4: ORM raw query escape hatches

ORMs parameterise their normal methods, which creates a false sense of safety around their raw SQL methods.

// Prisma: $queryRawUnsafe takes a plain string, so this is injectable
await prisma.$queryRawUnsafe(`SELECT * FROM users WHERE email = '${email}'`);

// Prisma: $queryRaw with a tagged template turns ${email} into a parameter
await prisma.$queryRaw`SELECT * FROM users WHERE email = ${email}`;

// Sequelize: use replacements or bind, never a template literal
await sequelize.query("SELECT * FROM users WHERE email = :email", { replacements: { email } });

Django's raw() and extra(), Rails' where("name = '#{name}'") and Laravel's DB::raw() have the same trap. Each has a parameterised form: raw("... WHERE name = %s", [name]), where("name = ?", name) and DB::select("... WHERE name = ?", [$name]).

Mistake 5: IN lists built by joining values

A list of IDs is another place where people reach for string building:

// Vulnerable
const sql = `SELECT * FROM products WHERE id IN (${ids.join(",")})`;

In PostgreSQL, pass the array as a single parameter. Elsewhere, generate one placeholder per item:

// PostgreSQL
await pool.query("SELECT * FROM products WHERE id = ANY($1)", [ids]);

// MySQL and others
const placeholders = ids.map(() => "?").join(",");
await conn.execute(`SELECT * FROM products WHERE id IN (${placeholders})`, ids);

The second version is safe because the string you build contains only question marks and commas.

Mistake 6: dynamic SQL inside stored procedures

Moving a query into a stored procedure does not help if the procedure builds SQL from its arguments:

-- SQL Server: vulnerable
EXEC('SELECT * FROM orders WHERE status = ''' + @status + '''');

-- Safe: sp_executesql with a parameter
EXEC sp_executesql N'SELECT * FROM orders WHERE status = @s', N'@s nvarchar(20)', @s = @status;

PostgreSQL's EXECUTE ... USING and MySQL's PREPARE ... EXECUTE ... USING are the equivalents.

Mistake 7: trusting data that is already in your database

Second-order injection happens when a value is stored safely, then later read back and concatenated into another query, for example a username used in a reporting job. The value came from your own database, so it feels trusted, but it was typed by a user. Treat every value as data, wherever it came from, and the rule stays simple: parameters everywhere.

Mistake 8: no second line of defence

Even with parameters everywhere, limit the damage of a mistake:

  • Connect as a database user that can only do what the application needs. A user that cannot DROP tables or read the users table from a reporting service limits any injection.
  • Do not show database errors to users. Messages such as "syntax error near ''" tell an attacker their quote reached the SQL. Log the detail and show a generic message.
  • Turn off multi-statement queries in the driver unless you need them, so ; DROP TABLE cannot run.

Finding these mistakes in your code

Search your codebase for the patterns above: SQL keywords next to +, ${, f", .format( or % formatting, and every use of raw query methods. Review each one. For a running application, a scanner such as sqlmap can test your own staging environment, but only run it against systems you own or are authorised to test.

When you are reading a long query from logs or an ORM to check how it was built, the SQL Formatter lays it out one clause per line, which makes a concatenated value much easier to spot.

Frequently Asked Questions

Does escaping user input prevent SQL injection?

Not reliably. Escaping depends on getting the character set, quoting context and database exactly right every time, and it does nothing for values placed outside quotes, such as numbers. Parameterised queries keep data and SQL separate, so there is nothing to escape.

Are ORMs safe from SQL injection?

Their normal query methods are, because they use parameters. Every ORM also has a raw SQL method, and those are only safe when you pass values as parameters rather than building the string yourself.

Do prepared statements make queries slower?

No, not in any way you would notice. Some databases can even reuse the query plan for a prepared statement. The safety benefit far outweighs any difference.

Can client-side validation stop SQL injection?

No. Anyone can send requests straight to your API without using your front end, so validation in the browser is only a convenience for honest users. The protection has to be in the server code that talks to the database.

Want help with this in a real project?

Our team builds web and mobile software, from planning and design to launch and support.