SQL Tutorial

SQL Introduction SQL Aggregate Functions SQL Aliases SQL And SQL Any All SQL Avg SQL Between SQL Case SQL Comments SQL Count SQL Delete SQL Distinct SQL Exists SQL GROUP BY SQL Having SQL In SQL INSERT INTO SQL Is Not Null SQL Join SQL Full Outer Join SQL Inner Join SQL Left Join SQL Right Join SQL Self Join SQL Like SQL Min Max SQL NOT Operator SQL Null SQL Operators SQL OR operator SQL ORDER BY SQL Select SQL Select Into SQL Top Limit Fetch SQL Stored Procedures SQL Sum SQL Union SQL Update SQL Where SQL Wildcards

SQL Database

SQL Alter Table SQL Auto increment SQL Backup Database SQL Check SQL Constraints SQL Create View SQL Create Database SQL Create Table SQL Data types SQL Dates SQL Default Constraint SQL Drop Database SQL Drop Table SQL Foreign Key SQL Hosting SQL Index SQL injections SQL Not NULL SQL PrimaryKey SQL Unique SQL Views

SQL injections

Example Table

We will create a table named users to demonstrate SQL injection:


    CREATE TABLE users (
        user_id INT PRIMARY KEY,
        username VARCHAR(50),
        password VARCHAR(50)
    );
    

Creating the Table

To create the table, use the following SQL command:


    CREATE TABLE users (
        user_id INT PRIMARY KEY,
        username VARCHAR(50),
        password VARCHAR(50)
    );
    

Result:

Command CREATE TABLE users (user_id INT PRIMARY KEY, username VARCHAR(50), password VARCHAR(50));
Result
  • A table named users is created.

Inserting Data

To insert data into the table, use the following SQL command:


    INSERT INTO users (user_id, username, password) 
    VALUES (1, 'admin', 'admin123'), 
           (2, 'user', 'user123');
    

Result:

Command INSERT INTO users (user_id, username, password) VALUES (1, 'admin', 'admin123'), (2, 'user', 'user123');
Result
  • Data is inserted into the users table.

SQL Injection Example

Consider the following vulnerable SQL query:


    SELECT * FROM users WHERE username = 'admin' AND password = 'admin123';
    

If an attacker inputs ' OR '1'='1 as the password, the query becomes:


    SELECT * FROM users WHERE username = 'admin' AND password = '' OR '1'='1';
    

Result:

Command SELECT * FROM users WHERE username = 'admin' AND password = '' OR '1'='1';
Result
  • Returns all rows from the users table, bypassing authentication.

Preventing SQL Injection

To prevent SQL injection, use prepared statements or parameterized queries:


    -- Example in PHP
    $stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password');
    $stmt->execute(['username' => $username, 'password' => $password]);
    

Result:

Command

    $stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password');
    $stmt->execute(['username' => $username, 'password' => $password]);
                
Result
  • Prevents SQL injection by safely handling user input.

Important Considerations

When securing your SQL queries, consider the following: