読み物Application Security

Level: Intermediate

SQL Injection and Secure Database Queries Explained

How SQL injection happens, why escaping isn't the fix, and how parameterized queries, safe ORMs, allowlists, and least-privilege database roles prevent it, with tests.

Edeeson Opina9 min read

An Intermediate lesson card: lesson 7 of the Security & Privacy series, SQL Injection and Secure Database Queries Explained, with the Miso fox sitting.

What you’ll learn

  • Explain how SQL injection changes a query's meaning
  • Write parameterized queries with node-postgres and Prisma
  • Handle dynamic column names and sort orders with allowlists
  • Limit damage with least-privilege database roles
  • Write a test that proves the fix
On this page
  1. Before you start
  2. How SQL injection happens
  3. Impact
  4. Why escaping isn't the fix
  5. Parameterized queries
  6. Why parameterized queries work
  7. Using an ORM safely
  8. What parameters can't cover
  9. LIKE patterns
  10. Dynamic SQL inside the database
  11. Limit the damage: least privilege
  12. Verifying the fix with a test
  13. Common mistakes and troubleshooting
  14. Practical exercise: find and fix
  15. Key takeaways
  16. References
  17. What's next

SQL injection has been understood for more than twenty-five years, and it still appears in new code every week. It happens when input from a user becomes part of the text of a database query, so the user can change what the query does. The result can be a leaked customer table, a bypassed login, or deleted data. This lesson shows how the attack works in a local example, why escaping strings isn't a reliable fix, how parameterized queries solve the problem, how to handle the cases parameters can't cover, and how to write a test that proves your fix.

Before you start

You should know basic SQL (SELECT, WHERE, INSERT) and have read OWASP Top 10 Explained, where injection is category A05. The examples use PostgreSQL with the pg (node-postgres) driver and Prisma in TypeScript. Run them only against a local database you created for practice.

How SQL injection happens

Here's a search endpoint built the wrong way. Don't use this code; it exists to show the vulnerability.

insecure-search.tsTypeScript
// INSECURE TEACHING EXAMPLE: user input is pasted into the SQL text.
app.get("/api/products", async (req, res) => {
  const name = String(req.query.name ?? "");
  const sql = `SELECT id, name, price FROM products WHERE name = '${name}' AND is_public = true`;
  const { rows } = await pool.query(sql);
  res.json(rows);
});

With a normal input such as Matcha, the database receives:

SQL
SELECT id, name, price FROM products WHERE name = 'Matcha' AND is_public = true

Now imagine the input is x' OR '1'='1' --. The query becomes:

SQL
SELECT id, name, price FROM products WHERE name = 'x' OR '1'='1' --' AND is_public = true

The quote closes the string early, OR '1'='1' is always true, and -- turns the rest of the line into a comment. The query now returns every product, including private ones. With a UNION SELECT, an attacker could read other tables entirely; in a login query, the same trick can skip the password check. The database isn't misbehaving: it's executing exactly the SQL it was given. The bug is that the application let input rewrite that SQL.

Impact

Depending on the query and the database account's permissions, SQL injection can expose every row the account can read, modify or delete data, bypass authentication, and in some configurations reach the file system or run commands on the database server. It's frequently the root cause of large data breaches.

Why escaping isn't the fix

A natural first idea is to escape quotes in the input. It's fragile: escaping rules depend on the database, its settings, the character encoding, and the context (a string, a number, an identifier, a LIKE pattern). A numeric context needs no quote at all to be exploited:

insecure-numeric.tsTypeScript
// INSECURE TEACHING EXAMPLE: no quotes to escape, still injectable (try "1 OR 1=1").
const sql = `SELECT * FROM orders WHERE id = ${req.query.id}`;

Every place that builds SQL with string concatenation is one forgotten escape away from a breach. The reliable fix changes the structure instead.

Parameterized queries

