thecodex.expert · The Codex Family of Knowledge
SQL

SQL Injection and Security

A single quote typed into a login form has, in real historical breaches, been enough to bypass authentication or delete an entire database — all from string concatenation, nothing more exotic.

SQL:2016 / ANSI Never concatenate input Last verified:
Canonical Definition

SQL injection occurs when user input is concatenated directly into a SQL string, allowing an attacker to inject their own SQL fragments that change the query's meaning entirely — bypassing a login check, extracting unauthorized data, or deleting tables. The fix is not escaping quotes or filtering "dangerous" characters (both are fragile and have repeatedly been bypassed in practice); it's using parameterized queries (also called prepared statements), which send the SQL structure and the user's data to the database separately, so user input can never be interpreted as SQL code no matter what it contains.

How the vulnerability actually works

If a username of ' OR '1'='1 is concatenated straight into this query, the WHERE clause becomes always-true, matching every row in the table — an attacker can log in as anyone without ever knowing a password.

SQLvulnerable.sql
-- VULNERABLE: string concatenation with raw user input
query = "SELECT * FROM users WHERE username = '" + userInput + "'"

-- if userInput is:   ' OR '1'='1
-- the actual query becomes:
--   SELECT * FROM users WHERE username = '' OR '1'='1'
-- '1'='1' is always true — this matches EVERY row in the table

The fix: parameterized queries

The placeholder and the value are sent to the database as two separate pieces — the database engine never treats the value as part of the SQL syntax, so no input, however crafted, can change the query's structure.

SQLparameterized.sql
-- SAFE: the ? (or $1, or %s depending on the driver) is a placeholder,
-- never string-concatenated with the query text
SELECT * FROM users WHERE username = ?;
-- the driver sends "?" and userInput as SEPARATE pieces —
-- even a value of ' OR '1'='1 is treated as a literal string to match, nothing more

Beyond injection: least privilege

Application database users should have only the permissions their application actually needs — a web app's login user rarely needs DROP TABLE or ALTER TABLE privileges, and restricting them limits the damage even if some other vulnerability is exploited. This complements, but doesn't replace, parameterized queries — the two address different layers of the same overall risk.

Sources

1
OWASP Foundation. SQL Injection, owasp.org/www-community/attacks/SQL_Injection.