SQL Injection: How Attacks Work and How to Prevent Them

SQL injection remains one of the most dangerous web vulnerabilities. Learn how it works through real examples and how to write code that's immune.

SQL Injection: How Attacks Work and How to Prevent Them

The Most Dangerous Vulnerability

SQL injection has been at the top of the OWASP Top 10 for over a decade. In 2024, it still appears in major breaches — from user data exposure to full server takeover. Understanding it isn't optional for developers.

How SQL Injection Works

The vulnerability occurs when user input is directly concatenated into a SQL query instead of being passed as a parameter.

The Vulnerable Code

// ❌ VULNERABLE — Never do this
const query = `SELECT * FROM users
  WHERE email = '${email}' AND password = '${password}'`;

// User enters:
// email: admin@example.com
// password: ' OR '1'='1
// Result: SELECT * FROM users WHERE email = 'admin@example.com'
//          AND password = '' OR '1'='1'
// Always true — attacker is logged in!

The Attack Types

  • Union-based: Extract data from other tables
  • Boolean-based: Infer information character by character
  • Time-based: Use SLEEP() to infer responses
  • Out-of-band: DNS exfiltration via database error messages

Real Attack Payload

' UNION SELECT NULL,username,password,NULL FROM users--

The Fix: Parameterized Queries

// ✅ Node.js with prepared statements
const result = await db.query(
  'SELECT * FROM users WHERE email = $1 AND password = $2',
  [email, password]
);

// ✅ Python with SQLAlchemy
user = db.session.query(User).filter_by(
  email=email, password=password
).first()

ORMs Are Not Foolproof

SQLAlchemy, Hibernate, Prisma — ORMs prevent most SQL injection, but some patterns still allow it:

// ⚠️ Still vulnerable — raw SQL in ORM
db.raw('SELECT * FROM users WHERE name = ' + userInput)

Defense in Depth

  • Parameterized queries — always, no exceptions
  • Least privilege — database user should only have needed permissions
  • Input validation — whitelist expected values, reject unexpected patterns
  • Web Application Firewall (WAF) — additional protection layer
  • Regular security audits — scan code and dependencies

How to Test Your Code

Try SQLMap (open-source SQL injection tool) on your own staging environment. If it finds something, fix it before attackers do.

Format SQL for Readability

Use our SQL Formatter to pretty-print complex queries — making suspicious patterns easier to spot during code review.

← Back to Blog
Copied!