Thuta Learning
SQL
AdvancedData & DatabasesBeginner

SQL Security & Parameterized Queries

SQLLesson 2635 min

What you'll walk away with

  • Show with an example how string concatenation turns input into SQL code
  • Write parameterised queries with PostgreSQL's $1, $2 placeholders and recognise other drivers' placeholder styles
  • Handle identifiers such as an ORDER BY column with an allow-list, because they cannot be parameters
  • Escape LIKE wildcards and give the application role only the GRANTs it needs

Explain it simply

SQL injection in plain language

The database reads a whole SQL string as a command. If the text a user typed is glued into that string, the user can rewrite the command; that is SQL injection. A parameterised query sends the SQL code once and the values separately, so whatever a value contains, it stays a value.

Think of a withdrawal slip at a bank counter. The slip has a separate box for the amount, so if someone writes 'and also close every account' in that box, the clerk rejects it as an invalid amount rather than following it as an instruction. A placeholder is that box.

Problem → Why → Solution

The problem: input glued into a login query

The login endpoint takes the email from a form, glues it between two quotes and looks up the user. Tested with normal addresses, it works perfectly. Then someone types x' OR '1'='1 into the email box: the quote closes the string early, the new OR condition is always true, and the whole users table comes back, often with the admin in the first row.

login-unsafe.js
// email comes straight from the request body
const sql = "SELECT id, email FROM users WHERE email = '" + email + "'";
const result = await db.query(sql);

// email = "x' OR '1'='1"  produces:
// SELECT id, email FROM users WHERE email = 'x' OR '1'='1'

Why this happens

After concatenation the database receives one string and can no longer tell which part the developer wrote and which part the user sent. Patching it by escaping quotes tends to leak, for example in numeric contexts with no quotes at all, or through unusual encodings. The root fix is never to mix code and data: send them through two separate channels.

Core concept: sending code and values separately

In a parameterised query, the SQL text marks each value's position with a placeholder and the values are passed separately as an array. On PostgreSQL's wire protocol this happens in steps: Parse (the SQL text is parsed), Bind (the values are attached) and Execute, and a prepared statement can be bound and executed many times with different values. The shape of the statement is fixed before any value arrives, so quotes, semicolons or OR inside a value are never read as code.

DriverPlaceholder style
node-postgres, PGlite, PREPARE$1, $2, ...
psycopg (Python)%s or %(name)s
JDBC PreparedStatement (Java)?
PHP PDO? or :name

psycopg's %s looks like Python's % string formatting but is something else entirely: pass the values as an argument, cursor.execute(sql, (email,)); formatting the string yourself with sql % email is concatenation again. The :email style is not understood by the PostgreSQL server itself either; it is psql variable syntax or the named-parameter style of certain drivers and ORMs.

Parameters are for values only. Table names, column names and keywords such as ASC or DESC are part of the statement's structure, so a placeholder cannot stand in for them. When those must come from the user, make the user choose from an allow-list and keep the SQL fragment under your control. The last line of defence is least privilege: if the app's database role holds only the permissions it needs on the tables and columns it uses, even a successful injection can do limited damage. Parameters, allow-lists and narrow GRANTs work as layers: each one catches what another might miss, so mature codebases use all three.

How a parameterised query travels
  1. Write SQL text with placeholders
  2. Database parses the text alone
  3. Values are bound into the slots
  4. A value can never become code

Identifiers are needed at parse time and cannot wait for the bind step, which is why they need an allow-list.

General pattern

javascript
// 1. SQL text with numbered placeholders (never user data)
const sql = "SELECT columns FROM table_name WHERE column_a = $1 AND column_b = $2";

// 2. values travel separately, in placeholder order
const result = await db.query(sql, [valueA, valueB]);

// 3. identifiers come from a fixed allow-list, never from input
const orderBy = ALLOWED_SORTS.get(userChoice);

Write the SQL text yourself as a literal and let input reach only the values array. When an identifier is needed, use the input as a key and take the SQL fragment from your own map.

Worked example: concatenation versus a parameter

The Node.js script below creates a two-user table in PGlite, which is PostgreSQL compiled to WASM, and sends the same attack input in two ways. Concatenation returns every row; the parameter returns none, because no user has that exact email. node-postgres's client.query(text, values) has the same shape.

injection-demo.mjs
import { PGlite } from "@electric-sql/pglite";

