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

  1. Login Forms: One of the most attacked entry points. Malicious input tricks the query into bypassing authentication.
  2. Search Fields: If search input goes directly into a query, attackers can manipulate it to dump sensitive data.
  3. URL Parameters: URLs that contain query strings like ?id=5 can be hijacked for unauthorized data access.
  4. 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

  1. Classic SQL Injection: Input is appended to a query string, modifying its behavior directly.
  2. Blind SQL Injection: Based on behavior analysis when no error or data is shown.
  3. Time-Based Blind SQL Injection: Attackers inject conditions that delay execution (e.g., SLEEP(5)) to determine if a condition is true.
  4. 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

  1. 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.

  2. Input Validation

    While validation alone won’t stop all attacks, restricting input formats (e.g., only numbers for IDs) makes many attacks harder.

  3. Stored Procedures

    When implemented correctly, stored procedures can limit the risk by avoiding dynamic SQL.

  4. Escaping Input (with Caution)

    Escaping characters like quotes can reduce risk but is error-prone and shouldn't be the primary defense.

  5. Use ORM Tools

    Tools like Sequelize (Node.js), Hibernate (Java), and Entity Framework (C#) help abstract SQL and enforce safe query construction.

  6. 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.

  7. 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.

  8. 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.

Learn SQL for Free
Start learning now
button icon
To advance beyond this tutorial and learn SQL by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH

Reach your coding goals faster