What is SQL injection and how is it prevented?

IntermediateConceptOWASP ZAP
Answer

Short answer

SQL injection happens when user input is concatenated into a SQL query, letting an attacker change the query — reading, modifying or deleting data. It's prevented with parameterised queries (prepared statements), ORMs used correctly, input validation and least-privilege database users. SAST finds it in code; DAST (ZAP) finds it in the running app.

Vulnerable code

String sql = "SELECT * FROM users WHERE email = '" + email + "'";

Input ' OR '1'='1 turns it into ... WHERE email = '' OR '1'='1' → returns every user.

Safe code

PreparedStatement ps = conn.prepareStatement("SELECT * FROM users WHERE email = ?");
ps.setString(1, email);
cur.execute("SELECT * FROM users WHERE email = %s", (email,))

Defence in depth

  • Parameterised queries everywhere (also in stored procedures).
  • Least-privilege DB user — the app can't DROP tables even if injected.
  • Generic error messages (don't leak SQL errors).
  • WAF rules as an extra layer.

How tools detect it

  • SonarQube flags string-built queries (taint analysis).
  • ZAP active scan sends payloads like ', ' AND 1=1--, time-based SLEEP(5) and watches for errors or behaviour changes.

What to say in the interview

"SQL injection comes from concatenating input into queries. The fix is parameterised queries, backed by least-privilege DB users and generic errors. SonarQube catches it statically, ZAP confirms it dynamically."

All Security Tools questions Roadmap: OWASP ZAP — dynamic testing (DAST)

More on OWASP ZAP