SQL · Module 14 · Lesson 21 min read

SQL Injection & Parameterized Queries

What is SQL injection?

When user input is glued into a SQL string, an attacker can type SQL that changes the meaning of your query.

ini
// ❌ NEVER do this
const sql = "SELECT * FROM users WHERE email = '" + email + "'";

If someone types ' OR '1'='1 as their email:

SQL
SELECT * FROM users WHERE email = '' OR '1'='1'   -- returns EVERY user

Worse inputs can read other tables (UNION SELECT …), modify data, or DROP TABLE.

The fix: parameterized queries (prepared statements) ✅

Send the SQL and the values separately. The database treats values as data, never as code.

csharp
// Node (pg)
await client.query('SELECT * FROM users WHERE email = $1', [email]);
  • Python psycopg: cur.execute("… WHERE email = %s", (email,))
  • Supabase JS: .eq('email', email) builds parameterized requests for you
  • ORMs (Prisma, Drizzle, Sequelize) parameterize automatically — except raw-query escape hatches like $queryRawUnsafe

Things parameters can't do

Parameters work for values only — not table names, column names or keywords like ASC/DESC.

  • Use an allow-list: const sort = ['amount', 'spent_on'].includes(input) ? input : 'spent_on'
  • In PL/pgSQL dynamic SQL use format('%I', name) (identifier) and format('%L', value) (literal), or EXECUTE … USING

Defence in depth

  1. Parameterized queries everywhere (non-negotiable)
  2. Least-privilege database roles (the app can't DROP tables)
  3. Row Level Security so even a leaked query only sees the user's own rows
  4. Validate input types and lengths
  5. Don't show raw database errors to users
  6. Never build SQL from user input inside database functions with EXECUTE 'text' || input

Second-order injection

Data saved safely can still be dangerous if it's later concatenated into another query. The rule is simple: never concatenate, anywhere.

Example

SQL
-- Simulating what an app would send.

-- ❌ VULNERABLE: string concatenation inside dynamic SQL
CREATE FUNCTION find_user_unsafe(p_email TEXT) RETURNS SETOF users
LANGUAGE plpgsql AS $$
BEGIN
  RETURN QUERY EXECUTE 'SELECT * FROM users WHERE email = ''' || p_email || '''';
END $$;

SELECT name FROM find_user_unsafe('asha@example.com');          -- Asha Sharma (normal)
SELECT name FROM find_user_unsafe($$' OR '1'='1$$);            -- 😱 ALL 6 users leaked!

-- ✅ SAFE: parameters with EXECUTE … USING
CREATE FUNCTION find_user_safe(p_email TEXT) RETURNS SETOF users
LANGUAGE plpgsql AS $$
BEGIN
  RETURN QUERY EXECUTE 'SELECT * FROM users WHERE email = $1' USING p_email;
END $$;

SELECT name FROM find_user_safe('asha@example.com');            -- Asha Sharma
SELECT name FROM find_user_safe($$' OR '1'='1$$);              -- 0 rows ✅ (treated as text)

-- ✅ Even simpler: plain SQL functions are always parameterized
CREATE FUNCTION find_user(p_email TEXT) RETURNS SETOF users
LANGUAGE sql STABLE AS $$ SELECT * FROM users WHERE email = p_email $$;

-- ✅ Prepared statements (what drivers do under the hood)
PREPARE get_expenses(INT, NUMERIC) AS
  SELECT title, amount FROM expenses WHERE user_id = $1 AND amount > $2;
EXECUTE get_expenses(2, 3000);
DEALLOCATE get_expenses;

-- ✅ Dynamic identifiers: allow-list + format('%I')
CREATE FUNCTION sorted_expenses(p_sort TEXT) RETURNS SETOF expenses
LANGUAGE plpgsql AS $$
BEGIN
  IF p_sort NOT IN ('amount', 'spent_on', 'title') THEN
    RAISE EXCEPTION 'Invalid sort column: %', p_sort;
  END IF;
  RETURN QUERY EXECUTE format('SELECT * FROM expenses ORDER BY %I DESC LIMIT 3', p_sort);
END $$;
SELECT title, amount FROM sorted_expenses('amount');

-- In application code (Node.js + pg):
--   ❌ client.query(`SELECT * FROM users WHERE email = '${email}'`)
--   ✅ client.query('SELECT * FROM users WHERE email = $1', [email])