Key Takeaways
- SQL injection has been documented since 1998 and still ranks second on MITRE’s 2025 list of the most dangerous software weaknesses, even though OWASP’s Top 10:2025 moved the Injection category from third to fifth place.
- Parameterized queries are the primary defense. Allow-list validation and escaping are backups, and least privilege caps the damage when a flaw slips through.
- The credential an application uses to reach its database sets the ceiling on what a successful injection can do, so short-lived, narrowly scoped database credentials belong in the defense plan.
- Read on for the attack workflow, a real zero-day case, six prevention techniques with code, and where secrets management fits.
Answer Capsule: What Is an SQL Injection Attack?
An SQL injection attack is an attack in which malicious SQL code is entered through an input field, URL parameter, or other request data so that it changes the query an application sends to its database. When the application builds that query by concatenating user input into a string, the database cannot tell the developer’s SQL from the attacker’s, and it runs both. Depending on the account the application uses, the result can be stolen records, altered or deleted data, or a foothold in the systems behind the database.
- The root cause is untrusted input concatenated into a query string.
- The primary fix is parameterized queries (prepared statements).
- Least privilege limits what a successful injection can reach.
SQL injection was first described in 1998, and in 2025 it still ranks second on MITRE’s list of the most dangerous software weaknesses. OWASP’s ranking tells a different story: the Injection category fell from third to fifth place in the 2025 Top 10. The two rankings can both be right, and the gap between them says something useful about where the risk sits today.
An SQL injection attack happens when an attacker sends SQL code as input and the application passes it to the database as part of a query, so the database runs the attacker’s instructions alongside the developer’s. In OWASP’s testing data, the Injection category logged more than 1.4 million occurrences, and SQL injection alone accounts for more than 14,000 CVEs.
This guide is written for developers and security engineers and covers how the attack works, how a real zero-day SQL injection played out, and six prevention techniques with code. The final section makes a point most prevention guides skip: the database credential your application holds decides how much damage a missed flaw can do.
Understanding SQL Injection Attacks
An SQL injection flaw lets an attacker insert malicious SQL into a query an application sends to its database. SQL injection flaws typically arise when developers build dynamic queries by string concatenation that includes user-supplied input. OWASP describes the broader class as an application flaw that allows untrusted user input to be sent to an interpreter, which then executes parts of that input as commands.
Vulnerability versus exploit. The vulnerability is the flaw: code that concatenates untrusted input into a query. The exploit is the attack that uses it. A vulnerable parameter can sit unexploited for years, and it only becomes an incident when someone finds it and sends a crafted request.
If an attack succeeds, the attacker can read sensitive information such as credit card details, passwords, and personal data. Depending on the privileges of the database account, they can also modify or delete records. When the account holds enough privilege and the database exposes features that run operating system commands, the attack can reach the underlying server.
A short history. The first public write-up appeared on December 25, 1998, in Phrack issue 54, where researcher Jeff Forristal (known as rain.forest.puppy) described attacks on web applications built on Microsoft IIS and SQL Server. According to NCC Group’s account of that history, the article never used the term SQL injection, which came later. OWASP’s Top 10 shows the category’s gradual descent from the number one spot it held through 2017, to third place in 2021 and fifth place in 2025.
Why the threat persists. The two rankings above measure different things. OWASP groups 37 weakness types into Injection, and it notes that the volume of cross-site scripting CVEs pulls the category’s average impact down, while SQL injection is low frequency but high impact. MITRE scores CWE-89 (SQL injection) on its own, and it rose one place to second in 2025. Three habits keep the flaw alive:
- The flaw is a coding habit, not a missing patch. Any code path that concatenates untrusted input can reintroduce it, including raw-query shortcuts inside ORMs.
- Databases hold what attackers want, so even a low-frequency flaw pays off.
- Commercial software ships the flaw too, as the MOVEit case below shows.
How SQL Injection Attacks Work
Every SQL injection follows the same chain: a request carries crafted input, the application builds a vulnerable query from it, and the database returns a response that serves the attacker. Attackers look for any parameter the application passes into a database interaction. OWASP lists parameters, headers, URLs, cookies, and JSON, SOAP, and XML data as inputs worth testing.
| Step | What Happens |
| 1. Request | The attacker submits crafted input in a search box, URL parameter, cookie, header, or API field. |
| 2. Vulnerable query | The application concatenates that input into a SQL string without separating data from code. |
| 3. Execution | The database parses the combined string as SQL and runs all of it. |
| 4. Response | The result, or a database error message, goes back to the attacker or changes data behind the scenes. |
Take an online bookstore where visitors search by title. The application builds its query like this:
| // Vulnerable: user input is concatenated into the query $title = $_GET[‘title’]; $query = “SELECT * FROM books WHERE title = ‘” . $title . “‘”; $result = mysqli_query($conn, $query); |
A visitor who searches for Harry Potter produces the query the developer intended:
| SELECT * FROM books WHERE title = ‘Harry Potter’; |
Now an attacker enters this instead:
| ‘ OR ‘1’=’1 |
The application builds this query:
| SELECT * FROM books WHERE title = ” OR ‘1’=’1′; |
The condition ‘1’=’1′ is always true, so the query returns every book in the table. A more destructive input adds a second statement:
| Input: ‘; DELETE FROM books; –Query: SELECT * FROM books WHERE title = ”; DELETE FROM books; –‘; |
The payload is two statements: a select that finds nothing, and a delete that empties the table. The double dash starts a SQL comment, which discards the leftover quote so the statement stays valid. In MySQL the double dash must be followed by a space. Stacked statements like this depend on the database and driver. OWASP notes that many database servers, including Microsoft SQL Server, allow multiple statements separated by semicolons, while Oracle does not, so the same payload can fail on one platform and succeed on another.
What attackers are after. Most attacks aim at one of three goals:
- Data exfiltration: a UNION SELECT injected after the original query can append rows from other tables, such as usernames and password hashes, when the column count and types match.
- Privilege escalation and authentication bypass: input such as admin’ — in a login form can comment out the password check, and tampering with data can grant a normal account higher rights.
- Denial: deleting or corrupting data, or running expensive queries, can take an application down.
Types of SQL Injection
Security teams usually sort SQL injection into three groups, based on how the attacker gets results back:
| Type | How It Works | Common Variants |
| In-band | The attacker launches the attack and reads the results through the same channel, usually the web page. | Error-based (reads database error messages), union-based (appends query results with UNION) |
| Blind (inferential) | The page shows no data or errors, so the attacker infers answers from changes in behavior. | Boolean-based (page differs for true and false conditions), time-based (response delay reveals the answer) |
| Out-of-band | The attacker sends results through a different channel, such as a DNS or HTTP request triggered by the database. | Depends on features enabled on the database server, so it is less common |
When Does an SQL Injection Vulnerability Become Zero-Day?
A vulnerability is a zero-day while the vendor or developer does not know about it and no patch exists. The name refers to the zero days they have had to fix it. An SQL injection attack becomes a zero-day attack when attackers exploit such a flaw before anyone has a fix. The usual timeline runs in three stages: someone discovers the flaw, someone exploits it, and the vendor learns of it and ships a patch. Defenders can only act after the third stage, so the gap between exploitation and the patch is the exposure window.
The 2023 attack on Progress Software’s MOVEit Transfer is the clearest recent example. CISA and the FBI reported that the Cl0p ransomware group began exploiting a previously unknown SQL injection vulnerability, CVE-2023-34362, in internet-facing MOVEit Transfer servers and used it to steal data from the underlying databases.
| Date | Event |
| May 27, 2023 | Cl0p begins exploiting an SQL injection flaw that the vendor and public do not yet know about (CISA and FBI). |
| May 31, 2023 | Progress publishes an advisory and begins releasing fixes; the flaw is tracked as CVE-2023-34362 (Akamai). |
| Following weeks | Two more SQL injection flaws in the same product, CVE-2023-35036 and CVE-2023-35708, are disclosed (Hive Pro threat advisory). |
Why early detection matters for development teams. Exploitation began four days before the advisory, and follow-up reviews of the same code turned up more injection flaws. For software your team writes, you are the vendor, so a flaw in your own code is a zero-day until you find it. Static and dynamic testing shorten that window. Logging helps too: database error messages in responses, queries containing unexpected UNION or comment markers, and response-time anomalies are the signals that blind and error-based probing leaves behind.
How to Prevent SQL Injection Attacks
OWASP’s SQL Injection Prevention Cheat Sheet ranks the defenses in a deliberate order: prepared statements first, then properly constructed stored procedures, then allow-list input validation, with escaping as a last resort and least privilege as an additional layer. The sections below follow that order and merge the original page’s two overlapping scanning and validation items into one. A web application firewall can block known payloads as a compensating control, but it filters traffic and leaves the flaw in place, and OWASP publishes guidance on bypassing WAFs with SQL injection. Fix the code first.
Prepared Statements & Parameterized Queries
A prepared statement defines the SQL structure first and passes each value separately, so the database never treats input as code. Prepared statements are the primary defense. Here is the bookstore query in PHP with PDO:
| $pdo = new PDO($dsn, $user, $pass, [ PDO::ATTR_EMULATE_PREPARES => false, // use native server-side prepares ]); $stmt = $pdo->prepare(‘SELECT * FROM books WHERE title = :title’); $stmt->execute([‘:title’ => $title]); $books = $stmt->fetchAll(); |
And the same query in Java with JDBC:
| String sql = “SELECT * FROM books WHERE title = ?”; try (PreparedStatement ps = connection.prepareStatement(sql)) { ps.setString(1, title); try (ResultSet rs = ps.executeQuery()) { // process results } } |
Make sure parameterization happens on the server. OWASP’s Query Parameterization Cheat Sheet warns that some client-side libraries build queries by string concatenation before sending them, which defeats the purpose. Parameters bind values only. Table names, column names, and keywords such as ASC and DESC cannot be bound, so map those to a fixed allow-list in code. Any speed difference from prepared statements depends on the database and driver, so choose them for the security guarantee. The OWASP cheat sheet covers other languages in depth.
Stored Procedures & ORM Safeguards
A stored procedure keeps the SQL inside the database and takes parameters from the application. OWASP treats a properly built procedure as equally effective as a prepared statement, with one condition: it must not build SQL dynamically. The OWASP Top 10 notes that a parameterized stored procedure can still be injectable if PL/SQL or T-SQL concatenates queries and data or runs hostile data with EXECUTE IMMEDIATE or exec(). Compare an unsafe and a safe T-SQL procedure:
| — Unsafe: dynamic SQL built from the parameter CREATE PROCEDURE FindBook @title NVARCHAR(200) AS EXEC(‘SELECT * FROM books WHERE title = ”’ + @title + ””); — Safe: the parameter is bound inside the query CREATE PROCEDURE FindBook @title NVARCHAR(200) AS SELECT * FROM books WHERE title = @title; |
ORMs parameterize by default for their standard query methods, but a raw query fragment bypasses that protection. OWASP’s example is a Hibernate Query Language call that concatenates a request parameter into the query string, which an input like ‘ OR custID IS NOT NULL OR custID=’ turns into a request for every account. Use this checklist when reviewing ORM code:
- Bind every value through the ORM’s parameter or query-builder API.
- Search the codebase for raw or native query methods and string-formatted queries, and review each one.
- Allow-list any column name or sort order that comes from user input.
- Review ORM search and filter parameters, since unsanitized values there can return extra sensitive records.
- Keep the ORM and database driver on supported versions.
Input Validation & Allow-Lists
An allow-list defines exactly what input is acceptable and rejects everything else. A deny-list tries to enumerate bad input, such as quotes or SQL keywords, and attackers routinely find variants it missed. A deny-list also rejects legitimate input like a surname with an apostrophe. A numeric ID field is the easy case:
| // PHP: accept only 1 to 10 digits, reject everything else if (!preg_match(‘/\A[0-9]{1,10}\z/’, $id)) { http_response_code(400); exit; } |
Validation is a supporting layer. OWASP’s Input Validation Cheat Sheet states that it should not be the primary defense against SQL injection, and the Top 10 adds that it is not a complete defense because many applications need special characters, such as text areas or mobile APIs. Use it to shrink the attack surface, and keep parameterized queries as the control that actually stops injection.
Escaping User Input
Escaping asks the database driver to neutralize special characters before they enter a query. OWASP’s Top 10 warns that it involves parsing and escaping complex strings, which makes it error-prone and fragile when the underlying system changes, and the SQL injection cheat sheet places it last. Treat it as a fallback for legacy code where parameterization is not yet possible.
| // Works only because the value sits inside quotes $title = mysqli_real_escape_string($conn, $_GET[‘title’]); $result = mysqli_query($conn, “SELECT * FROM books WHERE title = ‘$title'”); |
Escaping fails in non-string contexts. In the next query the value is a number with no quotes around it, so an attacker needs no quote character to break out:
| // Still injectable: id=1 OR 1=1 contains no characters to escape $id = mysqli_real_escape_string($conn, $_GET[‘id’]); $result = mysqli_query($conn, “SELECT * FROM books WHERE id = $id”); |
The same weakness applies to LIMIT clauses and identifiers, and OWASP notes that SQL structure such as table and column names cannot be escaped at all. Escaping functions differ by database:
| Database (PHP) | Escaping Function | Note |
| MySQL and MariaDB (mysqli) | mysqli_real_escape_string() | String values only, and only inside quotes |
| PostgreSQL (pgsql) | pg_escape_literal() | PHP documents it as preferred over pg_escape_string() |
| PostgreSQL identifiers | pg_escape_identifier() | For table and field names that must be dynamic |
| Other databases | Your driver’s quoting function | Check the driver documentation, and prefer bound parameters |
Enforcing Least Privilege
The principle of least privilege limits the damage of an injection that gets through. Give the application the narrowest database account that works, and use separate accounts for reading and writing. The MySQL example below gives the search feature read-only access to one table and gives the order feature write access to another, with no delete rights anywhere:
| CREATE USER ‘bookstore_reader’@’10.0.%’ IDENTIFIED BY ‘<password from your secrets manager>’; GRANT SELECT ON bookstore.books TO ‘bookstore_reader’@’10.0.%’; CREATE USER ‘bookstore_writer’@’10.0.%’ IDENTIFIED BY ‘<password from your secrets manager>’; GRANT SELECT, INSERT, UPDATE ON bookstore.orders TO ‘bookstore_writer’@’10.0.%’; |
With these grants, the search endpoint’s ‘ OR ‘1’=’1 payload still returns rows from books, but an injected DELETE FROM books fails with a permission error, and a UNION SELECT against a users table fails because the reader account has no rights on it. OWASP also warns that on Microsoft SQL Server, some stored-procedure setups push applications to run with the db_owner role, which removes this protection entirely.
A grant list only helps if the account’s password stays secret and the account is not shared across services. Static passwords that live in config files and pipelines are the weak point, and short-lived, scoped database credentials address it. The last section of this guide covers how.
Automated Code Scanning & SCA
OWASP recommends combining source code review with automated testing and adding static (SAST), dynamic (DAST), and interactive (IAST) tools to the CI/CD pipeline to find injection before release. Three tool types matter here, and they answer different questions:
| Tool Type | What It Examines | SQL Injection Use |
| SAST | Your source code | Flags unsafe patterns such as a query string built with + or string formatting from request data |
| SCA | Third-party libraries and frameworks | Flags known-vulnerable versions of your ORM, driver, or other dependencies; it does not read your own query code |
| DAST | The running application | Sends injection payloads to live endpoints; ZAP and sqlmap are common open-source options |
A SAST rule flags code like this on sight:
| String query = “SELECT * FROM books WHERE title = ‘” + request.getParameter(“title”) + “‘”; |
ZAP (formerly OWASP ZAP, now maintained as ZAP by Checkmarx) ships Docker scripts for CI use. ZAP’s baseline scan is passive only and will not find injection by probing. The full scan script runs an active scan. Point it at a staging environment, never production, because active payloads are real requests:
| docker run -t ghcr.io/zaproxy/zaproxy:stable zap-full-scan.py -t https://staging.example.com |
To fail the build on serious findings, pass the scan script a rules configuration file that sets the relevant rules to FAIL, so a critical injection result stops the pipeline instead of landing in a report nobody reads.
SQL Injection vs. Secrets Management Vulnerabilities
A secrets vulnerability is a weakness in how credentials are stored, shared, or retired: a hardcoded API key in source code, a database password in a config file or CI variable, or a static credential nobody has rotated in years. Hardcoded API keys and credentials left in pipelines are the common forms.
The two problems have different mechanics. SQL injection abuses how an application handles input at runtime. SQL injection needs an injectable parameter, and the injected query runs with the privileges of the application’s database account. A leaked secret needs no flaw in the application at all. The attacker signs in as the credential’s owner, and every defense in the previous section, including prepared statements, is irrelevant.
An earlier version of this page said the two issues do not directly influence each other. In practice they feed each other in three ways:
- Injection exposes secrets. A successful injection that can read tables reads whatever those tables hold, which often includes API keys, tokens, and password hashes.
- Secrets bypass injection defenses. A database credential found in a repository, log, or ticket gives direct access with no injection needed.
- Over-privileged credentials multiply the damage. If the application’s database account can read every table and change schema, a small injection becomes a full compromise, which is the least-privilege problem from the previous section.
For a look at how stolen credentials can turn a contained incident into a larger one, see Akeyless’s retrospective on the LastPass breach.
Akeyless approaches the credential side directly. For SQL databases such as MySQL, PostgreSQL, and Microsoft SQL Server, the platform’s database dynamic secrets connect to the database through the Gateway and generate a temporary, restricted account when an application asks for one, with the databases, tables, and permissions you define and a short TTL, then revoke it using the revocation statements you configure. The application holds no standing database password, and the pattern follows the logic of zero standing privileges. Dynamic credentials do not stop an injection, but they limit what an injected query can do and how long a stolen credential keeps working.
Cimpress, one of Akeyless’s customers, describes the operational effect on credentials in its case study. Conor Mancone, Principal Application Security Engineer at Cimpress, said: “We set Akeyless up 9 months ago, and we haven’t had to worry about credential rotation. We haven’t had to worry about credential leakage.” The deployment is not specific to SQL injection, but credential rotation and leakage are the secrets-side risks described above.
To go deeper, explore Akeyless’s secrets management platform and the dynamic secrets concept behind it.
Conclusion
An SQL injection attack turns a query built from untrusted input into a command the attacker controls. The consequences range from exposed records to altered data and, in the worst cases, access to the server behind the database. The most reliable prevention is to keep data and SQL separate with parameterized queries, then layer on safe stored procedures, allow-list validation, least privilege, and automated testing. Escaping belongs in legacy code as a stopgap.
Testing and patching never finish: scan every release, review raw queries when code changes, and treat the database credential as part of the defense. If you want to see how short-lived database credentials work in practice, schedule an Akeyless demo. For the wider pipeline picture, the guide to DevOps secrets management is a good next read.
FAQs
Below are quick answers to common SQL injection questions.
What Is an SQL Injection Attack?
An SQL injection attack is an attack in which malicious SQL code is entered through application input so that it manipulates the queries the application sends to its database.
How Can I Test My Website for SQL Injection?
Start with manual payloads in each input and watch for errors or changed results: a single quote, ‘ OR ‘1’=’1, and a boolean pair such as ‘ AND 1=1 — versus ‘ AND 1=2 –, plus time-delay payloads for blind cases. Then run an automated scanner such as ZAP or sqlmap. Test a staging copy with realistic data, never production, because active payloads can modify or delete records, and get written permission before testing any system you do not own.
Which Programming Languages Are Most Exposed to SQL Injection?
OWASP does not publish a risk ranking by programming language. Any language is exposed when queries are built by concatenating input, and OWASP says the concept is identical across all interpreters. Frameworks that parameterize by default lower the odds, but raw-query escape hatches inside those frameworks bring the risk back.
Can Prepared Statements Fully Eliminate SQL Injection?
Prepared statements stop injection through bound values but do not cover dynamic SQL built from user input elsewhere, such as table names, sort orders, or concatenation inside a stored procedure, and they do not fix a value that was stored safely and later concatenated into another query. Combine them with allow-list validation and least privilege so a missed case does less damage.
What Is the Difference Between SQL Injection and XSS?
SQL injection sends SQL to an application’s database to read or change data, while cross-site scripting injects script that runs in other users’ browsers. The first is stopped mainly with parameterized queries and least privilege, the second with context-aware output encoding.
Sources
OWASP, “A05:2025 Injection,” OWASP Top 10:2025
MITRE, “2025 CWE Top 25 Most Dangerous Software Weaknesses”
OWASP, “SQL Injection Prevention Cheat Sheet”
OWASP, “Query Parameterization Cheat Sheet”
OWASP, “Input Validation Cheat Sheet”
OWASP, “SQL Injection” (community attacks page)
Akamai, “MOVEit SQLi Zero-Day (CVE-2023-34362) Exploited by CL0P Ransomware Group”
NCC Group, “SQL Inference Attacks” (history of SQL injection)
ZAP, “Full Scan” (Docker documentation)