Security operations

SQL Injection Cheat Sheet: Types, Payloads, Fixes and Tests

SQL injection is one of the oldest web vulnerabilities — and still one of the most dangerous. This cheat sheet covers every type, the payloads attackers use, and the fixes that actually work.

Cysoro Security TeamPublished · 8 min read
SECURITY OPERATIONS SQL injection cheat sheet Types, payloads, detection — and the one fix that stops them all. admin' OR '1'='1vulnerable input WHERE user = ?parameterized — safe 4 types, 1 fix parameterize every query OWASP A05:2025 — Injection CYSORO
Quick answer

SQL injection happens when untrusted input becomes part of a database query and changes its logic. The fix is parameterized queries: define the SQL structure separately from its data values and bind the values through the database API. That single control stops classic, union-based, blind and second-order injection.

Key takeaways

  • SQL injection is untrusted input changing a query's logic — parameterized queries stop all four types.
  • Union-based and error-based attacks steal data fast; blind attacks are slower but just as dangerous.
  • Least privilege, allow-lists for identifiers, and testing in CI catch what parameterization alone cannot.

SQL injection is the oldest trick in web security, and it still works. An attacker types a fragment of database code into a login form, a search box or an API field — and if the application stitches that input into its query, the database obeys the attacker instead of the application.

What is SQL injection?

SQL injection is an attack in which untrusted data becomes part of a database query and changes the query's logic. The application meant to ask "find the user named X"; the attacker makes it ask "find the user named X — or anyone at all".

The root cause is simple: the application builds a query by joining strings together, mixing code and data in one string. The database cannot tell which parts were meant as instructions and which were meant as data. OWASP's SQL Injection Prevention Cheat Sheet puts it plainly: define the SQL structure separately from its data values, then bind those values through the database API.

Injection is category A05 in the OWASP Top 10:2025. It has slid down the list as frameworks improved, but that is not the same as solved — the unsafe path is still one line of code away in every language.

What does vulnerable code look like?

Almost every SQL injection flaw looks the same: a query built with string concatenation. Here is the classic example, in Python, and the safe version next to it.

VULNERABLE — never do this query = f"SELECT * FROM usersWHERE username = '{user}'"cursor.execute(query)# input becomes part of the SQL Input: admin' OR '1'='1 — logs inas the first user in the table. SAFE — parameterized query query = "SELECT * FROM usersWHERE username = %s"cursor.execute(query, (user,))# value is data, never code The same input is treated as aliteral username — no match, no login. The placeholder (%s, ?, :name) is not string formatting — the driver binds the value separately.
Vulnerable string concatenation versus a parameterized query. Illustration by Cysoro.

The Java version is the same pattern. The unsafe form concatenates the customer name into the query string; the safe form uses a PreparedStatement with a ? placeholder and setString(1, customerName). An input such as tom' or '1'='1 is then treated as the literal username to match, not as a condition added to the query.

The critical detail: the placeholder is not string formatting. You hand the query and the values to the driver separately, and the driver keeps your data strictly as data. The moment you use an f-string, .format() or + to assemble SQL, that is the bug.

What are the four types of SQL injection?

All four types share one root cause — input treated as SQL — but they behave differently, and that changes how you detect them. Learn to recognize all four, because a test that only checks for visible data theft will miss the quiet ones.

TypeHow it worksWhat the attacker seesSpeed
Classic (in-band)Injected code changes the query; results appear in the pageData directly, e.g. extra rows or an error messageFast
Union-basedUNION SELECT appends a second query to the firstData from other tables in the normal responseFast
Error-basedMalformed input forces the database to leak details in errorsTable names, types and values inside error textFast
BlindNo data returned; attacker asks true/false questionsOnly page changes, timing or delaysSlow

Classic (in-band) injection

The attacker changes the query and sees the result in the application's normal response. The login bypass admin' OR '1'='1 is the textbook case: the OR '1'='1' makes the WHERE clause always true, so the query returns the first user row and the application logs the attacker in.

Union-based injection

The attacker appends UNION SELECT to pull data from another table into the same result set. For example, ' UNION SELECT username, password FROM users -- returns every username and password alongside the page's normal results. The -- comments out the rest of the original query. This is how large credential dumps start.

Error-based injection

