This tutorial teaches SQL injection fundamentals through hands-on labs and code review, covering how the vulnerability works, how to test for it safely in intentional practice environments, and how to fix it with parameterized queries. The article explains that SQL injection remains a present threat, ranking as category A05:2025 in OWASP's latest guidance, and demonstrates that the core fixβseparating query structure from data valuesβapplies consistently across detection and prevention workflows. Readers learn both offensive testing methodology and defensive code patterns they can apply immediately.
- The core mechanism: data escaping command contextSQL injection occurs when untrusted data becomes part of a query's SQL syntax because SQL statements mix data with commands in one string. When a developer concatenates user input directly into a query string using operations like `query = "SELECT * FROM users WHERE username = '" + user + "'"`, a single quote in the input can close the string prematurely, moving subsequent characters from data context into command context where the database interprets them as executable syntax. This quote-breaking mechanism is the same underlying flaw in all variantsβin-band, blind, and out-of-bandβonly the da
- Three SQL injection types by answer retrieval pathIn-band injection returns results directly in the page response, appearing either as database errors that expose the query structure or through UNION-based stacking where a second query's results display alongside normal ones. Blind injection shows no data or errors, so the tester infers the answer through behavior: boolean-based testing watches for page changes when conditions are true or false, and time-based testing measures response delays caused by deliberate database pauses. Out-of-band injection makes the database trigger an external network lookup or request to a server the tester cont
- Parameter binding separates structure from valuesThe primary defense is parameterized queries, which define the SQL structure first with placeholders (such as `?` markers), then pass values separately through the database API. In Python with SQLite, `cur.execute("SELECT * FROM users WHERE name = ? AND pw = ?", (name, pw))` treats the values as pure data regardless of their content, preventing any input from being parsed as SQL syntax. The article demonstrates with a local SQLite demo that the concatenated vulnerable query returns a row for `alice' --` even with a wrong password, while the parameterized version correctly returns an empty resu
- Parameters cannot defend keywords and identifiersParameterized queries protect data values but cannot stand for table names, column names, or SQL keywords like ASC and DESC. When a user selects a sort order, the article shows using a server-side allow-list dictionary that maps user input to fixed column namesβ`allowed = {"name": "name", "date": "created_at"}` and then `col = allowed.get(sort, "name")` before interpolating it into the query. This ensures only pre-approved values reach the query text, preventing injection through dynamic identifiers.
- Stored procedures and ORMs require code reviewNeither stored procedures nor Object-Relational Mappers provide automatic protection because both can execute dynamically built SQL. OWASP notes that concatenation inside stored procedures remains injectable, and ORMs like Hibernate leak the same vulnerability when developers use raw-query methods or build queries from strings. The article warns that binding protects the call but not dynamic SQL constructed before it, so code reviewers must search for raw query calls and string concatenation patterns even within supposedly safe abstractions.
- Detection workflow: map, probe, confirm, stopThe article presents a four-stage methodology for testers and code reviewers. Mapping identifies every input point: form fields, URL parameters, cookies, and headers visible in proxy history. Probing gently changes one parameter at a timeβadding a single quoteβand compares responses against baseline (status code, length, wording, timing). Confirming uses safe boolean or timing checks to verify behavior without extracting data. Stopping at proof means one repeatable, clear difference suffices; the article warns never to extract data you do not need. For code review, the same logic applies by se
- Testing requires legal authorization and isolated environmentsThe article emphasizes that probing a real system without written permission is illegal in many countries, even with good intent. Practice occurs only in intentionally vulnerable labs like SecurityElites' MiniMail or PortSwigger Web Security Academy, or on your own localhost. The article provides specific setup: a separate browser profile, an intercepting proxy (default 127.0.0.1:8080), and verification using curl or server checks. Never use real accounts, real customer data, or someone else's site; record timestamps for evidence. Timing checks on shared or real databases are forbidden; in lab
- Escaping quotes and WAFs are incomplete defensesThe article states that manual quote escaping is a common mistake because escaping rules differ between SQL dialects and are easy to get wrong; OWASP advises against it. Similarly, WAFs are presented as a safety net that may slow attackers, not a replacement for parameterized queries. Verbose error messages are explicitly called 'a gift to an attacker' because raw database errors expose the full query and reveal injection sits inside a single-quoted string. The article instructs that production systems should log errors server-side and return only generic user-facing messages.
Bottom line: SQL injection is prevented by defining query structure separately from values, then binding values through the database API using parameterized queries; this is the only complete fix for injection in data context. Verification requires retesting the same input against the patched code to confirm it is now treated as plain data, not executable syntax, and this same evidence-first discipline applies to both offensive testing in authorized labs and defensive code review in production systems.
β±οΈ 60 min Β· Beginner Β· 1 hands-on lab
Picture a login page on a practice app you are allowed to break. You type a single quote into the username box and the page throws a strange database error instead of a polite "wrong password". That small slip is how sql injection usually announces itself, and it tells you the developer glued your input straight into a query.
In this Tutorial I will walk you through exactly that, but only against the SecurityElites practice lab and your own machine. We will look at why the flaw exists, how in-band, blind and out-of-band variants differ, and how to test a login form safely.
Then we switch sides. I will show you how to spot injectable code in a review, fix it with parameterized queries, handle the parts parameters cannot cover, and retest to prove the hole is closed.
π― What You Will Be Able to Do
β Before You Start
- Basic understanding of how web forms and HTTP requests work
- Very basic SQL: SELECT, WHERE, AND, OR
- A browser, and optionally a web proxy such as Burp Suite
π In This Tutorial
- SQL injection in plain words: the direct answer
- What SQL injection is and how it works
- Threat model: what an attacker can reach
- Types of sql injection: in-band, blind and out-of-band
- Set up a safe, legal practice environment for sql injection
- Controlled demo: bypassing a vulnerable login
- Detection methodology for testers and reviewers
- Prevention: fix sql injection in the code
- Retest the fix and keep learning
- Your checklist
- What I want you to remember
- Questions people ask
SQL injection in plain words: the direct answer
I'll give you the short answer first, then we build it up. SQL injection happens when untrusted data becomes part of a query's SQL syntax [1]. The database cannot tell what the developer meant as a command and what the user typed as a value, so it runs all of it.
The main fix is just as short. Define the SQL structure separately from the data values, then bind the values through the database API [1]. This is called parameter binding. The user's input is only ever treated as a value, never as code.
This is not an old problem that has gone away. In the OWASP Top 10:2025, injection is category A05:2025, down from third place in the previous edition, and SQL injection sits inside it alongside NoSQL injection, OS command injection and XSS [8]. That Top 10 was released on 6 November 2025 [10]. In 2026, CISA added SQL injection flaws in Fortinet FortiClient EMS (CVE-2026-21643) and Metabase (CVE-2026-72898) to its Known Exploited Vulnerabilities catalog [15][17].
This page is part of our wider path. If you are new to the field, start with the ethical hacking roadmap to see where this skill fits.
What SQL injection is and how it works
Let me show you why this flaw exists. SQL statements mix data with commands in the same string [19]. A crafted input can leave the data context and enter the command context. That jump is the whole vulnerability.
Picture a login page. The developer builds the query by gluing the typed username and password into a string. Here is the vulnerable pattern in pseudo-code, which you will only ever see on your own machine or in a lab.
User input is pasted straight into the SQL text.
π§ Walking through the flaw
We will test this safely in a lab later. For now, understand the mechanism, because every type of sql injection is a variation on that quote breaking out of its context.
π§ Quick check
Threat model: what an attacker can reach
Now let's think about impact. What a successful sql injection can do depends on database features and privileges. OWASP lists reading data, modifying it, running administration operations such as shutting down the DBMS, and reading or writing files. In some cases it can run operating system commands [2].
So who is the attacker? Often anyone who can reach the page. The Metabase flaw let a remote attacker inject arbitrary SQL queries without authentication [17]. Entry points are any place the application takes input and uses it in a query: login and search forms, URL parameters, and also headers or cookies if the code uses them.
It is still in advisories because the mistake is easy to make. CISA's 2026 weekly bulletins list many new SQL injection flaws, several where user-controlled parameters were concatenated or interpolated into SQL without parameterization or escaping [18]. CISA also described this vulnerability type as a frequent attack vector for malicious actors when it added a Cisco Secure Email Gateway flaw [16]. CISA and the FBI have also called it a still-prevalent class of vulnerability [19].
It helps to keep it separate from its relatives. Here the interpreter is the database. In command injection the interpreter is the operating system shell, and in server-side template injection it is a template engine. Same root idea, different target.
Types of sql injection: in-band, blind and out-of-band
Here is the key point: sql injection is not one trick. It is a family of techniques, and the type you meet depends on what the application shows you back. Testers sort them by how the answer reaches you: in the same response, by inference, or through a separate channel. Let me walk you through each one at concept level, with no attack strings, so you know what you are looking for when we reach the lab.
π Words I just used
In-band is the easiest to spot. Two common forms exist. Error-based relies on the database error appearing in the page. UNION-based lets the tester append a second query so its results are displayed alongside the normal ones, for example in a product list.
Blind comes in two flavours. With boolean-based testing, you ask the database a true or false question and watch whether the page changes, perhaps a result appears or vanishes. With time-based testing, the page looks identical either way, so you ask the database to pause and measure how long the response takes.
Out-of-band is for cases where even timing is unreliable. The database is made to trigger an external lookup or request. The PortSwigger Web Security Academy path covers all of these, and its out-of-band labs need Burp Suite Pro features such as Collaborator. That is why I will not ask you to do them today.
π§ Quick check
Set up a safe, legal practice environment for sql injection
Before you type a single quote into anything, let me set the ground rules. Testing for sql injection against a system you do not own, and have no written permission to test, is illegal in many places, even if you only look. So we practise in two kinds of place only: intentionally vulnerable labs, and targets where the owner has explicitly authorised you in writing.
βοΈ Authorisation rules I follow
For practice, I point you to two places. The SecurityElites lab below is a mock webmail called MiniMail with a login page you can break safely. The free PortSwigger Web Security Academy offers a login bypass lab and a product-category filter lab, among many others.
Now prepare your tools. You need a browser and an intercepting proxy, which is a program that sits between the browser and the site so you can see and edit each request. Burp Suite is the usual choice, and the ethical hacking roadmap points you to the right tutorial. Set the browser to send traffic through the proxy, normally 127.0.0.1 on port 8080, then check that a request appears in the proxy history.
Start any simple web server on your own machine first, for example python3 -m http.server 8000. If curl says connection refused, start the proxy and check the listener port.
This is the lab we use for the demo next. Open it now and get comfortable before we test it together.
βΈ Load the MiniMail login page with your proxy running
βΈ Submit a normal wrong login and study the response in the proxy history
βΈ Note which fields the server receives and how the failure looks
βΈ Think about how the server might build its query from those two fields
What to notice: Whether the error message differs for a wrong username and a wrong password What the request looks like in the proxy, including method and parameters
I start a throwaway web server on my own machine so the proxy check has something to talk to.
The server prints a serving line, curl returns HTTP/1.0 200 OK, and ss shows a LISTEN entry on port 8080 once the proxy is running.
Controlled demo: bypassing a vulnerable login
I am going to run this test with you, step by step, against one place only: the SecurityElites practice lab called SQL Injection, Login Bypass. It is built to be vulnerable. Never repeat these steps on a real site unless you hold written permission from its owner. If you ever find a flaw in a live system you are not authorised to test, stop and report it through the owner's disclosure channel.
The lab app is called MiniMail. Its login page builds a SQL query by joining your username and password into a string. That is the textbook cause of sql injection, so it is a safe place to watch the flaw happen. I will show you the method and the reasoning, and leave the final step for you to work out.
Detection methodology for testers and reviewers
I want to give you a repeatable method for finding sql injection, because random poking wastes time and can break things. Everything here runs only against your own lab, a deliberately vulnerable practice app or localhost. Testing anything else needs written permission, and if you ever find a flaw in a real system you were not invited to test, report it through the owner's disclosure channel and stop there.
The method has four stages: map, probe, confirm, stop. It works the same whether you are a tester watching responses or a reviewer reading source code. For the wider picture of where this skill fits, see the ethical hacking roadmap.
- Map every input
- Probe for errors or differences
- Confirm with a safe check
- Stop at proof
- Write it up
π§ Tester workflow in your own lab
Reviewers have an easier job. Search the codebase for queries built from strings. Look for concatenation or interpolation next to SELECT, INSERT, UPDATE or DELETE, and check ORM raw-query calls and dynamic SQL inside stored procedures, since OWASP notes both can still be injectable.
These patterns give leads, not verdicts. Read each hit and ask whether user input reaches it.
CISA bulletins in 2026 describe many flaws where user-controlled parameters were concatenated or interpolated into SQL without parameterisation, so these greps match what real advisories describe. Once you have a finding, judge how serious it is and whether it is real. The broken access control and IDOR guide shows the same evidence-first habit.
π§ Quick check
Prevention: fix sql injection in the code
I want to show you the fix now, because understanding sql injection only pays off when you can close the hole. Everything here runs against your own machine or a deliberately vulnerable practice app. Never test a fix or a flaw on a system you do not have written permission to touch.
The main defence is simple to say. Define the SQL structure first, then pass the values separately so the database never mistakes them for syntax. OWASP calls this binding values through the database API [1], and the 2025 Top 10 also prefers a safe, parameterized interface [10].
π§ Fix the vulnerable login query
? markers. A marker can only stand for a data value, so the input stays data.Same query, but the second form sends the values to the database separately from the SQL text.
Notice what changed. The text of the query no longer depends on anything the user typed. That is the whole idea.
Stored procedures and ORMs are not magic. Binding protects the call, but dynamic SQL built by concatenation inside a procedure is still injectable. The same goes for ORMs such as Hibernate when you build queries from strings, so check raw query methods carefully.
Placeholders cannot stand for table names, column names or keywords like ASC and DESC. For a sort order, map the user's choice to a fixed value on the server.
Only values from your own dictionary reach the query text, so user input never does.
βοΈ Defence in depth around the fix
π§ Quick check
I build a tiny local database so you can run the vulnerable and fixed queries yourself and see the difference.
The concatenated query returns a row for a wrong password, while the parameterized query returns an empty list.
Retest the fix and keep learning
I want to close the loop now, because a finding is only finished when the fix is proven. We found the weakness in the lab, we looked at how parameter binding removes it, and now I will rerun the same test against the fixed version. Everything here runs only against the SecurityElites practice lab or your own localhost copy of a deliberately vulnerable app. Never repeat it on a system you do not own or have written permission to test.
The idea is simple. The same input that once changed the query logic should now be treated as a plain string, because the database receives the structure and the values separately. That is the whole point of defending against sql injection at the code level [1].

