SQL Injection: What It Is and How We Prevent It
SQL injection is one of the oldest and most dangerous web application vulnerabilities. Despite being well understood for over 20 years, it remains in the OWASP Top 10 because it continues to appear in poorly built applications.
How SQL Injection Works
When an application takes user input and inserts it directly into a database query without sanitisation, an attacker can inject malicious SQL code. For example, if a login form constructs a query like:
SELECT * FROM users WHERE username = '[input]' AND password = '[input]'
An attacker entering ' OR '1'='1 as the username could bypass authentication entirely — because the resulting query always evaluates to true.
The Impact
SQL injection can allow attackers to: extract the entire contents of a database (all user data, passwords, sensitive records), modify or delete data, bypass authentication, and in some configurations, execute system commands on the database server.
How We Prevent It
- Parameterised queries (prepared statements): The primary defence. User input is passed as a parameter, never interpolated directly into the query. The database treats it as data, not code.
- ORM (Object-Relational Mapping): Frameworks like Django ORM, Hibernate, or Eloquent use parameterised queries by default.
- Input validation: Validate that inputs match expected format and type before use.
- Least privilege: Database accounts used by applications should have the minimum permissions needed — no DROP TABLE access for a read-heavy application.
- WAF: A Web Application Firewall can detect and block common SQL injection patterns as a secondary defence.