The attacker crafts input that makes the database throw an error containing useful information: table names, column types, even values. Verbose database errors in production are a gift to attackers — one more reason to show users a generic error page and log the details server-side.

Blind injection

The application returns no data and no useful error, but it still runs the injected SQL. The attacker asks yes/no questions and watches the response: ' AND 1=1 -- loads the page normally, ' AND 1=2 -- changes it.

Time-based blind injection is slower still: ' AND SLEEP(5) -- delays the response by five seconds if the injection works. A SOC analyst once traced a breach to a blind time-based injection in a reporting endpoint that took weeks to detect because the logs looked normal.

There is also second-order injection: the payload is stored safely — in a username or a comment — and fires later, when a different query reads it back without parameterizing. Parameterize every query, including ones that read your own data.

SQL injection payloads cheat sheet

These are the payloads testers use to confirm a vulnerability. Use them only against systems you own or have written permission to test. Each one probes a different behavior.

GoalPayloadWhat a hit looks like
Detect the flaw'Database error, or page behaves differently
Login bypassadmin' OR '1'='1Logged in without the password
Login bypass (comment)admin' --Password check is commented out
Union data theft' UNION SELECT username, password FROM users --Extra rows appear in the response
Boolean blind test' AND 1=1 -- vs ' AND 1=2 --Page differs between the two
Time-based blind test' AND SLEEP(5) --Response delayed about 5 seconds
Find column count' ORDER BY 3 --Error when the number exceeds the columns
List tables (MySQL)' UNION SELECT table_name, NULL FROM information_schema.tables --Table names in the response

Two notes on using this table. First, syntax varies by database: MySQL uses SLEEP(), SQL Server uses WAITFOR DELAY, and comment markers differ. Second, a failed payload proves nothing — a well-built application with parameterized queries will simply treat every one of these as a literal string and return no match.

How do you prevent SQL injection?

Prevention has one primary defense and several supporting ones. The primary defense stops the attack; the others limit the damage if a flaw slips through. Never swap them around — input validation and escaping are not substitutes for parameterization.

Prevention, in order of importance 1Parameterized queriesevery data value, every query — the fix that stops all four types 2Allow-list for identifierstable names, column names, sort direction — map input to fixed values 3Least privilegethe app database user can read and write only what it needs — no DROP, no admin tables 4Validate input, hide errorstype and range checks; generic error pages; log details server-side only Escaping user input by hand is error-prone and strongly discouraged by OWASP.
Four layers of SQL injection prevention, in priority order. Illustration by Cysoro.

1. Parameterized queries (the primary defense)

Use parameterized queries for every dynamic data value. OWASP's Query Parameterization Cheat Sheet shows the pattern in Java, .NET, Ruby, PHP, Perl, Rust and more: Java uses PreparedStatement with ?, .NET uses SqlCommand with @CustomerId, PHP uses PDO with bindParam(), Python drivers use %s or $1. Make sure the parameterization happens server-side — some client-side libraries only build queries with concatenation before sending them.

2. Allow-lists for identifiers

Table names, column names and sort order cannot be parameterized, because they are part of the query structure. Map user choices to a strict allow-list of fixed, application-owned values instead: if the user picks name or date, look it up in a list you wrote, and reject anything else.

3. Least privilege

Give the application's database account only the permissions it needs. If injection ever succeeds, a read-only account on one schema cannot drop tables or read the admin database. Separate accounts for migrations and for the running application make this easy.

4. Stored procedures — with a caveat

Stored procedures are safe when they use static SQL with parameters. But binding procedure arguments protects only the call — if the procedure builds dynamic SQL inside itself by concatenating its inputs, the injection moves inside the database. Use static SQL or bind values in the internal dynamic queries too.

5. ORMs, used correctly

ORMs like the Django ORM and SQLAlchemy parameterize queries for you, which is a big reason injection has dropped down the OWASP list. Stay on the safe path: the moment you reach for raw SQL or an unsafe query method, you are responsible for parameterizing again. Review every raw query in code review.

How do you test for SQL injection?

