R
Rishtaara
SQL: Zero to Data Analyst
Lesson 22 of 30Article16 min

SQL Injection, Parameters & Prepared Statements

SQL injection happens when untrusted text is pasted into SQL strings. Attackers can read or delete data by typing clever input.

SQL Injection — when user input breaks your query

SQL injection happens when untrusted text is pasted into SQL strings. Attackers can read or delete data by typing clever input.

Never build queries by concatenating raw user input: "SELECT * FROM students WHERE name = '" + input + "'" is dangerous.

Real-life example: Injection is a forged note slipped into the principal's inbox — 'Also show me every password' hidden in a normal request.

Unsafe vs safe pattern (concept)
-- UNSAFE (never do this in app code)
-- query = "SELECT * FROM students WHERE full_name = '" + userInput + "'"
-- If userInput is: ' OR '1'='1
-- Whole table is exposed!

-- SAFE: use parameters / prepared statements (app sends values separately)

Parameters — placeholders for values

Parameterized queries use ? or @name placeholders. The database treats user values as data, not as SQL commands.

Real-life example: Parameters are numbered slots on a form — you write the answer in box 1, you cannot rewrite the form itself.

Placeholder style examples
-- JDBC / many drivers
-- SELECT * FROM students WHERE city = ?

-- SQL Server
-- SELECT * FROM students WHERE city = @city

-- PostgreSQL
-- SELECT * FROM students WHERE city = $1

Prepared Statements — compile once, run many

Prepared statements parse SQL once, then bind new values for each run. They stop injection and can improve performance.

Real-life example: Prepared statements are a stamp with blank fields — same template, different name each time, shape never changes.

In web apps (Node, Python, Java), use your driver's prepared statement API — do not hand-build SQL strings from form data.
Conceptual prepared statement flow
-- Step 1: prepare
PREPARE student_by_city (TEXT) AS
  SELECT student_id, full_name FROM students WHERE city = $1;

-- Step 2: execute with different cities
EXECUTE student_by_city('Delhi');
EXECUTE student_by_city('Mumbai');