← All lessons Stage 3 · Lesson 1
25 min

SQL injection from first principles

Stage 3 · Lesson 1 · 25 minutes · Requires Stage 2


The one-line answer

SQL injection happens when user input is glued into a database query, letting an attacker change what the query does.

The boundary: Stage 3 is about real bug classes. Every technique here is practised only on PortSwigger's labs or OWASP Juice Shop on your own machine. Trying it on a real site — even "just to check" — can be an offence under the IT Act.


Why you should care

SQL injection (SQLi) is one of the oldest web bugs and still one of the most damaging. When it works, an attacker can often read the whole database — customer records, password hashes, orders — and sometimes change or delete it. Many of the largest data breaches in history started with SQLi.

It's also the clearest example of the single idea behind most of Stage 3: data being treated as code. Understand it here and XSS, command injection and others will make sense faster.


How it actually works

What a database query is

Most applications store data in a database — think of it as a set of spreadsheets called tables. A products table might look like:

idnamecategoryreleased
1Laptop standOffice1
2USB hubOffice1
3New gadgetOffice0

The application talks to the database in SQL (Structured Query Language). To show released office products, it might run:

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

Read it as English: "give me everything from the products table where the category is Office and it's released."

How the bug happens

The user picks a category from a URL: /products?category=Office. A careless developer builds the query by gluing the input into a string (Python example — recall Stage 1 Lesson 7):

query = "SELECT * FROM products WHERE category = '" + category + "' AND released = 1"

With normal input, it works. But the user controls category. Suppose they send:

Office'--

The glued query becomes:

SELECT * FROM products WHERE category = 'Office'--' AND released = 1
  • The ' closes the text value early.
  • -- starts a comment in SQL — everything after it is ignored.

So the AND released = 1 check disappears, and unreleased products show up. The user didn't just supply data — they changed the structure of the query.

The classic login example works the same way. A query like:

SELECT * FROM users WHERE username = 'INPUT' AND password = 'INPUT'

can be bent so the password check never runs. You'll do exactly this in a PortSwigger lab.

How you notice it (on an authorised target)

The first sign is usually that a single quote ' breaks something:

You sendYou seeSuggests
category=OfficeNormal pageBaseline
category=Office'500 error or broken pageThe quote broke the SQL syntax
category=Office''Normal page againTwo quotes = an escaped quote; syntax repaired

That pattern — one quote breaks it, two quotes fix it — is strong evidence the input reaches SQL unsafely. This is Lesson 2's "change one thing, observe one thing" in Repeater.

What an attacker can do

Depending on the database and the query, SQLi can let an attacker:

  • Read data they shouldn't — other users' details, password hashes (recall Stage 0 Lesson 6: hashes, not encryption).
  • Bypass logins.
  • Change or delete data.
  • In some setups, reach the underlying server.

The two broad categories

  • In-band SQLi — the results show up directly in the page. Easier to see, easier to exploit. (This lesson.)
  • Blind SQLi — the page doesn't show query results at all; the attacker infers information from yes/no differences or timing. (Lesson 2.)

See it yourself

Only on PortSwigger's labs:

  1. Open the SQL injection learning path (link in Your lab) and read the first section.
  2. Do the apprentice lab about retrieving hidden data with a WHERE clause. With Burp running, find the category request, send it to Repeater, and apply this lesson: baseline, then a single ', then the comment trick.
  3. Do the apprentice lab about subverting application logic (login bypass).
  4. For each, write one sentence: what did the original query probably look like, and how did your input change it?

How attackers abuse this

Attackers look for any input that reaches a database — search boxes, filters, IDs, login forms, even headers and cookies (recall your input-point table from Stage 2 Lesson 3). Automated tools scan the internet for SQLi constantly, so an exposed injectable parameter rarely stays undiscovered for long.

The defensive fix:

1. Parameterised queries (prepared statements) — the real fix. Send the query structure and the data separately, so the database never treats data as code:

