SQL Injection Regex
Regex patterns for detecting common SQL injection attempts in input validation.
(\b(SELECT|INSERT|UPDATE|DELETE|DROP|UNION|ALTER)\b)|(--)|(;\s*$)About this pattern
This flags input containing SQL keywords, comment markers, or a trailing semicolon — a rough heuristic for spotting attempted injection in logs or a web application firewall.
Say the important thing first: this is not a defence, and using it as one is dangerous. Blocklists fail in both directions. They produce false positives constantly, because ordinary text contains these words — a customer named Update, a message reading "please select a delivery date", a comment mentioning a dropped call. And they are trivially evaded, because SQL admits comment insertion, case variation, encoding, and whitespace tricks that a keyword list does not anticipate. A filter that catches DROP TABLE does not catch its many equivalent spellings.
The actual fix is parameterised queries. When values travel to the database separately from the statement text, the engine never parses them as SQL, and injection becomes structurally impossible rather than merely filtered. Every mainstream database driver supports them, and using one is less code than the alternative — not more.
Where this pattern is legitimately useful is detection rather than prevention: flagging suspicious requests for review, alerting on probing, or triaging logs after an incident. Treat a match as a signal worth looking at, never as a control that makes unsafe query construction safe.
Worked examples
A detection heuristic, not a defence. Parameterised queries are the actual fix — this only flags suspicious input.
Matches
- '; DROP TABLE users; --
- SELECT * FROM users
Does not match
- ordinary user input
FAQ
Can I use this to block SQL injection?
No, and relying on it is dangerous. Keyword blocklists produce constant false positives on ordinary text and are trivially evaded through case changes, comments, and encoding.
What actually prevents SQL injection?
Parameterised queries. Values travel separately from the statement, so the engine never parses them as SQL and injection becomes structurally impossible rather than filtered.
So what is this pattern good for?
Detection, not prevention — flagging suspicious requests for review, alerting on probing, and triaging logs after an incident.