Testing belongs in the pipeline, not in a once-a-year penetration test. A simple routine catches most flaws before they ship.

  1. Manual probe. Put a single quote in every input — forms, URL parameters, API fields, cookies — and watch for database errors or changed behavior.
  2. Boolean and time tests. Try ' AND 1=1 -- against ' AND 1=2 --, then a time-based payload. A difference in response means the input reaches the query.
  3. Automated scan. Run OWASP ZAP or a similar scanner against a staging environment in CI. Review findings by hand; scanners produce false positives.
  4. Code review. Search the codebase for string concatenation near SQL: f-strings, .format(), + next to SELECT, execute(. Every hit gets a second look.
  5. Retest after fixes. A fix that parameterizes one query but leaves the reporting endpoint open is not a fix. Re-run the same payloads.

Also check your public-facing posture: run our free security headers checker against your site as part of the same routine.

Our SSL checker belongs in the same routine. Neither tool tests for SQL injection, but they catch the misconfigurations that usually sit next to it.

Common mistakes that keep SQL injection alive

Teams that know the fix still ship the flaw. These are the patterns that cause it.

  • Escaping instead of parameterizing. Hand-written escaping misses edge cases in every database dialect. OWASP strongly discourages relying on it.
  • Parameterizing only the login form. Search boxes, filters, sort parameters and reporting endpoints get the same treatment — or they become the way in.
  • Trusting stored data. Second-order injection fires from data already in the database. Parameterize queries that read stored values too.
  • Concatenating identifiers. Building ORDER BY {user_input} directly is injection, even if every value is parameterized. Use an allow-list.
  • Verbose errors in production. A database error message that names tables and columns hands the attacker a map. Show users a generic page.
  • Over-privileged database accounts. An application account that can drop tables turns a read-only flaw into a destructive one.

The bottom line

SQL injection has one root cause and one primary fix. Keep data and code separate with parameterized queries, use allow-lists for identifiers, and give the database account the least privilege it needs. Everything else is defense in depth.

If you maintain a web application, search your codebase for concatenated SQL today — it takes an afternoon, and it is the highest-value security check most small teams can run. For the rest of your site's posture, our website security platform covers the headers, certificates and monitoring that keep the basics from drifting.

Frequently asked questions

What is SQL injection in simple terms?

SQL injection is an attack where someone types database commands into a form field, URL or API input, and the application runs them as part of its database query. The attacker can then read, change or delete data they were never supposed to see.

What is the most common SQL injection payload?

The classic test payload is a single quote followed by OR 1=1, for example admin' OR '1'='1. It closes the original string and adds a condition that is always true, which can log the attacker in as the first user in the table.

How do you prevent SQL injection?

Use parameterized queries for every data value, and a strict allow-list for anything that cannot be parameterized, such as table names, column names and sort direction. Add least-privilege database accounts and input validation as extra layers, not as replacements.

Can an ORM prevent SQL injection?

Yes, if you stay on its safe path. ORMs such as the Django ORM and SQLAlchemy parameterize queries for you. The protection disappears the moment you use raw SQL, string formatting or an unsafe query method inside the ORM.

Is SQL injection still a problem in 2026?

Yes. Injection is category A05 in the OWASP Top 10:2025, and SQL injection remains the most common form. Frameworks made the safe path easy, but string concatenation is still one keystroke away in every language.

What is the difference between SQL injection and XSS?

SQL injection targets the database: the attacker injects SQL into a query. Cross-site scripting targets the browser: the attacker injects JavaScript into a page other users view. Both come from the same root cause — untrusted input treated as code — but they attack different systems.

Can SQL injection happen through an API?

Yes. Any input that reaches a query can carry injection, including JSON fields, headers, cookies and values read back from the database itself. Second-order injection hides in stored data and fires later, in a different query.

How do you test for SQL injection?

Start with a single quote in each input and watch for database errors or changed behavior, then test boolean and time-based payloads. For real coverage, run an automated scanner such as OWASP ZAP in CI and review the findings by hand, since scanners produce false positives.

Sources

  1. OWASP — SQL Injection Prevention Cheat Sheet
  2. OWASP — Query Parameterization Cheat Sheet
  3. OWASP — Top 10:2025
  4. PortSwigger Web Security Academy — SQL injection
Written & fact-checked byCysoro Security Team

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.

  • Email authentication
  • Phishing & BEC
  • Domain & DNS security
  • Small-business security

Checked against the OWASP SQL Injection Prevention and Query Parameterization cheat sheets and PortSwigger's Web Security Academy.

How we write and fact-check →

Free tools for this topic

No account needed.

See where your domain stands

Free for up to 3 domains. No card, no installs.

Start free