SQL injection happens when an application builds a database query by gluing user input directly into the SQL text, so the database cannot tell data from commands. An attacker types SQL syntax into a form field, URL or API parameter, changing the query's meaning — for example turning a login check into a condition that is always true, or appending a second query that dumps another table.
Key takeaways
- SQL injection works because the database cannot tell user data apart from SQL commands when input is concatenated into a query.
- The classic examples are login bypass with OR 1=1, UNION data theft, error-based leaks, and blind attacks that steal data one character at a time.
- Parameterized queries are the only reliable fix; escaping, blocklists and stored procedures alone do not stop it.
A login form asks for a username and a password. What happens if the username is not a name at all, but a fragment of database code? In a vulnerable application, the database runs it — and the attacker walks in as admin.
What is SQL injection?
SQL injection is an attack in which untrusted input is inserted into a SQL query so that the database executes part of the input as a command. It works because SQL makes no real distinction between the control plane and the data plane.
OWASP defines it plainly: a successful exploit can read sensitive data, modify data, execute administration operations such as shutting down the database, recover files from the database server's filesystem and, in some cases, issue commands to the operating system. The OWASP SQL injection page notes the severity is limited mainly by the attacker's skill and imagination.
The root cause is always the same: the application builds a query by concatenating strings. The database receives one long string containing both the intended query and the attacker's input, and it cannot tell which part was meant to be data.
What does vulnerable code look like?
Vulnerable code builds a query by pasting user input into the SQL string. This pattern appears in every language, and it looks deceptively ordinary.
In Python, the vulnerable version looks like this:
query = f"SELECT * FROM users WHERE username = '{username}'"- With normal input
alice, the database runsSELECT * FROM users WHERE username = 'alice'. - With malicious input, the same line runs the attacker's logic instead.
The same flaw appears in Node.js, PHP, Java and C#. The language does not matter; the string concatenation does. If you find a query built with +, an f-string or a template literal that includes user input, you have found the bug.
Example 1: login bypass with OR 1=1
An attacker enters ' OR '1'='1 as the username, and the login query becomes a check that is always true. The database returns a user row without any valid password.
Start with the intended query:
SELECT * FROM users WHERE username = 'alice' AND password = 'secret123'
Now the attacker submits the username admin' OR '1'='1 and any password. The query becomes:
SELECT * FROM users WHERE username = 'admin' OR '1'='1' AND password = 'whatever'
Because '1'='1' is always true, the WHERE clause matches rows it should never match. Depending on how the application reads the result, the attacker logs in as the first user returned — often the admin account. OWASP's own worked example uses the same trick with name' OR 'a'='a in an item search, where it returns every item in the table regardless of owner.
A shorter variant is admin' --. The -- turns the rest of the query into a comment, so the password check is never evaluated at all:
SELECT * FROM users WHERE username = 'admin' --' AND password = ''
Example 2: stealing data with UNION SELECT
If the application displays query results, an attacker can append a UNION SELECT to pull data from a completely different table. This turns a product page into a window into the users table.
Suppose a product page runs:
SELECT name, price FROM products WHERE id = '1'
The attacker sends the id 1' UNION SELECT username, password FROM users --. The database runs:
SELECT name, price FROM products WHERE id = '1' UNION SELECT username, password FROM users --'
Usernames appear where product names should be, and password hashes where prices should be. The attack only works if the injected query returns the same number of columns, with compatible types, as the original — so attackers first probe with ORDER BY or UNION SELECT NULL, NULL to learn the column count. You can read more about how attackers find these flaws in our guide to spear phishing, which often starts with credentials stolen this way.
Example 3: error-based injection
When an application shows database error messages, an attacker can make the database put stolen data inside the error itself. The error becomes the exfiltration channel.
A common payload forces a type-conversion error that includes a value from another table. For example, in SQL Server, CONVERT(int, (SELECT TOP 1 username FROM users)) fails with an error message containing the username, because the database tries to convert that text into a number and reports the value it could not convert.
The fix for this one is partly operational: production applications should never show raw database errors to users. But hiding errors only removes the channel — the underlying injection must still be fixed with parameterized queries, or the attacker will switch to a blind technique.
Example 4: blind SQL injection, one character at a time
Blind SQL injection works even when the application returns no data and no errors. The attacker asks the database a series of true-or-false questions and watches whether the page changes.
Imagine a login page that says "user not found" for one outcome and "wrong password" for another. The attacker submits:
admin' AND SUBSTRING(password,1,1)='a' --
If the response changes, the first character of the admin password is a. If not, the attacker tries b, then c, and so on. Repeating the process for each character position recovers the whole value — slowly, but automatically, with a script sending hundreds of requests.
This is why "the app does not display database output" is never a defense. A difference in page content, a redirect, or even a missing image is enough signal for an automated attack.
Example 5: time-based blind injection
When even true-or-false differences are suppressed, attackers use time as the signal. They make the database pause when a guess is correct, and measure how long the response takes.
In MySQL, the payload looks like this:
admin' AND IF(SUBSTRING(password,1,1)='a', SLEEP(5), 0) --
If the response takes five seconds, the first character is a. In SQL Server the equivalent is WAITFOR DELAY '0:0:5'. The technique is slow — a full password can take thousands of requests — but it works against applications that return identical pages for every input.
Time-based injection is also a useful detection signal for defenders: a login endpoint that sometimes takes exactly five seconds longer than usual is worth investigating in your logs.
Example 6: stacked queries that delete data
Some databases allow several SQL statements in one request, separated by semicolons. An attacker can close the original query and append a destructive one of their own.
OWASP documents this exact case. With the username hacker and the item name name'); DELETE FROM items; --, the application runs:
SELECT * FROM items WHERE owner = 'hacker' AND itemname = 'name';DELETE FROM items;
The trailing -- comments out the leftover quote. The classic classroom version is '; DROP TABLE users; --. Not every database allows stacked queries — Oracle, for example, rejects them in this form — but where they are allowed, the damage is immediate and total. Backups are the only recovery.
Example 7: second-order injection
Second-order injection is the sneakiest variant: the malicious input is stored safely, then used unsafely later. The attack succeeds in a completely different place from where the payload was entered.
Consider a registration form that stores usernames with a parameterized query — safe so far. Later, an admin report builds a query by concatenating the stored username. An attacker who registered as admin' -- now triggers injection when the admin views the report.
This is why code review must follow data, not just entry points. Every place a value reaches a query matters, including values read back from the database, from files, or from another service. Stored procedures do not save you here either: OWASP shows a PL/SQL procedure that builds a query by concatenation and is vulnerable to the same attack.
How do the types of SQL injection compare?
Injection is usually grouped by how the attacker gets information out. In-band attacks see results directly, blind attacks infer them, and out-of-band attacks use a separate channel.
| Type | How data comes back | Example payload | Speed |
|---|---|---|---|
| In-band: UNION-based | In the normal page response | 1' UNION SELECT username, password FROM users -- | Fast |
| In-band: error-based | Inside a database error message | Type-conversion error revealing a value | Fast |
| Blind: boolean-based | True/false differences in the page | ' AND SUBSTRING(password,1,1)='a' -- | Slow |
| Blind: time-based | Response delay | ' AND IF(..., SLEEP(5), 0) -- | Very slow |
| Out-of-band | DNS lookup or HTTP request | Database function that fetches a URL | Medium |
| Second-order | Later, when stored data is reused | Payload stored at registration | Delayed |
Out-of-band injection deserves a note: functions such as Oracle's UTL_HTTP or SQL Server's xp_cmdshell can make the database server itself send data out, for example by triggering a DNS lookup for a subdomain containing the stolen value. It is rarer, but it bypasses applications that return nothing at all.
What damage can SQL injection cause?
The impact goes far beyond a leaked table. OWASP lists spoofed identity, tampered data, voided transactions, changed balances, complete disclosure of all data on the system, destroyed data, and full database-server administration.
In practice, a single injection point can lead to:
- Account takeover — logging in as any user, including administrators.
- Full data theft — customer records, passwords, payment details and internal documents.
- Data destruction — deleting or corrupting tables, as in Example 6.
- Server compromise — reading files from the database host, or running operating-system commands where the database allows it.
- A foothold for ransomware — stolen credentials and internal access are exactly what ransomware operators buy and use.
That is why injection has stayed in the OWASP Top 10 since 2003. It is an old flaw, but the payoff for attackers has only grown as databases hold more valuable data.
How do you fix SQL injection?
The fix is to never concatenate user input into SQL. Use parameterized queries, also called prepared statements, so the query structure and the data travel separately.
In Node.js with PostgreSQL, the safe version is:
await db.query('SELECT * FROM users WHERE email = $1', [email])
In Java, OWASP's safe example uses a PreparedStatement with ? placeholders and setString for each value. ORMs such as SQLAlchemy and Prisma parameterize automatically when you use their query APIs — but raw query methods in those same tools are still vulnerable if you concatenate into them.
What does not work on its own:
- Escaping quotes — easy to miss a case, and some encodings bypass it.
- Blocklists of words such as
DROPorUNION— attackers rephrase, encode or split payloads around them. - Stored procedures — safe only if they use parameters internally; a procedure that concatenates is still vulnerable.
- A WAF alone — useful as a layer, but bypassable, as OWASP's WAF-bypass guidance shows.
Layer the fix: parameterized queries everywhere, a database account with only the permissions the application needs, input validation on an allow-list basis, and no raw database errors shown to users. OWASP's SQL Injection Prevention Cheat Sheet sets out the same defense-in-depth order.
Then test with a scanner such as OWASP ZAP or sqlmap against a staging copy — never against production — and check your site's headers with our free security headers checker.
How do you test for SQL injection?
Test deliberately, in a staging environment, with permission. Never test a system you do not own or have written authorization to test.
- Find every input — form fields, URL parameters, headers, cookies and API fields.
- Try a single quote — enter
'and look for a database error or a changed page. - Try a true/false pair —
' AND '1'='1versus' AND '1'='2— and compare the responses. - Probe column counts with
ORDER BYif a UNION attack looks possible. - Automate carefully with OWASP ZAP or sqlmap, pointed at staging only.
- Fix, then retest — confirm the same payloads now return normal, safe behavior.
For a broader defense checklist, our small business cybersecurity checklist covers patching, backups and access control alongside application security.
The bottom line
SQL injection is a solved problem with an unsolved habit: building queries by gluing strings together. Every example in this article — login bypass, UNION theft, blind extraction, stacked deletes — disappears when the query structure and the data travel separately.
Audit your code for concatenated queries, replace them with parameterized statements, and give the database account the fewest permissions it needs. Check the rest of your site's defenses with the free SSL checker while you are at it.
Frequently asked questions
What is SQL injection in simple terms?
SQL injection is an attack where someone types database commands into a website's input box instead of normal text. Because the application pastes that input straight into a database query, the database runs the attacker's commands as if they were part of the program.
What is the most famous SQL injection example?
The classic example is entering admin' OR '1'='1 in a login form. It turns the login query's check into a condition that is always true, so the database returns the admin account without a valid password.
Can SQL injection delete a database?
Yes, on databases that allow several statements in one request. Input such as '; DROP TABLE users; -- can append a command that deletes a table. Even where that is blocked, attackers can still read, change or delete data through the original query.
What is the difference between in-band and blind SQL injection?
In-band SQL injection returns stolen data directly in the application's normal response, for example through a UNION query or an error message. Blind SQL injection returns no data, so the attacker infers it from true-or-false differences in the page or from response delays.
Does SQL injection still happen in 2026?
Yes. Injection has been in the OWASP Top 10 since the list began in 2003, and it remains common because older code, forgotten internal tools and third-party components still build queries by concatenating input. Modern frameworks make the fix easy, but only if developers use them.
How do you fix SQL injection?
Use parameterized queries, also called prepared statements, everywhere user input reaches the database. The query structure is sent separately from the data, so input can never be interpreted as SQL. Add least-privilege database accounts and input validation as extra layers.
Can a firewall stop SQL injection?
A web application firewall can block many known attack patterns, but it is not a reliable fix on its own. Attackers encode and rephrase payloads to bypass filters, so a WAF should sit in front of parameterized queries, not replace them.
Is SQL injection the same as cross-site scripting?
No. SQL injection targets the database behind a website by injecting SQL commands. Cross-site scripting targets other users' browsers by injecting JavaScript. Both come from trusting user input, but they attack different parts of the system.
Sources
The engineers and analysts who build Cysoro's domain scanner, email-authentication checks and free security tools. We test what we write about every day — SPF, DKIM, DMARC, certificates, look-alike domains and phishing — and check each guide against the relevant standards, government guidance and vendor documentation.
Checked against OWASP's SQL injection page and SQL Injection Prevention Cheat Sheet.
How we write and fact-check →