100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

What Is SQL Injection and How Do You Prevent It?

Learn how SQL injection works via string concatenation and how parameterized queries prevent it, with a code example.

mediumQ94 of 224 in Web Development Est. time: 5 minsLast updated:
Open Code Lab

Expected Interview Answer

SQL injection is a vulnerability where an attacker supplies crafted input that gets concatenated directly into a SQL query string, causing the database to execute attacker-controlled SQL instead of the query the developer intended, most reliably prevented by using parameterized queries (prepared statements) instead of string concatenation.

When application code builds a query by concatenating raw user input into a SQL string — for example inserting a username directly into a WHERE clause — an attacker can supply input like a value containing a quote and additional SQL syntax to alter the query’s logic, bypass authentication checks, exfiltrate unrelated table data via UNION SELECT, or in some database configurations execute destructive statements. The vulnerability exists because the database cannot distinguish between the intended query structure and attacker-supplied data once they have been merged into a single string. Parameterized queries fix this at the root by sending the query structure and the user-supplied values to the database separately: the driver sends a query template with placeholders, and the values are bound afterward, so the database always treats them strictly as data, never as executable SQL syntax, no matter what characters they contain. Additional layers like least-privilege database accounts, input validation, and ORM query builders that use parameterization under the hood all help, but parameterized queries are the primary, non-negotiable defense.

  • Parameterized queries make the database treat all user input strictly as data, never as executable syntax
  • Eliminates the entire class of injection regardless of how creatively input is crafted
  • Works uniformly across nearly all major relational databases and drivers
  • Combines well with least-privilege DB accounts to limit blast radius if another layer fails

AI Mentor Explanation

SQL injection is like a scorer accepting a handwritten note that says “team name: India, then also erase the entire scoreboard” and blindly typing the whole note into the official system as one command. Because the note mixes the actual team name with extra instructions, the system cannot tell where the real data ends and the malicious instruction begins. A parameterized approach is instead handing the scorer a fixed form with one blank labeled “team name,” so anything written there is always treated as plain text, never as a new command. That separation-of-instructions-from-data is exactly what parameterized queries enforce.

Step-by-Step Explanation

  1. Step 1

    App builds a query with string concatenation

    Raw user input is inserted directly into a SQL string instead of being bound as a separate parameter.

  2. Step 2

    Attacker crafts malicious input

    Input includes SQL syntax (quotes, UNION SELECT, statement terminators) designed to alter the query’s intended logic.

  3. Step 3

    Database executes the altered query

    Because the query and data were merged into one string, the database cannot tell attacker syntax from legitimate structure.

  4. Step 4

    Attacker achieves impact

    This can bypass authentication, exfiltrate unrelated data, or modify/delete records, depending on privileges and query context.

What Interviewer Expects

  • Clear explanation of why string concatenation is the root cause
  • Naming parameterized queries / prepared statements as the primary fix, not just input sanitization
  • Understanding of the mechanism: query structure and data sent separately to the database
  • Mention of defense-in-depth: least-privilege DB accounts, ORM parameterization, input validation as supporting layers

Common Mistakes

  • Believing input sanitization/escaping alone is a sufficient primary defense instead of parameterized queries
  • Assuming ORMs are automatically safe even when raw/string-interpolated queries are used within them
  • Not mentioning UNION-based data exfiltration as a real-world impact beyond authentication bypass
  • Confusing SQL injection with XSS (injection targets the database query; XSS targets the browser-rendered output)

Best Answer (HR Friendly)

SQL injection happens when an app takes what a user typed and pastes it directly into a database command, so a cleverly crafted input can change what that command actually does, like bypassing a login or deleting data. It is prevented by always sending user input to the database separately from the command structure, using what is called a parameterized query, so the database only ever treats that input as plain data, never as an instruction.

Code Example

Vulnerable concatenation vs safe parameterized query
// VULNERABLE: user input concatenated directly into SQL
async function findUserUnsafe(db, username) {
  const query = "SELECT * FROM users WHERE username = '" + username + "'"
  return db.query(query)
  // username = "' OR '1'='1" bypasses the intended filter entirely
}

// SAFE: parameterized query, value bound separately from structure
async function findUserSafe(db, username) {
  const query = 'SELECT * FROM users WHERE username = $1'
  return db.query(query, [username])
  // username is always treated as data, never as SQL syntax
}

Follow-up Questions

  • How does a UNION-based SQL injection attack exfiltrate data from unrelated tables?
  • Why is input sanitization alone considered insufficient compared to parameterized queries?
  • How does the principle of least privilege limit the blast radius of a successful injection?
  • How does SQL injection differ from NoSQL injection in a document database like MongoDB?

MCQ Practice

1. What is the root cause of SQL injection vulnerabilities?

Merging user input into the query string means the database cannot distinguish intended syntax from attacker-supplied data.

2. What is the primary, most reliable defense against SQL injection?

Parameterized queries send the query template and values separately, so values are always treated as data by the database.

3. What is a UNION-based SQL injection typically used to achieve?

UNION SELECT lets an attacker append a second query to merge unrelated table data into the original result set.

Flash Cards

What is SQL injection?Attacker input alters a SQL query’s logic because it was concatenated into the query string instead of bound as data.

Primary defense?Parameterized queries / prepared statements, which bind values separately from query structure.

Why is sanitization alone insufficient?It is easy to miss an edge case; parameterization removes the entire vulnerability class structurally.

Supporting defense layer?Least-privilege database accounts limit the damage if another layer fails.

1 / 4

Continue Learning