What Is SQL Injection? How It Works and How to Stop It
SQL injection turns a form field into an instruction the database obeys. It is one of the oldest flaws on the web, second on the latest list of the most dangerous software weaknesses, and one of the very few problems in security with a complete fix.

The search box on a company website looks like the least dangerous thing on the internet. It takes a few words and returns a list of products. Behind it, the site is writing a sentence in another language and handing that sentence to the database holding every customer record it has. SQL injection is what happens when the words someone types stop being the subject of that sentence and become part of the instruction instead.
What Is SQL Injection?
SQL is the language almost every application uses to talk to its database. When you log in somewhere, the application does not go looking through a filing cabinet. It writes a short request in SQL, roughly "give me the account whose email address is this one", and hands it to the database, which answers.
Injection is what happens when the value in that request stops being a value. If the application builds its request by gluing your text into the middle of the sentence, then text that contains SQL punctuation can close the value early and add instructions of its own. The database receives one continuous request and has no way to tell which parts came from the developer and which parts came from you.
MITRE catalogs the flaw as CWE-89, improper neutralization of special elements used in an SQL command, and rates its likelihood of exploit as high. The name is a mouthful, but it is precise about where the fault lies: the special characters that mean something to SQL were never neutralized, so the database read them as language rather than as data.
The flaw does not live only in visible forms. Anything a person can influence that eventually reaches a database query is a candidate: a login field, a search bar, a product filter, a number in a web address, a value in an API request, a file name, an HTTP header your browser sends without showing you. Security people shorten the whole thing to SQLi.
How Does a SQL Injection Attack Work?
Take a login form. The application has an email box and a password box, and somewhere in its code it builds a query by joining fixed text to whatever arrived from the browser. When someone types an ordinary email address, the finished query reads exactly as intended.
SELECT * FROM users
WHERE email = 'dana@example.com'
Now suppose the box receives an apostrophe followed by a condition that is always true and a comment marker that tells the database to ignore whatever comes after. The apostrophe closes the value early, the always-true condition widens the request from one row to all of them, and the comment marker discards the rest of the original sentence, including the password check. The finished query is still valid SQL. It is simply a different question.
SELECT * FROM users
WHERE email = '' OR 1=1 --'
Read those two blocks again and notice what the attacker did not have to do. No password was guessed, no encryption was broken, no software was exploited in the sense of a memory bug or a missing patch. The application built a sentence out of untrusted parts and read it out loud, and the database did what any database does with a valid question.
The same shape works anywhere the pattern repeats. A search box that pastes your words into a query can be asked to return rows from a different table. A product page that reads an item number out of the web address can be asked to return the price list, the order history, or the table where the passwords are kept.
Why Does the Database Trust the Input?
Because it cannot tell the difference. OWASP's own write-up of the attack puts the cause at the level of the language itself: the flaw depends on SQL drawing no real line between the commands and the data those commands operate on, so a single punctuation character in the wrong place moves user input into the part of the sentence that gives orders, where it did not exist before.
That is worth sitting with, because it explains why the usual instincts do not help. The database is not compromised, misconfigured or out of date. It received a syntactically perfect request from an application it has every reason to trust, and it answered honestly. The failure happened one step earlier, when the application assembled a command out of a string it did not control.
It also explains why this is a defect in how software is built rather than a product you forgot to buy. The database vendor cannot fix it for you. The hosting company cannot fix it for you. The fix has to happen in the moment the query is written, and that moment belongs to whoever wrote the code.
What Can an Attacker Do With a SQL Injection Attack?
More than most people assume, because a database rarely holds one kind of thing. MITRE's entry for CWE-89 lists the consequences by what they violate, and the list runs from bad to worse.
- Read data the application never displays. Customer tables, order histories, internal notes, stored password hashes. Loss of confidentiality is the most frequent outcome because databases are where the sensitive material lives.
- Bypass the login entirely. MITRE is explicit that when weak SQL is used to check usernames and passwords, an attacker can connect as another user with no prior knowledge of that user's password. The login is not defeated. It is skipped.
- Change or delete records. The same access that reads a balance can alter it, void a transaction, add an administrator, or remove the log entries that would have shown any of it happening.
- Take on someone else's privileges. If the application stores who is allowed to do what in the same database, that table can be edited too.
- Reach beyond the database. In some configurations an attacker can redirect query output into a file and get commands running on the server itself, which turns a website flaw into a foothold on the network.
Any of the first three, on a table with customer records in it, is a data breach with notification obligations attached, and the steps that follow are the same ones covered in what to do after a data breach: work out what was reachable, work out what was taken, and tell the people whose data it was.
Types of SQL Injection Attacks
The categories describe how the answer gets back to the attacker, which matters because it determines what you would see in your logs.
| Type | How it works | What it means for you |
|---|---|---|
| Error-based | The attacker submits input that provokes a database error, and the error message names tables, columns or the database engine | Detailed errors shown to visitors hand over the map. Turn them off in production |
| Union-based | A second query is attached to the first with the UNION operator, so results from another table come back inside the normal page | The data arrives through the ordinary page, which is why it can pass unnoticed |
| Boolean blind | No data comes back, so the attacker asks true or false questions and watches whether the page changes | Slow and noisy. Thousands of near-identical requests are the tell |
| Time blind | The attacker asks the database to pause before answering, and reads the answer from how long the page takes | Nothing appears in the response at all. Only request volume and timing show it |
| Out of band | The database is told to make its own outbound connection, such as a lookup to a domain the attacker controls | Rare, and the reason outbound rules on database servers matter |
| Second order | Hostile text is stored innocently in one place, then used unsafely later by another part of the application | The input that caused it and the query that fired it are in different features, so testing one screen at a time misses it |
Blind techniques are the ones that surprise people. There is no error message, no odd page, nothing on the screen that looks wrong, and the attacker is still extracting the database one yes or no question at a time. What gives it away is volume: thousands of requests to the same address, differing by one character each time.

