Web Security & WAF interview question · Most asked

What is SQL injection and how do you prevent it?

Summary

SQL injection occurs when untrusted input is concatenated into SQL, letting attackers change the query to read or modify data. Prevent it with parameterized queries/prepared statements (or ORMs used correctly), allow-listing identifiers like sort columns, and least-privilege database accounts.

Longer Answer

Escaping functions are error-prone; parameters keep data separate from code. ORMs are safe unless you use raw SQL with string formatting (text(f"... {x}"), whereRaw). Second-order injection stores malicious input that's later used unsafely. NoSQL databases have analogous operator-injection issues.

Code Example

-- Vulnerable (string concatenation)
query = "SELECT * FROM users WHERE email = '" + email + "'"

-- Safe (parameterized)
cursor.execute("SELECT * FROM users WHERE email = %s", (email,))

Key Points

  • Parameterized queries
  • Allow-list identifiers
  • Beware raw SQL in ORMs
  • Least-privilege DB users

More most-asked Web Security & WAF questions

← All Web Security & WAF questions