SQL Injection Tutorial: Learn, Practice & Defend with Free Labs
Understand SQL injection attacks from the ground up. Learn how attackers exploit databases, practice in safe environments, and defend your applications.
What Is SQL Injection?
SQL injection (SQLi) is a vulnerability where an attacker inserts malicious SQL code into input fields, tricking the database into executing unintended commands. It consistently ranks in the OWASP Top 10 and remains one of the most exploited web vulnerabilities.
SQL injection accounts for approximately 65% of all web application attacks. Despite being well-understood, it continues to plague applications due to poor input handling and legacy code.
Types of SQL Injection
Classic (Error-Based)
The application returns database error messages that reveal the query structure. Attackers use these to extract data directly.
Example:
Input: ' UNION SELECT null,null--
Error: You have an error in your SQL syntax near 'UNION SELECT null,null--'
The error reveals the database type and query structure, helping the attacker refine their injection.
Blind (Boolean-Based)
The application doesn't return errors, but responds differently depending on whether the injected condition is true or false.
Example:
True condition: ' AND 1=1 -- (normal page response)
False condition: ' AND 1=2 -- (different page response)
Attackers infer data one bit at a time by observing response differences.
Union-Based
Attackers use UNION SELECT to combine results from injected queries with legitimate ones, extracting data from other tables.
Example:
' UNION SELECT username,password FROM users--
Time-Based
Blind injection variant where attackers measure response time to determine if conditions are true. Slower but harder to detect.
Example:
' AND (SELECT CASE WHEN (1=1) THEN pg_sleep(5) ELSE pg_sleep(0) END)--
If the response takes 5 seconds, the condition was true.
Step-by-Step SQL Injection Examples
Example 1: Login Bypass
Vulnerable code:
query = f"SELECT * FROM users WHERE username='{username}' AND password='{password}'"
Attack:
Username: admin' --
Password: anything
Resulting query:
SELECT * FROM users WHERE username='admin' --' AND password='anything'
The -- comments out the password check. The attacker logs in as admin.
Example 2: Data Extraction
Vulnerable code:
$query = "SELECT * FROM products WHERE id = " . $_GET['id'];
Attack:
?id=1 UNION SELECT username,password FROM users--
Resulting query:
SELECT * FROM products WHERE id = 1 UNION SELECT username,password FROM users--
The UNION query appends the user credentials to the product results.
Example 3: Blind Data Extraction
Attack (character by character):
?id=1 AND SUBSTRING((SELECT password FROM users WHERE username='admin'),1,1)='a'
If true, the page loads normally. If false, it may differ. The attacker iterates through each character position and each possible character value.
How an Attack Works
Consider a login form with this query:
SELECT * FROM users WHERE username = 'INPUT' AND password = 'INPUT'
An attacker enters:
Username: ' OR 1=1 --
The query becomes:
SELECT * FROM users WHERE username = '' OR 1=1 --' AND password = ''
The -- comments out the rest. The OR 1=1 makes the condition always true. The attacker logs in without a valid password.
Why SQL Injection Is Dangerous
- Data Theft — Extract entire databases including user credentials, credit cards, and personal information.
- Authentication Bypass — Log in as any user, including administrators.
- Data Modification — Insert, update, or delete records.
- Server Compromise — Some database configurations allow command execution on the host system.
- Lateral Movement — Use database access to pivot to internal networks.
How to Practice Safely
Never practice SQL injection on systems you don't own. Use these intentionally vulnerable environments:
- DVWA — Damn Vulnerable Web Application with multiple difficulty levels
- SQLi-labs — Dedicated SQL injection practice platform
- Juice Shop — Modern vulnerable web app with progressive challenges
- WebGoat — OWASP's official training application
Each provides a safe sandbox where you can explore injection techniques without legal or ethical concerns.
Practice progression:
- DVWA (low security) → Basic injection
- SQLi-labs → All injection types
- Juice Shop → Real-world scenarios
- WebGoat → OWASP-structured lessons
Defense Techniques
Parameterized Queries (Prepared Statements)
The single most effective defense. Never concatenate user input directly into SQL queries.
Vulnerable (NEVER do this):
cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")
Secure (parameterized):
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
Node.js example:
// Vulnerable
db.query(`SELECT * FROM users WHERE id = ${userId}`);
// Secure
db.query("SELECT * FROM users WHERE id = $1", [userId]);
PHP example:
// Vulnerable
$result = mysqli_query($conn, "SELECT * FROM users WHERE id = " . $_GET['id']);
// Secure
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $_GET['id']);
$stmt->execute();
ORM Frameworks
Object-Relational Mappers like Sequelize, SQLAlchemy, and Prisma abstract raw SQL, reducing injection risk.
Prisma example:
// Automatically parameterized
const user = await prisma.user.findUnique({
where: { id: parseInt(userId) }
});
Input Validation
Whitelist expected input patterns. Reject anything that doesn't match.
import re
def validate_user_id(user_id):
if not re.match(r'^[0-9]+$', user_id):
raise ValueError("Invalid user ID")
return int(user_id)
Least Privilege
Database accounts should have minimal permissions. The web application shouldn't use a DBA account.
-- Create a limited user for the web application
CREATE USER 'webapp'@'localhost' IDENTIFIED BY 'secure_password';
GRANT SELECT, INSERT, UPDATE ON mydb.* TO 'webapp'@'localhost';
-- Do NOT grant DROP, ALTER, CREATE, or GRANT
Stored Procedures
CREATE PROCEDURE GetUser(IN userId INT)
BEGIN
SELECT * FROM users WHERE id = userId;
END
-- Call with parameterized input
CALL GetUser(123);
Web Application Firewall
WAFs like ModSecurity catch common injection patterns as an additional layer. Not a primary defense, but adds depth.
# ModSecurity rule example
SecRule REQUEST_URI|REQUEST_BODY|QUERY_STRING "@detectsqli" \
"id:1001,phase:1,block,msg:'SQL Injection Detected'"
Real-World Impact
The 2019 Capital One breach exposed 100 million records through a misconfigured WAF combined with SSRF — techniques that start with understanding SQL injection fundamentals. The 2017 Equifax breach, affecting 147 million people, exploited a known vulnerability that proper input handling would have prevented.
Cost of SQL injection:
- Average breach cost: $4.88 million
- Time to identify and contain: 277 days
- Regulatory fines: Up to 4% of global revenue under GDPR
Start Learning
SQL injection is the gateway to web application security. Master it through hands-on labs, then expand to XSS, CSRF, and other OWASP Top 10 vulnerabilities.
Learning path: SQL injection → XSS → CSRF → Authentication flaws → Authorization bypass → Business logic
Key Takeaways
- SQL injection remains one of the most common and dangerous web vulnerabilities
- Four main types: Error-based, Blind (Boolean and Time-based), and Union-based
- Parameterized queries are the single most effective defense
- Never concatenate user input into SQL queries
- Practice in safe environments (DVWA, SQLi-labs, Juice Shop)
- Defense requires multiple layers: parameterization, validation, least privilege, WAF
Try It Yourself
- Deploy DVWA and complete all SQL injection challenges at Low security
- Write parameterized queries in your preferred language
- Complete 5 SQLi-labs challenges
- Implement input validation for a web form
Related Articles
- Free Cybersecurity Labs for Beginners
- Web Application Security Testing
- 15 Cybersecurity Tools Every Beginner Should Know
FAQ
Can SQL injection be completely prevented?
Yes, when proper defenses are implemented. Parameterized queries effectively eliminate SQL injection when used consistently. No defense is 100% alone — use parameterization as primary defense, with input validation, least privilege, and WAF as additional layers.
What databases are vulnerable to SQL injection?
All databases that accept SQL queries are potentially vulnerable: MySQL, PostgreSQL, Microsoft SQL Server, Oracle, SQLite, and others. The vulnerability exists in how the application constructs queries, not in the database itself.
How do I test for SQL injection in my application?
Use automated scanners like SQLmap, Burp Suite, or OWASP ZAP. Also perform manual testing with common injection payloads. Check every input field, URL parameter, and HTTP header that feeds into database queries.
Is SQL injection still relevant in 2026?
Yes. Despite being well-understood, SQL injection continues to appear in the OWASP Top 10. Legacy applications, poor coding practices, and new application features without proper input handling keep this vulnerability prevalent.
SQL Injection
1 of 5What is SQL injection?
Related Articles
Ready to practice?
Apply what you learned with free hands-on labs on XpertClass. Deploy real Docker sandboxes — no setup required.