# Unsafe — input glued into the query
cursor.execute("SELECT * FROM products WHERE category = '" + category + "'")

# Safe — the ? is a placeholder; the database treats category purely as data
cursor.execute("SELECT * FROM products WHERE category = ?", (category,))

With the safe version, Office'-- is simply searched for as a category literally named Office'-- — and nothing matches. Every mainstream language and framework supports this; ORMs (libraries that build queries for you) do it by default when used properly.

2. Least privilege. The application's database account should only have the permissions it needs. If the shop only reads products, it shouldn't be able to drop tables. This limits damage if something slips through.

3. Input validation — as defence in depth. If category should only ever be one of five values, reject anything else. If an ID should be a number, check it's a number. Validation reduces risk but is not a replacement for parameterised queries.

4. Don't show database errors to users. Generic error pages (Stage 2 Lesson 2); log the details privately.


Common mistakes

  • "Escaping quotes" by hand instead of parameterising. Home-made filters miss edge cases. Use the database library's placeholders.
  • Thinking only login forms are vulnerable. Any input that reaches a query can be — including sort orders, filters, cookies and headers.
  • Believing input validation alone is enough. It's a useful second layer, not the fix.
  • Using a database admin account for the app. One bug then means total control.
  • Practising on real sites. Labs only. A quote in a search box on a live site is still an unauthorised test.

Check yourself

  1. In one sentence: what's the root cause of SQL injection?
  2. Why does -- matter in the example Office'--?
  3. A developer says "we filter out the word SELECT, so we're safe from SQLi." What would you tell them to do instead?
Answers
  1. User input is concatenated into a SQL query, so the database treats part of the input as query code instead of data.
  2. -- starts an SQL comment, so the rest of the original query (like AND released = 1) is ignored.
  3. Blocklisting words is easy to get around and breaks legitimate input. Use parameterised queries so input can never change the query structure, plus least-privilege database accounts. Validation can be a second layer.

Your lab

  • PortSwigger SQL injection learning path — start with the apprentice labs: https://portswigger.net/web-security/sql-injection

Writeup: for each lab, the vulnerable parameter, the evidence (one-quote/two-quote test), what it allowed, and the fix.


Summary in your language

தமிழில் சுருக்கம்

பயனர் input நேரடியாக database query-யுடன் ஒட்டப்படும்போது SQL injection நடக்கிறது — அப்போது attacker query என்ன செய்கிறது என்பதையே மாற்ற முடியும். ஒரு ' பக்கத்தை உடைத்து, '' சரி செய்தால் அது வலுவான அறிகுறி. இதன் மூலம் மறைந்த தரவைப் படிக்கலாம், login-ஐத் தவிர்க்கலாம், தரவை மாற்றலாம். உண்மையான தீர்வு: parameterised queries (prepared statements) — query அமைப்பும் தரவும் தனித்தனியாக அனுப்பப்படும். கூடவே least-privilege database கணக்குகள், input validation, பொதுவான error pages. Lab-களில் மட்டுமே பயிற்சி.

हिंदी में सारांश

जब user का input सीधे database query में जोड़ दिया जाता है, तब SQL injection होता है — attacker query का काम ही बदल सकता है। अगर एक ' page तोड़ दे और '' उसे ठीक कर दे, तो यह मज़बूत संकेत है। इससे छिपा data पढ़ा जा सकता है, login bypass हो सकता है, data बदला जा सकता है। असली इलाज: parameterised queries (prepared statements) — query का ढाँचा और data अलग-अलग भेजे जाते हैं। साथ में least-privilege database accounts, input validation और साधारण error pages। अभ्यास सिर्फ़ labs पर।

Want this summary in Malayalam, Telugu, Kannada or another language? Tell us — the most requested languages get added next.


What's next

When the page shows nothing at all, SQLi can still work: Blind SQLi and time-based extraction