const db = new PGlite();
await db.exec(`
  CREATE TABLE users (id integer PRIMARY KEY, email text NOT NULL);
  INSERT INTO users VALUES (1, 'ada@example.com'), (2, 'lin@example.com');
`);

const typed = "nobody@example.com' OR '1'='1";

// UNSAFE: the input is glued into the SQL text
const glued = "SELECT id, email FROM users WHERE email = '" + typed + "'";
console.log(glued);
const unsafe = await db.query(glued);
console.log("concatenated:", unsafe.rows.length, "rows");

// SAFE: the SQL text and the value travel separately
const sql = "SELECT id, email FROM users WHERE email = $1";
const safe = await db.query(sql, [typed]);
console.log("parameterised:", safe.rows.length, "rows");

const normal = await db.query(sql, ["lin@example.com"]);
console.log(normal.rows);

Code breakdown

  1. The attack stringconst typed = "nobody@example.com' OR '1'='1";

    The first quote closes the developer's string literal, and the rest adds a new condition that is always true.

  2. Concatenationconst glued = "SELECT id, email FROM users WHERE email = '" + typed + "'";

    Look at the printed SQL: the input has changed the logic of the WHERE clause, so both rows match.

  3. Placeholderconst sql = "SELECT id, email FROM users WHERE email = $1";

    $1 marks where the first value goes. The SQL text contains no user data at all.

  4. Values travel separatelyconst safe = await db.query(sql, [typed]);

    The entire attack string is compared as one email value, so nothing matches. Called with a real email, the same query returns the right row.

You should see
SELECT id, email FROM users WHERE email = 'nobody@example.com' OR '1'='1'
concatenated: 2 rows
parameterised: 0 rows
[ { id: 2, email: 'lin@example.com' } ]

Parameters in plain SQL: PREPARE and EXECUTE

PostgreSQL can build a prepared statement in SQL alone, without a driver. PREPARE parses the statement and its parameter types once, and EXECUTE supplies the values. The second EXECUTE below passes the attack string, yet it is compared as one email and returns zero rows. Dynamic SQL inside PL/pgSQL functions follows the same rule: pass values with EXECUTE ... USING and quote identifiers with format('%I', name).

prepare-execute.sql
PREPARE find_user (text) AS
    SELECT id, email FROM users WHERE email = $1;

EXECUTE find_user('lin@example.com');                     -- 1 row
EXECUTE find_user('nobody@example.com'' OR ''1''=''1');   -- 0 rows

Least privilege is set up in SQL like this: create a role for reporting and grant it SELECT on just the id and email columns of users. Reading is_admin as that role fails with permission denied for table users, so even if an injection slipped through, it could not read password hashes or admin flags.

least-privilege.sql
CREATE ROLE report_reader NOLOGIN;
GRANT SELECT (id, email) ON users TO report_reader;

SET ROLE report_reader;
SELECT id, email FROM users ORDER BY id;  -- allowed
-- SELECT is_admin FROM users;            -- permission denied for table users
RESET ROLE;

In real projects

SQL security in real projects

SQL injection has sat in the OWASP Top 10 'Injection' category for years and has been the starting point of many data breaches. ORMs such as the Django ORM, Prisma and SQLAlchemy parameterise ordinary queries automatically, but their raw-SQL escape hatches, such as raw(), $queryRawUnsafe or text() built with an f-string, open the hole again the moment a developer concatenates input.

  • Code-review checklists look for SQL strings built with + or with variables inside template literals, and static-analysis tools such as Semgrep can flag the pattern automatically.
  • Sortable tables and filter UIs often take a column name from the query string, so the backend checks it against an allow-list map and rejects unknown values with a 400 error.
  • Production setups keep one role for the app and a separate table-owner role for migrations, so the app role cannot run DROP TABLE or ALTER TABLE at all.

Common mistakes

Common SQL security mistakes

Trying to pass a column name as a parameter

ORDER BY $1 treats the parameter as a constant string value, not a column, so nothing gets sorted, and developers then fall back to concatenation. The answer is an allow-list map that uses the input only as a key.

Using a plain object as the allow-list

In JavaScript, a plain-object lookup such as SORTABLE[input] returns a function for input like 'constructor', which is truthy. A Map or an Object.hasOwn() check matches only the keys you put there yourself.

Forgetting wildcards inside a LIKE parameter

A parameter blocks injection, but % and _ still act as LIKE wildcards. A user who searches for a single % gets every row and can force slow scans on big tables. Escape \, % and _ before sending the value.

