00->1
Learning pathStep 47 of 62Web application attacks and the OWASP Top 10 ← All writeups

SQL Injection, Explained

If you are reading this, you have probably seen "SQLi" at the top of every web security list and you want to understand what really goes wrong inside the application, why the classic ' OR 1=1-- works, and how developers stop it.

By the end you will be able to explain what SQL injection is, read a vulnerable query and see the flaw, describe the main types, recognise how testers find it, and write the correct fix. It is one part of the Injection category in the OWASP Top 10, so read that overview first if the terms are new. Every technique here is shown for understanding and for practice on labs you own or are allowed to test.


1. What SQL injection is

Most web applications keep their data (users, products, orders) in a database, and talk to it in SQL (Structured Query Language). A SQL command to list products might be:

SELECT * FROM products WHERE category = 'Gifts' AND released = 1

That means: "give me every product in the Gifts category that has been released."

The application does not hard-code the category. It takes it from the visitor, for example from the URL …/products?category=Gifts, and builds the SQL command around it. SQL injection (SQLi) is a flaw where that input is not kept separate from the command, so a visitor can change the meaning of the command instead of just supplying a value.

PortSwigger's definition: SQL injection is a web security vulnerability that allows an attacker to interfere with the queries that an application makes to its database, which can let the attacker view, modify or delete data they should not be able to.

The one idea behind it

The database receives one string of text. It cannot tell which part the developer wrote (the code) and which part the visitor typed (the data). If the visitor's text is simply glued into the command, the database may read part of it as code. All injection flaws, in SQL or elsewhere, are the same mistake: mixing code and data in one string.


2. The classic example

Here is vulnerable code (Python, but the pattern is the same in any language):

category = request.args["category"]          # whatever the visitor sent
query = "SELECT * FROM products WHERE category = '" + category + "' AND released = 1"
rows = db.execute(query)

For category=Gifts, the query is exactly as intended. Now the visitor sends this value instead (shown here without URL encoding):

Gifts' OR 1=1--

The code glues it in, and the database receives:

SELECT * FROM products WHERE category = 'Gifts' OR 1=1--' AND released = 1

Read it piece by piece:

Part What it does
' after Gifts Closes the string the developer opened, so the rest is read as SQL
OR 1=1 Adds a condition that is always true, so every row matches
-- Starts a comment, so the database ignores the rest, including AND released = 1

The result: the page shows all products, including ones that were not released. This is PortSwigger's standard example of retrieving hidden data. (Comment syntax differs between databases: --, # and /* … */ are all used. MySQL, for instance, needs a space after --.)

Subverting a login

The same trick can change a login check. The application builds:

SELECT * FROM users WHERE username = 'wiener' AND password = 'secret'

If an attacker enters administrator'-- as the username, the query becomes:

SELECT * FROM users WHERE username = 'administrator'--' AND password = ''

The comment removes the password check, so the database returns the administrator's row and the application logs the attacker in as the administrator, without a password. Real applications that store hashed passwords usually compare in a different way, but the principle is the same: input that changes the logic of the query.


3. The types of SQL injection

Type How the attacker gets information Typical sign
In-band: error-based The database's error message appears on the page and leaks details Raw database errors in the response
In-band: UNION-based A second SELECT is appended so its results are shown together with the normal results Data from other tables appears in the page
Blind: boolean Nothing from the database is shown, but the page behaves differently when a condition is true or false Content appears or disappears
Blind: time-based The attacker makes the database wait when a condition is true, and measures the delay Response takes noticeably longer
Out-of-band The database is made to send data to a server the attacker controls, via DNS or HTTP Unexpected outbound network requests from the database server
Second-order Input is stored safely first, then used unsafely later in a different query The bug appears in a different page from where the input was entered

In-band attacks use the same channel to attack and to read the result, and are the easiest. A UNION attack works because SQL lets you combine two queries; for it to work, the added query must return the same number of columns, with compatible types, as the original.

Blind attacks are slower but work when the page shows no data at all. Testers detect them by sending conditions that are true and false (for example OR 1=1 and OR 1=2) and comparing the responses, or by asking the database to pause. The delay function depends on the database, for example SLEEP() in MySQL, pg_sleep() in PostgreSQL and WAITFOR DELAY in Microsoft SQL Server.

Second-order attacks happen when a developer assumes "this value came from our own database, so it is safe." Data that was saved earlier is only as safe as the check that happened when it went in, so it must be handled with the same care on the way out.


4. What an attacker can do with it

Impact How
Read data they should not see Passwords, personal data, card details, other users' records
Bypass authentication Log in as another user, including an administrator
Change or delete data Alter prices, balances, accounts, or wipe tables
Gain a foothold In some setups, features of the database or its account permissions allow reaching the operating system or other systems
Persistent access PortSwigger notes a successful attack can give a backdoor into the organization's systems

Beyond the technical harm come reputation damage and regulatory fines.

A real case: TalkTalk, 2015

In October 2015 the UK telecoms company TalkTalk was breached by an SQL injection attack. According to the UK Information Commissioner's Office (ICO), the attacker accessed the personal data of 156,959 customers (names, addresses, dates of birth, phone numbers and email addresses), and in 15,656 of those cases also had bank account numbers and sort codes. The ICO called SQL injection "a common type of cyber attack that has been well-understood for more than ten years". Its investigation found that the database software was outdated and affected by a bug for which a fix had been available for over three and a half years, and that there had been two earlier SQL injection attacks on 17 July 2015 and on 2 to 3 September 2015, but TalkTalk "did not take any action". It issued its biggest ever fine at that time: £400,000.

