SQL Basics

Overview

This document covers essential SQL statements for database operations, based on MySQL/MariaDB syntax. These are fundamental operations needed for database interaction and SQL injection understanding.


Database and Table Operations

Create Database

CREATE DATABASE users;

Show Databases

SHOW DATABASES;

Use Database

USE users;

Create Table with Constraints

CREATE TABLE logins (
    id INT NOT NULL AUTO_INCREMENT,
    username VARCHAR(100) UNIQUE NOT NULL,
    password VARCHAR(100) NOT NULL,
    date_of_joining DATETIME DEFAULT NOW(),
    PRIMARY KEY (id)
);

Common Constraints:

  • NOT NULL - Field cannot be empty

  • UNIQUE - Field must be unique

  • AUTO_INCREMENT - Automatically increment value

  • DEFAULT NOW() - Set default to current timestamp

  • PRIMARY KEY - Unique identifier for records

Show Tables and Structure


Data Manipulation

INSERT Statement

Insert All Columns

Insert Specific Columns

Insert Multiple Records

SELECT Statement

Select All Data

Select Specific Columns

Select with Conditions

Example Output:

UPDATE Statement

Update Records with Conditions

Update Multiple Columns

Important: Always use WHERE clause to avoid updating all records!

DELETE Statement


Table Structure Modification

ALTER TABLE Operations

Add New Column

Rename Column

Modify Column Data Type

Drop Column

Add Constraints

DROP Operations

Drop Table (Permanent Deletion!)

Drop Database (Extremely Dangerous!)

Warning: DROP operations are permanent and cannot be undone!


Common WHERE Clause Conditions

Comparison Operators

Pattern Matching

Logical Operators

Basic Logical Operations

Operator Evaluation Examples

Symbol Operators (Alternative Syntax)

Practical WHERE Clause Examples


Operator Precedence (Critical for SQL Injection!)

Precedence Order (High to Low)

  1. Arithmetic: Division (/), Multiplication (*), Modulus (%)

  2. Arithmetic: Addition (+), Subtraction (-)

  3. Comparison: =, >, <, <=, >=, !=, LIKE

  4. Logical: NOT (!)

  5. Logical: AND (&&)

  6. Logical: OR (||)

Precedence Examples

Parentheses Override Precedence

Common Precedence Gotchas

NULL Handling


Useful Functions

String Functions

Date Functions

Aggregate Functions


Security Notes

Bad Practices

Good Practices


HTB Academy Example Scenario

Target Database: employees Connection: mysql -u root -ppassword -h target --skip-ssl

Common Enumeration Steps

Expected Workflow

  1. Connect: mysql -u root -ppassword -h target --skip-ssl

  2. List: SHOW DATABASES;

  3. Select: USE database_name;

  4. Explore: SHOW TABLES;

  5. Query: SELECT * FROM table_name;

  6. Target: SELECT column FROM table WHERE condition;

Last updated