SQL Injection

Updated · 9 min read
mediumPostgreSQL 18sqlsql-injectionsecurityprepared-statementsowaspinterview

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'='1 turns "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:

Java
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:

SQL▶ Try it
SELECT 'SELECT student_id, first_name FROM students'
       || ' WHERE last_name = ''' || 'x'' OR ''1''=''1' || ''''
       || ' ORDER BY student_id' AS query_the_program_builds;
Output
                                     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:

SQL▶ Try it
SELECT student_id, first_name
FROM students
WHERE last_name = 'x' OR '1'='1'
ORDER BY student_id;
Output
 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.

The typed quote closes the programmer's string, so OR '1'='1' becomes part of the SQL

It Happens in Every Language

The same flaw, in Java and in JavaScript, run against the Fee Tracker database:

Java
// 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"));
        }
    }
}
JavaScript
// 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:

Output
Unsafe search for: x' OR '1'='1
  101 Srihitha
  102 Advitha
  103 Navika

What Attackers Can Reach

If the injected query can...The damage
Change a WHERE conditionRead every row, or bypass a login check
Add a UNION SELECTRead other tables, such as user accounts
Run extra statements (some drivers allow this)Change or delete data, create accounts
Trigger detailed error messagesLearn 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:

SQL▶ Try it
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');
Output
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:

Java
// 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
    }
}
JavaScript
// 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:

Output
Safe search for: x' OR '1'='1
(done)
safe: []
Pasted into the SQL, the input matched all 3 students; sent as a parameter, it matched 0

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:

SQL▶ Try it
SELECT student_id, first_name
FROM students
WHERE student_id = 103 OR 1=1
ORDER BY student_id;
Output
 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

LayerWhat it does
Parameters everywhereStops injection at its source
Allow-lists for namesTable and column names can't be parameters; check them against a fixed list (Parameters and Prepared Statements)
Least privilegeThe app's role can do only what the app needs
Validate inputReject an id that isn't a number, a date that isn't a date
Generic error messagesDon't show database errors to users
Parameters stop injection; allow-lists, validation, least privilege and quiet errors limit what slips through

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
SQL▶ Try it
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');
Output
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.

Quick check: SQL injection

3 questions
1What causes SQL injection?
2A query is built as "... WHERE last_name = '" + name + "'". The user types x' OR '1'='1. What happens?
3What's the reliable fix?

Key Takeaways

Instead ofWrite
"... 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?

Lesson 91 of 115