SQL Injection: Explained Simply

Web · 8 min read · Published 2026-01-15

What SQL Injection is

SQL Injection (SQLi) is a vulnerability where an application accidentally treats user input as part of a SQL query. The core problem is untrusted input influencing query structure, not “magic hacker strings”.

Why it happens (root cause)

  • Building SQL queries by concatenating strings
  • Trusting input without validation/constraints
  • Using overly-privileged database accounts
  • Missing monitoring, rate limits, and error handling

Safe mental model

Think of a query in two parts: query structure + values. SQLi happens when the attacker can change the structure. Defenses aim to lock structure and only allow values.

Insecure pattern (do not use)

This is an educational example showing a common anti-pattern: string concatenation.

insecure login query (anti-pattern)
// ❌ Anti-pattern: SQL built via string concatenation
const query =
  "SELECT id, username FROM users WHERE username = '" + username +
  "' AND password = '" + password + "'";

Correct pattern: parameterized queries

Parameterization keeps the SQL structure fixed and sends values separately. This is the main fix for SQLi.

parameterized query (concept)
SELECT id, username
FROM users
WHERE username = ? AND password = ?;

Defense checklist (what pros actually do)

  • Parameterized queries everywhere (ORMs can still be unsafe if misused)
  • Least privilege DB users (apps shouldn’t have admin rights)
  • Input constraints (length limits, allow-lists where appropriate)
  • Safe error handling (don’t leak query errors to users)
  • Logging & monitoring (spikes, unusual query patterns)
  • WAF/rate limiting as a backup layer, not the main fix

Quick “review your code” questions

  • Do we ever build SQL with +, template strings, or string formatting?
  • Do we use prepared statements/parameters for every query?
  • Do app DB credentials have only the minimum permissions needed?
  • Do we leak raw DB errors back to the browser?

Mini lab idea (safe)

Create a tiny demo app in a local dev environment that logs how queries are built (no real users/data). Compare string concatenation vs parameterized queries and observe the difference.

“structure vs values” rule of thumb
// ✅ Rule: SQL structure is constant, only values change
// Use parameters, not concatenation.

Ethical note: only test systems you own or have explicit permission to test.

← Back to Blog