Skip to Content
Mengty Learns
Security

SQL Injection & Parameterized Queries

How SQL injection happens, why parameterized queries separate code from data, ORM raw-query escape hatches, and least-privilege database users.

explanationbeginnerTested with asvs 5.0.0 (V1), owasp_top_10 2025 (A05)Updated Nov 26, 2026

TL;DR

SQL injection (SQLi) happens when untrusted input is concatenated into a SQL string, letting data rewrite the query's logic. Always use parameterized queries (prepared statements), use strict allowlists for dynamic table/column identifiers, avoid unsafe ORM raw-query escape hatches, and run the app with a least-privilege DB role.

Intent

TL;DR

Understand why string-built SQL lets attackers rewrite query ASTs, how bound parameters eliminate that class of bug, and where ORMs still have sharp edges.

Problem

Concatenating user input into a SQL string mixes code and data in the same channel. Even with an ORM, developers reach for raw SQL for complex reports or dynamic sorting (ORDER BY ${sortCol})—and one unvalidated template literal reopens the entire database to extraction or tampering.

Parameterized queries send the SQL template and bound values in separate channels.

Solution

Keep SQL structure and untrusted data strictly separated:

  1. Parameterized queries (prepared statements): Use $1 / ? placeholders (or ORM tagged templates like Prisma $queryRaw\...``). The DB parser compiles the query plan before seeing the parameter bytes.
  2. Allowlist identifiers: SQL parameters only work for values, not column names, table names, or ASC/DESC. Map those through a fixed Record<string, string> allowlist.
  3. Least-privilege DB credentials: The web app's DB role should never be SUPERUSER or db_owner—restrict it to the required schema and DML operations.

Real-world analogy

▶ Flow: watch it work

SQL Injection: String Concat vs Parameterized Query

Overview of SQL Injection: String Concat vs Parameterized Query. 4 steps.
Overview4 steps in this flow

Press Start or tap any step dot to trace the path.

▸All steps (4)

Code

Compare unsafe string interpolation and dynamic ORDER BY against parameterized queries and an explicit allowlist:

// UNSAFE: string interpolation in raw SQL and unvalidated ORDER BY column
const unsafeUsers = await db.query(
  `SELECT id, email FROM users WHERE email = '${email}' ORDER BY ${sortBy}`,
);

// SAFE: parameterized value ($1) + strict allowlist for column identifier (ASVS V1)
const ALLOWED_SORT = {
  created_at: 'created_at',
  email: 'email',
} as const;

const safeSort = ALLOWED_SORT[sortBy as keyof typeof ALLOWED_SORT] ?? 'created_at';
const safeUsers = await db.query(
  `SELECT id, email FROM users WHERE email = $1 ORDER BY ${safeSort} ASC`,
  [email],
);

When to use / when to avoid

When to use
  • Use parameterized queries ($1, ?) or ORM query builders for every SQL value.
  • Use a strict server-side allowlist map whenever column names, table names, or sort directions are dynamic.
  • Run the application with a dedicated DB role that has only the permissions it needs.
When to avoid
  • Never try to "fix" SQLi by stripping quotes or keywords with regexes—use prepared statements.
  • Never pass interpolated strings into ORM escape hatches ($queryRawUnsafe, sequelize.literal, raw()).

How to implement

Ban raw string concatenation

Enable lint rules or SAST checks flagging template literals inside db.query or $queryRawUnsafe.

Allowlist dynamic identifiers

Map user-supplied sort or filter keys through a const object or Map before building ORDER BY.

Restrict DB role privileges

Separate migration credentials (DDL) from runtime app credentials (DML only).

Pros / Cons

Pros
  • Parameterized queries eliminate SQL injection on values completely and let the DB cache query plans.
  • Least-privilege DB roles limit blast radius if another vulnerability occurs.
Cons
  • Identifiers (table/column names) cannot be bound as parameters and still require allowlists.
  • Legacy stored procedures that concatenate dynamic SQL internally are still vulnerable.

Relations

Check yourself

Check Yourself

1. You use an ORM for normal CRUD, but write one reporting endpoint with db.$queryRawUnsafe(`SELECT ... ORDER BY ${req.query.sort}`). Is it safe?

2. Why can't you pass a column name as a $1 bound parameter in SELECT * FROM users ORDER BY $1?

Sources