Back to blog
Application security

SQL Injection (SQLi) – How to Defend in Practice

Published: 2025-01-152 minKrzysztof Jaroński

What is SQL injection?

SQL injection (SQLi) means an attacker injects parts of a SQL query into your application (e.g. in a form or URL parameter). If the app concatenates user input into the SQL string without escaping or parameterization, the database will execute that code. Results can include: reading others' data, modifying or deleting data, and in extreme cases – server takeover.

SQLi is in the OWASP Top 10 (under Injection) and still appears very often in audits and pentests.

Rule no. 1: parameterized queries

Instead of:

"SELECT * FROM users WHERE id = " + userInput

use prepared statements / parameterized queries:

"SELECT * FROM users WHERE id = ?"  // and pass userInput as a parameter

Then user data is treated only as a value, never as part of SQL syntax. That removes most classic SQLi.

ORM and query builders

Good ORMs (e.g. in Python, Node, Java) parameterize by default – as long as you do not use "raw" SQL with concatenation. Query builders (Knex, SQLAlchemy, etc.) usually enforce parameters too. Be careful with raw / execute and user-supplied strings.

Additional steps

  • App DB account – use least privilege (e.g. only SELECT/INSERT/UPDATE on needed tables, no DROP or user management).
  • Input validation – even with parameterization: if a field should be a number, accept only numbers; limit length and characters where it makes sense.
  • Logging and monitoring – unusual queries or SQL errors can indicate attack attempts.

Summary

Defence against SQLi in practice comes down to: parameterized queries (or ORM) + least privilege in DB + input validation. A pentest or code review will confirm whether your application is resistant.

Planning an [application security test](/testy-penetracyjne/)? SQLi is one of the first areas I check.