Mini challenge

Mini challenge: a safe user search

Write searchUsers(db, emailContains, sortBy) for an admin page. emailContains is the text to search for, and sortBy must be one of 'id', 'email' or 'newest'. Try it with attack inputs as well and print the results.

  • Send the search text through a $1 parameter into ILIKE
  • Escape \, % and _ so they are matched literally
  • Turn sortBy into an SQL fragment through a Map allow-list and reject unknown values with an error
  • Test with 'max_', "' OR '1'='1" and 'email; DROP TABLE users'
search-users.mjs
import { PGlite } from "@electric-sql/pglite";

const db = new PGlite();
// TODO: create users (id, email, created_on) and insert four rows,
//       including 'max_power@example.com' and 'maxpower@example.com'

// TODO: a Map from the allowed sort names to fixed ORDER BY fragments
const SORTABLE = new Map();

function escapeLike(text) {
  // TODO: put a backslash before every \, % and _
}

async function searchUsers(db, emailContains, sortBy) {
  // TODO: look up sortBy; throw for anything not in the Map
  // TODO: query with ILIKE $1 and the escaped, %-wrapped search text
  // TODO: return just the email strings
}

// TODO: call searchUsers with normal and hostile inputs and print the results

Expected: The 'newest' search lists all four emails, most recent created_on first. 'max_' returns only max_power@example.com (without escaping, maxpower would match too), the attack string returns [], and the sortBy containing DROP TABLE prints a rejected message.

Show hint

text.replace(/[\\%_]/g, (ch) => "\\" + ch) puts a backslash before each of those characters, and PostgreSQL's LIKE uses backslash as its default escape character. Map.get() returns undefined for unknown keys, which makes the allow-list check simple.

Show solution
search-users.mjs
import { PGlite } from "@electric-sql/pglite";

const db = new PGlite();
await db.exec(`
  CREATE TABLE users (
    id integer PRIMARY KEY, email text NOT NULL, created_on date NOT NULL
  );
  INSERT INTO users VALUES
    (1, 'ada@example.com', '2026-01-10'),
    (2, 'lin@example.com', '2026-03-02'),
    (3, 'max_power@example.com', '2026-02-14'),
    (4, 'maxpower@example.com', '2026-02-20');
`);

// Identifiers cannot be parameters, so map user choices to fixed SQL.
const SORTABLE = new Map([
  ["id", "id"],
  ["email", "email"],
  ["newest", "created_on DESC"],
]);

// Make \, % and _ match literally in LIKE / ILIKE.
function escapeLike(text) {
  return text.replace(/[\\%_]/g, (ch) => "\\" + ch);
}

async function searchUsers(db, emailContains, sortBy) {
  const orderBy = SORTABLE.get(sortBy);
  if (!orderBy) throw new Error("cannot sort by " + JSON.stringify(sortBy));
  const sql = "SELECT email FROM users WHERE email ILIKE $1 ORDER BY " + orderBy;
  const result = await db.query(sql, ["%" + escapeLike(emailContains) + "%"]);
  return result.rows.map((row) => row.email);
}

console.log(await searchUsers(db, "example.com", "newest"));
console.log(await searchUsers(db, "max_", "id"));
console.log(await searchUsers(db, "' OR '1'='1", "id"));
try {
  await searchUsers(db, "a", "email; DROP TABLE users");
} catch (err) {
  console.log("rejected:", err.message);
}

Quick quiz 1 / 3

What is wrong with this code? const sql = `SELECT * FROM orders WHERE id = ${req.query.id}`; await db.query(sql);

Quick quiz 2 / 3

Users may choose which column to sort by. Which approach is correct?

Quick quiz 3 / 3

A search box runs db.query("SELECT * FROM products WHERE name LIKE $1", ["%" + q + "%"]). What happens when a user searches for q = "%"?

What to remember

  • Any input glued into an SQL string, whether by +, template literals or % formatting, opens the door to injection.
  • Parameterised queries send the SQL text and the values separately, so a value never becomes code; PostgreSQL uses $1, $2.
  • Table and column names and ASC/DESC cannot be parameters; handle them with an allow-list map.
  • Escape LIKE wildcards, and give the app's database role only the permissions it needs.

SQL Injection Prevention Cheat Sheet — OWASP

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

SQL Security & Parameterized Queries | Thuta Learning