- Aggregate functions
- ALTER TABLE statement
- AVERAGE function
- BETWEEN operator
- CASE expression
- CAST() function
- COALESCE() function
- Comment
- Common table expression
- CONCAT() function
- Constraints
- CONTAINS
- CONVERT function
- COUNT() function
- CREATE TABLE statement
- CROSS JOIN
- Cursor
- Data types
- Date functions
- DATEADD() function
- DATEDIFF() function
- DELETE statement
- DROP TABLE statement
- EXISTS operator
- FORMAT() function
- GROUP BY statement
- HAVING clause
- IF statement
- Index
- Injection
- INNER JOIN
- INSERT INTO statement
- IS NOT NULL condition
- IS NULL condition
- Joins
- LAG function
- LEFT JOIN
- LENGTH() function
- LIKE operator
- LIMIT clause
- MERGE statement
- Normalization
- Not equal
- Operators
- ORDER BY clause
- Partition
- Pivot table
- Regex
- REPLACE function
- ROUND function
- SELECT DISTINCT clause
- SELECT statement
- Set operators
- Stored procedure
- String functions
- Subquery
- Substring
- Temporary table
- Transaction
- Trigger
- TRUNCATE TABLE
- UPDATE statement
- Views
- WHERE clause
- Window functions
SQL
SQL Injection: Syntax, Usage, and Examples
SQL injection
is a code injection technique where malicious SQL statements are inserted into an application’s input fields and executed by the database. This type of vulnerability can lead to unauthorized access, data theft, data deletion, or complete control of the database server.
How SQL Injection Happens
The core of injection SQL
attacks lies in improper handling of user input. When applications construct SQL queries using string concatenation with unchecked input, attackers can craft input that changes the structure of the original query.
Vulnerable Code Example
Imagine a login form where a developer builds a query like this:
SELECT * FROM users WHERE username = 'admin' AND password = '1234';
If the developer doesn’t sanitize input, and an attacker enters this into the username field:
' OR '1'='1
The resulting query becomes:
SELECT * FROM users WHERE username = '' OR '1'='1' AND password = '...';
Since '1'='1'
is always true, this sql injection example
bypasses authentication.
When SQL Injection Occurs
SQL injection
typically occurs in applications that:
- Directly embed user input into SQL queries
- Use string concatenation to build database queries
- Fail to use parameterized queries or stored procedures
- Lack input validation and output encoding
Common Targets
- Login Forms: One of the most attacked entry points. Malicious input tricks the query into bypassing authentication.
- Search Fields: If search input goes directly into a query, attackers can manipulate it to dump sensitive data.
- URL Parameters: URLs that contain query strings like
?id=5
can be hijacked for unauthorized data access. - Admin Panels: Interfaces for managing users or content are often vulnerable if built without secure practices.
Examples of SQL Injection
Example 1: Basic Authentication Bypass
-- Original query
SELECT * FROM users WHERE username = '[input]' AND password = '[input]';
-- Malicious input
username: ' OR 1=1 --
password: [anything]
-- Final query
SELECT * FROM users WHERE username = '' OR 1=1 --' AND password = '[input]';
The --
comment symbol ignores the rest of the query, so the password check is bypassed.
Example 2: Data Extraction
Suppose a vulnerable search feature:
SELECT * FROM products WHERE name LIKE '%[input]%';
An attacker enters:
%' UNION SELECT username, password FROM users --
The query becomes:
SELECT * FROM products WHERE name LIKE '%%' UNION SELECT username, password FROM users -- %';
Now, the attacker sees usernames and passwords in the product list.
Example 3: Database Destruction
-- Malicious input:
'; DROP TABLE users; --
-- Query becomes:
SELECT * FROM posts WHERE id = ''; DROP TABLE users; --';
This deletes the entire users
table.
This sql injection example
highlights how destructive these attacks can be if not mitigated.
Learn More About SQL Injection
What is SQL Injection Doing Under the Hood?
To answer what is sql injection from a technical perspective, it manipulates query logic. SQL interprets user-supplied data as executable commands rather than harmless strings. By controlling the structure of the query, attackers change its meaning.
The attack relies on improper trust between application logic and input data. A normal query expects strings like 'apple'
, but a malicious string like "' OR 1=1"
causes the logic to return more results than expected—or execute dangerous actions.
Injection SQL via Blind Attacks
Not all injection SQL
attempts reveal data immediately. In blind SQL injection, the attacker probes the database with true/false conditions and observes the system’s behavior.
' OR 1=1 --
' AND 1=2 --
By submitting inputs that change the logic slightly and comparing responses, attackers gather insights even without seeing direct output.
Types of SQL Injection Attacks
- Classic SQL Injection: Input is appended to a query string, modifying its behavior directly.
- Blind SQL Injection: Based on behavior analysis when no error or data is shown.
- Time-Based Blind SQL Injection: Attackers inject conditions that delay execution (e.g.,
SLEEP(5)
) to determine if a condition is true. - Out-of-Band SQL Injection: Data is exfiltrated using side channels like DNS queries or external HTTP requests.
Languages and Systems Affected
SQL injection
isn't limited to web applications or relational databases. Any system that constructs and executes SQL from dynamic input can be vulnerable:
- Languages: PHP, Python, Java, C#, Ruby
- Databases: MySQL, PostgreSQL, SQL Server, Oracle, SQLite
- Interfaces: APIs, command-line tools, admin dashboards
Even embedded systems using lightweight databases can fall victim.
Preventing SQL Injection
-
Use Parameterized Queries
This is the most reliable defense. In parameterized queries (aka prepared statements), the structure of the SQL query is fixed, and values are bound safely.
Example in Python with SQLite:
cursor.execute("SELECT * FROM users WHERE username = ? AND password = ?", (username, password))
This guarantees that user input can’t change the query structure.
-
Input Validation
While validation alone won’t stop all attacks, restricting input formats (e.g., only numbers for IDs) makes many attacks harder.
-
Stored Procedures
When implemented correctly, stored procedures can limit the risk by avoiding dynamic SQL.
-
Escaping Input (with Caution)
Escaping characters like quotes can reduce risk but is error-prone and shouldn't be the primary defense.
-
Use ORM Tools
Tools like Sequelize (Node.js), Hibernate (Java), and Entity Framework (C#) help abstract SQL and enforce safe query construction.
-
Least Privilege Access
Ensure your application’s database user account has only the permissions it needs. Avoid using root or admin-level database users in production apps.
-
Monitoring and Logging
Track unusual behavior like frequent failed logins, unexpected query patterns, or unusual latency. These might be signs of an active
sql injection
attempt. -
Web Application Firewalls (WAFs)
A WAF can detect and block basic SQL injection attempts, especially known patterns in URL parameters or headers.
How SQL Injection Affects Organizations
A successful SQL injection attack can have serious consequences:
- Data breaches (personal info, financial records, login credentials)
- Account takeover
- Website defacement
- Ransom or extortion
- Reputational damage and legal consequences under GDPR or HIPAA
Famous incidents include the Heartland Payment Systems breach and the early LinkedIn leaks—both made possible through SQL injection vectors.
SQL injection is one of the oldest and most dangerous vulnerabilities in modern software. It exploits poor query design and careless handling of input. But with careful coding practices—like parameterized queries, input validation, and least privilege—you can eliminate the risks. Developers who understand how injection SQL
attacks work and how to defend against them are crucial for building secure, resilient applications.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.