A parameterized query (also called a prepared statement or bind parameters) sends the SQL text and the values to the database separately. The SQL contains placeholders; the values are passed alongside. The database parses the SQL first, then binds the values as pure data. No value, whatever characters it contains, can change the query's structure.

With node-postgres, placeholders are $1, $2, and so on:

search.tsTypeScript
app.get("/api/products", async (req, res) => {
  const name = String(req.query.name ?? "");
  const { rows } = await pool.query(
    "SELECT id, name, price FROM products WHERE name = $1 AND is_public = true",
    [name],
  );
  res.json(rows);
});

Now the input x' OR '1'='1' -- is compared, as a literal string, against product names. No product has that name, so the result is empty.

Why parameterized queries work

The protection comes from where the boundary sits. With concatenation, your code and the user's input are merged into one string before the database ever sees it, and the database's parser can't tell which characters came from whom. With parameters, the query's structure is fixed when it's parsed, and the input arrives through a separate channel as a typed value. That's why parameters protect strings, numbers, and dates equally, and why you don't need to escape anything yourself.

Using an ORM safely

ORMs and query builders such as Prisma, Drizzle, Knex, and Sequelize parameterize queries for you when you use their normal APIs:

prisma-search.tsTypeScript
const products = await prisma.product.findMany({
  where: { name: req.query.name as string, isPublic: true },
  select: { id: true, name: true, price: true },
});

ORMs also offer raw SQL for queries their API can't express, and that's where injection returns. In Prisma, $queryRaw used as a tagged template turns each ${} into a parameter, while $queryRawUnsafe takes a plain string and does not:

prisma-raw.tsTypeScript
import { Prisma } from "@prisma/client";

// Safe: each ${} is sent as a bind parameter, not as SQL text.
const rows = await prisma.$queryRaw`SELECT id, name FROM products WHERE name = ${name} AND is_public = true`;

// Safe: a list of values for IN (...), still parameterized.
const byIds = await prisma.$queryRaw`SELECT id, name FROM products WHERE id IN (${Prisma.join(ids)})`;
insecure-prisma.tsTypeScript
// INSECURE TEACHING EXAMPLE: a string built first, then run unsafely.
const rows = await prisma.$queryRawUnsafe(`SELECT id, name FROM products WHERE name = '${name}'`);