The lessons are plain: a well-known flaw type, outdated software, and warning signs that nobody acted on.


5. How testers find it

A tester (with permission) looks at every input that might reach a database: URL parameters, form fields, headers, cookies, JSON values.

  1. Submit a single quote ' and look for a database error or a change in behaviour.
  2. Submit true and false conditions (OR 1=1, OR 1=2) and compare the responses.
  3. Submit time-delay payloads and watch the response time.
  4. Submit out-of-band payloads that trigger a network request to a server the tester controls.

PortSwigger's Burp Suite scanner automates these checks, and sqlmap is a well-known open-source tool that automates detection and exploitation. As always, they are for systems you own or have written permission to test.


6. How to fix it

The real fix: parameterized queries

A parameterized query (also called a prepared statement) sends the SQL structure to the database first, with placeholders where the values go, and sends the values separately. The database has already decided what is code, so the values can only ever be data, however strange they look.

Python (with sqlite3; other drivers use %s or named placeholders):

category = request.args["category"]
rows = db.execute(
    "SELECT * FROM products WHERE category = ? AND released = 1",
    (category,),
)

The same idea in other languages:

Language Safe pattern
Java PreparedStatement with ? placeholders and setString()
PHP PDO prepared statements with bound parameters
C# SqlCommand with Parameters.AddWithValue or typed parameters
Node.js The driver's parameterized query with $1 or ? placeholders

If the visitor sends Gifts' OR 1=1--, the database now looks for a product category literally named Gifts' OR 1=1--, finds none, and returns nothing.

Where parameters cannot be used

Placeholders work for values, not for table names, column names or ORDER BY clauses. If the application lets users choose a sort column, check the choice against an allowlist in your code (OWASP's cheat sheet recommends mapping the user's value to a legal name rather than using it directly, and notes that needing to do this at all can be a sign of poor design):

ALLOWED_SORTS = {"price", "name", "released"}
sort = request.args.get("sort", "name")
if sort not in ALLOWED_SORTS:
    sort = "name"
query = f"SELECT * FROM products ORDER BY {sort}"

Here the f-string is safe only because the value can only be one of three words that you wrote.

Defence in depth

These add safety but do not replace parameterized queries:

Control Why
Least privilege for the database account The web application's account should not be the database owner. If it can only read the tables it needs, the damage of a flaw is much smaller
Server-side input validation If a parameter must be a whole number, reject anything else. OWASP recommends positive (allowlist) validation
Do not show database errors to users Log them privately and show a generic message, which also removes error-based leaks
Use a mature ORM, with care Object-relational mappers parameterize for you, but any raw SQL string built with user input brings the flaw straight back
Safe stored procedures Safe only when the procedure itself does not build SQL by joining strings
Web application firewall (WAF) Can block common patterns and buy time, but attackers can often change their input to get around it. It is a net, not a fix
Monitoring and alerting Odd queries, error spikes and unusual data volumes should raise alerts (see OWASP A09)
Patching and inventory of old apps TalkTalk's database software was years behind on a fix

Why escaping is the wrong answer

Escaping means marking special characters such as the quote so the database treats them as plain text (for example by adding a backslash or doubling the quote). OWASP's SQL Injection Prevention Cheat Sheet marks this approach "strongly discouraged", calling it fragile compared to the other defences and saying it cannot guarantee that all SQL injection is prevented.


7. Practise it legally

Resource What you get
PortSwigger Web Security Academy: SQL injection Free, graded labs from "retrieve hidden data" to blind injection
OWASP Juice Shop A deliberately vulnerable shop with SQL injection challenges
OWASP WebGoat Guided lessons including SQL injection

Read the lab's code or description after you solve it: seeing why the query broke teaches you the fix.


8. Common mistakes

Myth The facts
"Escaping quotes makes it safe" Fragile and easy to get wrong. Use parameterized queries
"It only affects login forms" Any input that reaches a query: search boxes, filters, sort options, IDs in URLs, headers and cookies
"Hashed passwords stop SQL injection" Hashing protects stored passwords. It does not stop the injection, which can read or change other data
"We use an ORM, so we are immune" Only if you never put user input into raw SQL fragments
"A WAF fixes it" It blocks common attempts, not the underlying flaw
"Only old systems have this" It is still found in new code. It shows up whenever a developer builds a query by joining strings
"Input from our own database is safe" That is the second-order trap. Treat stored data as untrusted when it is used in a new query
"Blind means harmless" It is slower, not weaker. Data can still be extracted one answer at a time

Closing

SQL injection happens when user input is glued into a database command, so the database reads the visitor's text as part of the code. The attacker may then read data, log in without a password or change records. The fix is to keep code and data apart: use parameterized queries for values, allowlists for names and sort columns, a low-privilege database account, and never show database errors to users.

Keep these points:

  • Code and data must never share one string.
  • ' OR 1=1-- closes the string, makes the condition always true and comments out the rest.
  • Types: in-band (error, UNION), blind (boolean, time), out-of-band and second-order.
  • Parameterized queries are the fix; allowlists cover table names, column names and ORDER BY.
  • Escaping and WAFs are not substitutes.
  • Test only on labs or systems you have permission to test.