Skip to content
Back to all posts
Technology

Preventing SQL Injection: Parameterized Queries and Safe Database Access

Learn how SQL injection works and how to prevent it using parameterized queries, least-privilege database accounts, and input validation.

3 min read

TechSilo

Technology writer & developer

SQL injection happens when an application mixes untrusted input into a SQL command so that the database interprets the input as executable query syntax. The primary defense is simple: separate SQL code from query values.

The vulnerable pattern

Imagine an authentication lookup in a Node.js application:

javascript
const email = req.body.email;
const sql = "SELECT id FROM users WHERE email = '" + email + "'";
const result = await db.query(sql);

This creates a query string by concatenating input. If the input contains SQL metacharacters, the intended query structure can change. Escaping input by hand is fragile and database-specific.

Fix: parameterize values

For PostgreSQL using the pg client:

javascript
const email = req.body.email;

if (typeof email !== 'string' || email.length > 254) {
  return res.status(400).json({ error: 'Invalid email' });
}

const result = await pool.query(
  'SELECT id FROM users WHERE email = $1',
  [email]
);

The SQL structure remains fixed. The database receives the value separately from the SQL code. This approach also works for numbers, search terms, and other values that would otherwise be interpolated into queries.

For MySQL using a compatible driver, placeholders often look like ? rather than $1. Follow your actual database driver's documentation.

A complete safe update example

javascript
async function updateDisplayName(pool, userId, displayName) {
  if (!Number.isInteger(userId) || typeof displayName !== 'string') {
    throw new TypeError('Invalid update input');
  }
  if (displayName.length < 1 || displayName.length > 80) {
    throw new RangeError('Display name must be 1–80 characters');
  }
  const result = await pool.query(
    'UPDATE users SET display_name = $1 WHERE id = $2 RETURNING id',
    [displayName, userId]
  );
  return result.rows[0] ?? null;
}

Parameterization prevents query values from becoming SQL instructions. Input validation still matters for business rules and resource limits, but validation does not replace parameterization.

What about dynamic table names?

Most drivers cannot parameterize SQL identifiers such as table names, column names, and sort directions. When those truly need to vary, choose from a fixed allowlist:

javascript
const orderColumns = { newest: 'created_at', name: 'display_name' };
const orderColumn = orderColumns[req.query.sort] ?? 'created_at';
const rows = await pool.query(
  'SELECT id, display_name FROM users ORDER BY ' + orderColumn + ' DESC LIMIT $1',
  [20]
);

The interpolated column comes exclusively from trusted code, never directly from the request.

Defense in depth

- Give the application a database account with only the permissions it needs.

- Avoid connecting as a database administrator from the web server.

- Keep database drivers and frameworks patched.

- Don't expose raw database errors or connection strings to clients.

- Use tests with unusual characters, empty values, and unexpected types.

- Review raw SQL queries even when most of the application uses an ORM.

Prepared statements and ORM parameter binding are effective only when used correctly. An ORM's raw-query or unsafe-execution feature can still introduce SQL injection.

Takeaway

Never build SQL syntax from untrusted string fragments. Use parameterized values, restrict any necessary dynamic identifiers to a fixed mapping, and apply authorization checks on the records you retrieve or change. Pair these safeguards with TechSilo's [Input Validation Strategies](/blog/practical-security-guide-to-input-validation-strategies-mr79jrip).

Want to put this into practice?

Explore TechSilo's free developer tools for practical utilities you can use directly in your browser.

Related blog posts