SQL Injection
SQL injection is a security flaw where text typed by a user is pasted into a SQL statement and ends up being run as part of the SQL itself. It happens when a program builds a query by joining strings, such as "... WHERE last_name = '" + name + "'". If the "name" contains a quote, it can close the string early and add new SQL. For more than twenty years, injection has been one of the most common and most damaging web vulnerabilities, and it's on the OWASP Top 10 list of critical risks. In this lesson, we will see exactly how input turns into code, what an attacker can reach, why escaping and blocklists fail, and the one fix that works: parameters.
In One Minute
- Building SQL by joining strings with user input lets the input change the query's meaning.
- The classic input
x' OR '1'='1turns "find this name" into "find everyone". - Injection can expose, change or delete data, and bypass logins.
- The fix is parameters (prepared statements): the SQL and the values are sent separately, so values can never become code.
- Escaping and blocklists are not reliable fixes; least privilege limits the damage if something slips through.
How Input Becomes Code
A program wants to find students by last name. The unsafe way builds the SQL as text:
String sql = "SELECT student_id, first_name FROM students"
+ " WHERE last_name = '" + lastName + "'"
+ " ORDER BY student_id";With a normal name, the result is a normal query. But a user can type anything. Here is the text the program builds when someone types x' OR '1'='1:
SELECT 'SELECT student_id, first_name FROM students'
|| ' WHERE last_name = ''' || 'x'' OR ''1''=''1' || ''''
|| ' ORDER BY student_id' AS query_the_program_builds; query_the_program_builds
--------------------------------------------------------------------------------------------------
SELECT student_id, first_name FROM students WHERE last_name = 'x' OR '1'='1' ORDER BY student_id
(1 row)Explanation: The typed quote after x closes the string the programmer opened. Everything after it, OR '1'='1', is now SQL, not data. (Inside a SQL string literal, '' stands for one quote character, which is why the example doubles them.) Running that built query:
SELECT student_id, first_name
FROM students
WHERE last_name = 'x' OR '1'='1'
ORDER BY student_id; student_id | first_name
------------+------------
101 | Srihitha
102 | Advitha
103 | Navika
(3 rows)Explanation: '1'='1' is always true, so the WHERE matches every row. A search that should find nobody named "x" returns every student. On a login form, the same trick can make "check this password" always succeed.
It Happens in Every Language
The same flaw, in Java and in JavaScript, run against the Fee Tracker database:
// UNSAFE: the user's text is pasted into the SQL itself.
static void findUnsafe(Connection conn, String lastName) throws SQLException {
String sql = "SELECT student_id, first_name FROM students"
+ " WHERE last_name = '" + lastName + "'"
+ " ORDER BY student_id";
try (Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql)) {
while (rs.next()) {
System.out.println(" " + rs.getInt("student_id")
+ " " + rs.getString("first_name"));
}
}
}// UNSAFE: a template literal builds the SQL text from the user's input.
async function findUnsafe(lastName) {
const { rows } = await pool.query(
`SELECT student_id, first_name FROM students
WHERE last_name = '${lastName}' ORDER BY student_id`);
return rows;
}Called with x' OR '1'='1, both return all three students:
Unsafe search for: x' OR '1'='1
101 Srihitha
102 Advitha
103 NavikaWhat Attackers Can Reach
| If the injected query can... | The damage |
|---|---|
Change a WHERE condition | Read every row, or bypass a login check |
Add a UNION SELECT | Read other tables, such as user accounts |
| Run extra statements (some drivers allow this) | Change or delete data, create accounts |
| Trigger detailed error messages | Learn table and column names for the next attempt |
The real limit is the database account's privileges. An app that connects as a superuser can lose everything; one that connects as a role allowed only to read two tables can lose much less. Users, Roles and Privileges shows how to set that up.
The Fix: Parameters
A parameterized query sends the SQL with placeholders, and the values separately. The database parses the SQL first, so a value can only ever be a value, whatever characters it contains. PostgreSQL's PREPARE and EXECUTE show this directly in SQL:
PREPARE find_student (TEXT) AS
SELECT student_id, first_name FROM students
WHERE last_name = $1 ORDER BY student_id;
EXECUTE find_student ('Anamaneni');
EXECUTE find_student ('x'' OR ''1''=''1');PREPARE
student_id | first_name
------------+------------
101 | Srihitha
102 | Advitha
103 | Navika
(3 rows)
student_id | first_name
------------+------------
(0 rows)Explanation: $1 is a placeholder. With 'Anamaneni', all three sisters match. With the attack text, the database looks for a student whose last name is literally x' OR '1'='1, and there is none. The quotes are just characters in a value now.
In application code, the safe versions look like this:
// SAFE: the SQL has a placeholder, and the text is sent separately as a value.
String sql = "SELECT student_id, first_name FROM students"
+ " WHERE last_name = ? ORDER BY student_id";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setString(1, lastName);
try (ResultSet rs = ps.executeQuery()) {
// read rows as before
}
}// SAFE: $1 is a placeholder; the value travels separately.
const { rows } = await pool.query(
'SELECT student_id, first_name FROM students ' +
'WHERE last_name = $1 ORDER BY student_id', [lastName]);Run with the same input, the safe Java version prints no students, and the JavaScript one returns an empty array:
Safe search for: x' OR '1'='1
(done)
safe: []Why Escaping and Blocklists Fail
Escaping means doubling quotes in the input before pasting it in. It's easy to get wrong: a forgotten call, a different database's rules, or a number that isn't in quotes at all:
SELECT student_id, first_name
FROM students
WHERE student_id = 103 OR 1=1
ORDER BY student_id; student_id | first_name
------------+------------
101 | Srihitha
102 | Advitha
103 | Navika
(3 rows)Explanation: Imagine the program builds "... WHERE student_id = " + id and someone sends 103 OR 1=1 as the id. There are no quotes to escape, yet the query returns everyone. Converting the id to an integer first, or better, using a parameter, prevents it.
Blocklists reject input containing words like OR or --. Attackers simply use other spellings, comments and encodings, while honest users named O'Brien get blocked. Neither approach separates code from data, and only parameters do.
Defense in Depth
| Layer | What it does |
|---|---|
| Parameters everywhere | Stops injection at its source |
| Allow-lists for names | Table and column names can't be parameters; check them against a fixed list (Parameters and Prepared Statements) |
| Least privilege | The app's role can do only what the app needs |
| Validate input | Reject an id that isn't a number, a date that isn't a date |
| Generic error messages | Don't show database errors to users |
Common Mistakes
"This input comes from our own dropdown, so it's safe." Anyone can send any request; the browser isn't in control.
Escaping by hand. Libraries' placeholders exist so you never have to.
Parameterizing values but pasting in an ORDER BY column. Use an allow-list for names.
Connecting as a superuser. Injection then reaches everything.
Interview Corner
What is SQL injection?
A vulnerability where untrusted input is concatenated into a SQL statement, so the input can change the statement's structure and run as SQL.
How do you prevent SQL injection?
Use parameterized queries (prepared statements) for every value, allow-lists for identifiers such as sort columns, and least-privilege database accounts. Escaping and blocklists aren't reliable.
Why doesn't escaping quotes fully prevent injection?
It's easy to miss a case, rules differ between databases and encodings, and inputs used without quotes, like numbers, can be injected with no quote at all.
Practice
Challenge: A search box finds courses whose title contains the typed text. Write it safely with PREPARE, using '%' || $1 || '%' inside the SQL, then run it with the text Java and with the attack text x' OR '1'='1.
Show solution
PREPARE search_courses (TEXT) AS
SELECT course_id, title
FROM courses
WHERE title ILIKE '%' || $1 || '%'
ORDER BY course_id;
EXECUTE search_courses ('Java');
EXECUTE search_courses ('x'' OR ''1''=''1');PREPARE
course_id | title
-----------+-------------------
1 | Java Basics
2 | Java OOP
3 | Java Collections
5 | JavaScript Basics
(4 rows)
course_id | title
-----------+-------
(0 rows)The wildcards are added inside the SQL, so the user's text stays a value. "Java" finds four titles (including JavaScript Basics); the attack text finds nothing.
Key Takeaways
| Instead of | Write |
|---|---|
"... WHERE last_name = '" + name + "'" (Java) | "... WHERE last_name = ?" with ps.setString(1, name) |
`... WHERE last_name = '${name}'` (JavaScript) | '... WHERE last_name = $1', [name] |
f"... WHERE last_name = '{name}'" (Python) | "... WHERE last_name = %s", (name,) |
Was this tutorial helpful?