How Common Is SQL Injection?
Common enough that the people who rank software weaknesses put it near the top every year, decades after the fix was published.
The uncomfortable part is the date on the remedy. In the same alert, CISA and the FBI point out that MySQL shipped prepared statements, the feature that removes this entire class of defect, in 2004. The gap between the fix existing and the fix being used is what keeps the weakness at number two, and it is also why the alert is addressed to executives rather than to developers. This is a management problem wearing a technical costume.
What Is an Example of a SQL Injection Attack?
The clearest one is MOVEit. In May 2023 the CL0P extortion group began exploiting a SQL injection flaw in Progress Software's MOVEit Transfer, a product organizations use to move files between each other. According to the joint advisory from CISA and the FBI, the group started on May 27, used the injection flaw to install a web shell named LEMURLOOT on internet-facing MOVEit servers, and stole data from the databases underneath. CISA added the flaw to its known exploited vulnerabilities catalog on June 2, 2023.
NIST's National Vulnerability Database record for CVE-2023-34362 classifies it as CWE-89, scores it 9.8 out of 10, and describes an unauthenticated attacker able to infer the structure of the database and run statements that alter or delete what is in it. Unauthenticated is the word that matters. No account, no password, no phishing email. Nobody had a patch either, because it was a flaw nobody outside the attackers knew about when the campaign began.
- Find inputs that reach a databaseAutomated crawling of forms, web addresses and API endpoints
- Probe with punctuationA single quote mark, submitted everywhere, to see what breaks
- The application answersA database error, a changed page, or a delay confirms the flaw
- Map and extractTooling walks the tables and pulls the contents out
- Establish a footholdA web shell dropped on the server keeps access after the flaw is patched
- Detection and patchRequest volume in the logs, then the vendor fix, then hunting for the shell
The scale followed from the product's position rather than its size. MOVEit sat between organizations and their partners, so one vendor's flaw reached the records of everyone whose data passed through it, and the same crew ran the usual extortion playbook against the victims afterward. CISA and the FBI wrote their Secure by Design alert on SQL injection in response to the exploitation of injection defects in a managed file transfer application that, by their account, impacted thousands of organizations.
What Are Parameterized Queries?
A parameterized query, also called a prepared statement, is the fix. Instead of building one long sentence out of fixed text and user input, the application sends the sentence first, with blanks in it, and sends the values separately afterward.
# Unsafe: the value is pasted into the sentence
sql = "... WHERE email = '" + typed + "'"
# Safe: the value travels beside the sentence
sql = "... WHERE email = ?"
run(sql, [typed])
The difference is not cosmetic and it is not a filter. By the time the value arrives, the database has already parsed the command and decided what its structure is. The blank can only ever be a value. If someone types an apostrophe, a UNION and a comment marker into the email box, the database goes looking for an account whose email address is literally that entire string of characters, finds nothing, and returns nothing.
OWASP's SQL injection prevention cheat sheet describes the property that makes this work: prepared statements force the developer to define all the SQL first and pass each parameter in later, so the database always distinguishes between code and data no matter what the input contains. CISA and the FBI put the same point in terms of outcomes, recommending parameterized queries with prepared statements as the way to separate SQL code from user-supplied data and eliminate the class of defect rather than the individual bug.
Every mainstream language and framework supports this, most of them have for twenty years, and modern data access libraries do it by default. Which is why the honest description of a SQL injection vulnerability in new code is not that the team lacked a tool. It is that the team wrote the query the old way.
How to Prevent SQL Injection Attacks
Five things, in the order they pay off. The first one does almost all of the work and the other four exist because software is never uniformly good.
How Do You Know If Your Website Is Vulnerable to SQL Injection?
Three methods, in increasing order of cost and confidence, and one conversation.
An automated scan is the cheapest and finds the obvious cases. A vulnerability scanner submits test characters into every input it can reach and reports what responded abnormally, which catches the error-based and boolean cases well and the blind and second-order ones poorly. A penetration test puts a person behind the same work, which is what finds injection reachable only through a sequence of steps, an unusual API field, or data stored innocently on one screen and used unsafely on another. A code review is the only method that finds the pattern rather than the symptom, and the pattern is easy to see once you know what it looks like: a query assembled by joining text to a variable.
If you did not write the code, you are not helpless. Ask the people who did:
- Are all database queries in this application parameterized, and how do you verify that when new code is added?
- What rights does the account the application uses to reach the database actually have?
- What does a visitor see when a database error occurs?
- When was this application last tested for injection by someone who did not write it, and can I see the report?
Vague answers to these are themselves an answer. A team that has this handled will find the questions easy, because the work is already visible in their code and their pipeline.
Can a Web Application Firewall Stop SQL Injection?
Partly, and this one is genuinely contested. A web application firewall inspects HTTP requests before they reach your application and blocks the ones matching known attack patterns, which stops the automated background noise and buys real time when a flaw is announced in software you cannot patch today. On an internet-facing application it is worth having.
What it does not do is fix the defect. The application still builds its queries the same way, and the filter is now the only thing between the two. OWASP's own community page on SQL injection links a page on how to get injection past a web application firewall, which tells you how the people who write the defensive guidance regard its limits. Filters work on the shape of a request, and the shape of a request has more variations than a rule set can enumerate.
Key takeaways
- SQL injection sends database commands through an ordinary input, and it works because the application pastes user text into a query instead of keeping the two apart.
- The database is not broken when this happens. It receives a valid question and answers it correctly, which is why no database setting fixes it.
- The damage runs from reading customer tables to skipping the login, changing records, and in some setups reaching the server itself.
- It is still second on MITRE's 2025 list of the most dangerous software weaknesses, more than twenty years after the fix shipped.
- Parameterized queries end it, because the database parses the command before it ever sees the value. Sanitizing input is the weak alternative, and both OWASP and CISA say so.
- Least privilege on the database account decides how much an attacker gets when something is missed.
- If you did not write the code, the useful action is asking the people who did whether every query is parameterized and how they verify it.
Common questions
What is SQL injection in simple terms?
It is typing a command into a box that expected a value. The website was going to ask its database a question with your text inside it, and if your text contains database punctuation, it changes what the question says. The database then answers the attacker's question instead of the site's.
What is an example of a SQL injection attack?
MOVEit, in 2023. The CL0P group used a SQL injection flaw in Progress Software's file transfer product to install a web shell and steal data from the databases behind it, affecting thousands of organizations. NIST scored the flaw 9.8 out of 10 and recorded that no login was required to use it.
Is SQL injection still a threat?
Yes. CWE-89 ranks second in the 2025 CWE Top 25 Most Dangerous Software Weaknesses, up one place from 2024, and four of its vulnerabilities are in CISA's catalog of flaws known to be actively exploited. The fix has existed since 2004 and plenty of software still does not use it.
What can happen if a SQL injection attack succeeds?
Whatever the database holds, and whatever it can be made to do. The two that surprise people are the login bypass, where the attacker becomes another user without ever learning the password, and the configurations where query output can be turned into commands on the server. Where the table holds customer records, it is also a breach with notification obligations attached.
What is blind SQL injection?
Injection where nothing comes back on the page. The attacker asks the database true or false questions, or asks it to pause before responding, and reads the answer from how the page behaves rather than from what it says. It is slower, it works where error messages are switched off, and it looks like thousands of nearly identical requests in your logs.
How do prepared statements prevent SQL injection?
The application sends the query with blanks in it first, and the values afterward. The database has already parsed the command by the time the value arrives, so the value can only be a value. Whatever the user typed is treated as text to look for, never as an instruction to run.
Does input validation stop SQL injection?
Not on its own, and relying on it is the most common mistake in this area. A filter has to anticipate every encoding an attacker might try, which is why both OWASP and CISA rank sanitizing input below parameterized queries rather than beside them. Validate input for its own sake, then parameterize the query anyway.
Can a web application firewall block SQL injection?
It blocks the recognizable attempts and buys time when a vulnerability is announced in software you cannot patch immediately. It does not remove the flaw, and OWASP's own material covers how injection gets past these filters. Treat it as cover while the code is fixed, not as the fix.
Does using an ORM protect against SQL injection?
Mostly, because object relational mappers build parameterized queries for you by default, which is why they are recommended. The exceptions are the raw query escape hatch every ORM provides, and query fragments assembled as text for sorting or table names. The flaw follows the string concatenation wherever it goes.
How do I test my website for SQL injection?
Start with an automated vulnerability scan, which finds the obvious cases cheaply. Add a penetration test for the ones a scanner misses, particularly blind and stored injection. If you have access to the source, a code review looking for queries built by joining text to variables is the only method that finds the cause rather than the symptom.
Is SQL injection illegal?
Yes. Submitting injected input to a system you do not own or have written permission to test is unauthorized access under the Computer Fraud and Abuse Act, which makes it a federal crime to intentionally access a computer without authorization or to exceed authorized access, with state statutes on top. Testing your own systems is fine, and testing someone else's is fine only with a signed scope agreement in hand before you start.
On this page
- What Is SQL Injection?
- How Does a SQL Injection Attack Work?
- Why Does the Database Trust the Input?
- What Can an Attacker Do With a SQL Injection Attack?
- Types of SQL Injection Attacks
- How Common Is SQL Injection?
- What Is an Example of a SQL Injection Attack?
- What Are Parameterized Queries?
- How to Prevent SQL Injection Attacks
- How Do You Know If Your Website Is Vulnerable to SQL Injection?
- Can a Web Application Firewall Stop SQL Injection?

Daniel Reyes
Daniel Reyes is a CISSP who spent twelve years in security operations, most recently leading a detection and response team for a mid-sized healthcare group in Texas. He reviews every resource and breach report on Cyber Security Firms for technical accuracy before it publishes.
Most of the people he has trained arrived having been told too much: a dozen acronyms, six vendors, and no clear idea which risk was theirs. His approach is to explain what an attack actually does before naming the tool that stops it, on the basis that most breaches start with something a reader could have recognised.