Loading lessons...
SQL Injection
SQL Injection
SQL injection is an attack where a user's input is treated as part of the SQL command, letting attackers read or destroy data.
The classic example
A login box takes a username and builds SQL like this:
SELECT * FROM Users WHERE UserId = '105' OR 1=1;
If input "105 OR 1=1" is pasted in, the condition OR 1=1 is always true, and the query returns every user.
Another example
SELECT * FROM Users WHERE UserId = '105'; DROP TABLE Suppliers;
A second statement injected with ; could drop a table.
Why it happens
The application concatenates user input directly into the SQL string:
"SELECT * FROM Users WHERE Name = '" + userInput + "'"
The input becomes part of the query instead of staying a value.
The main defense: prepared statements
A prepared statement separates the SQL from the values:
-- Parameters are placeholders; the value is passed separately
PREPARE stmt FROM 'SELECT * FROM Users WHERE Name = ?';
EXECUTE stmt USING 'Alice';
The database treats the input as data, never as SQL.
More defenses
- Validate input (only allow expected characters).
- Escape special characters.
- Use a database permission model that limits what app accounts can do.
- Don't build SQL by string concatenation.
TL;DR
- SQL injection happens when user input becomes part of the SQL.
OR 1=1tricks and;statement injection are classic attacks.- Prepared statements / parameterized queries are the main fix.
- Never concatenate user input into SQL.