Search your codebase for queryRawUnsafe, executeRawUnsafe, .raw(, and template literals passed to query( to find these risky spots.

What parameters can't cover

Placeholders stand for values. They can't stand for table names, column names, sort directions, or SQL keywords. When those must vary, such as a "sort by" option, use an allowlist: map the user's choice to a fixed piece of SQL you wrote.

sorting.tsTypeScript
const SORT_COLUMNS = { name: "name", price: "price", newest: "created_at" } as const;
type SortKey = keyof typeof SORT_COLUMNS;

export function orderBy(sort: unknown, direction: unknown): string {
  // Object.hasOwn, not a plain lookup: SORT_COLUMNS["constructor"] would return an inherited function.
  const column = typeof sort === "string" && Object.hasOwn(SORT_COLUMNS, sort) ? SORT_COLUMNS[sort as SortKey] : SORT_COLUMNS.newest;
  const dir = direction === "asc" ? "ASC" : "DESC";
  return `ORDER BY ${column} ${dir}`; // only strings from this file reach the SQL
}

const { rows } = await pool.query(
  `SELECT id, name, price FROM products WHERE is_public = true ${orderBy(req.query.sort, req.query.dir)} LIMIT $1`,
  [20],
);

The user's input never reaches the SQL text; it only selects one of your own strings. Anything unexpected falls back to a safe default. Check membership with Object.hasOwn (or use a Map): a plain object lookup also finds inherited keys such as constructor, and an allowlist that can return something you didn't write isn't an allowlist.

LIKE patterns

Parameterizing a LIKE search prevents injection, but % and _ in the input still act as wildcards. If that matters (for example, for performance or to avoid matching everything), escape them in the value:

like.tsTypeScript
const escapeLike = (text: string) => text.replace(/[\\%_]/g, (char) => `\\${char}`);
await pool.query("SELECT id, name FROM products WHERE name ILIKE $1 ESCAPE '\\'", [`%${escapeLike(term)}%`]);

Dynamic SQL inside the database

The same rule applies to stored procedures. In PL/pgSQL, build dynamic SQL with format() using %I for identifiers and pass values with USING, never by concatenation:

SQL
EXECUTE format('SELECT count(*) FROM %I WHERE owner_id = $1', table_name) INTO total USING owner;

Limit the damage: least privilege

Defense in depth assumes a bug will slip through someday. Make sure the application's database account can do only what the application needs:

SQL
-- A role for the web application: no superuser, no schema changes, no access to other databases.
CREATE ROLE shop_app LOGIN;
GRANT CONNECT ON DATABASE shop TO shop_app;
GRANT USAGE ON SCHEMA public TO shop_app;
GRANT SELECT, INSERT, UPDATE, DELETE ON products, orders, order_items TO shop_app;
-- Run migrations with a separate, more privileged role, never the app's.

With this setup, even a successful injection can't drop tables, read tables the role wasn't granted, or create new functions. Also set a statement timeout and a row limit on queries that don't need more.

Verifying the fix with a test

A security fix should come with a test that fails on the vulnerable version and passes on the fixed one. This Vitest test runs against a disposable local test database:

products.test.tsTypeScript
import { describe, expect, it } from "vitest";
import { searchProducts } from "./products";

describe("product search", () => {
  it("treats SQL syntax in the input as plain text", async () => {
    // The test database is seeded with one public and one private product.
    const results = await searchProducts("x' OR '1'='1' --");
    expect(results).toEqual([]);
  });

  it("never returns private products, whatever the input", async () => {
    for (const input of ["%", "' OR is_public = false --", "Private Blend"]) {
      const results = await searchProducts(input);
      expect(results.every((product) => product.isPublic)).toBe(true);
    }
  });
});

Also add a lint rule or a CI search that fails when new code uses unsafe raw query functions, so the pattern can't return quietly.

Common mistakes and troubleshooting

  • Parameterizing some inputs but not others. Every value from outside the query, including ones from your own database (second-order injection), should be a parameter.
  • Building IN (...) lists by joining strings. Use the driver's array support (= ANY($1) in PostgreSQL) or Prisma.join.
  • Trusting "internal" input. Values from headers, cookies, other services, and admin forms are just as untrusted.
  • Using the migration account in the app. A superuser connection turns a small bug into a total compromise.
  • Showing database errors to users. Error text helps attackers refine their input. Log it; show a generic message.

If a parameterized query fails with an error like "could not determine data type of parameter," add an explicit cast in the SQL (for example, $1::int) rather than switching to concatenation.

Practical exercise: find and fix

On a local practice project:

  1. Write the insecure search endpoint above, seed a public and a private product, and confirm the injected input returns both.
  2. Rewrite it with a parameterized query and confirm the same input returns nothing.
  3. Add a "sort by" option using an allowlist.
  4. Create a least-privilege role and run the application with it.
  5. Write the two tests above and check that they fail on the old code and pass on the new.

Key takeaways

  • SQL injection happens when input becomes part of the SQL text.
  • Parameterized queries fix it structurally by sending SQL and values separately; escaping is fragile.
  • ORMs are safe through their normal APIs; be careful with their raw and "unsafe" functions.
  • Use allowlists for identifiers and sort orders, which parameters can't cover.
  • Run the application with a least-privilege database role, and prove the fix with tests.

References

What's next

Injection into the database has a browser-side sibling. Cross-Site Scripting (XSS), CSRF, and Browser Defenses shows how untrusted input becomes script in a page, how other sites can trigger actions on a user's behalf, and the browser features that stop both.

See every lesson in Security & Privacy: Building Secure Applications