Masterclass

The Complete
Database Knowledge

From precise column types to complex stored procedures. This documentation covers all facets of MySQL/MariaDB – including comprehensive code examples for real-world practice.

💎

1. Structure, Keys & Constraints

Uniqueness Rules

PRI

Primary Key

The absolute anchor. Unique, indexed, never NULL.

UNI

Unique Key

Prevents duplicate values (e.g., email). However, it allows NULL values.

Performance & Validation

MUL

Multiple Index

A simple table of contents for searching. Duplicates are allowed.

CHK

CHECK Constraint

Content validation directly in the DB. Prevents nonsensical values.

Practical Example: The "Perfect" Table

Here we see how to cleverly combine all these constraints when creating a table:

CREATE TABLE employees (
    id INT AUTO_INCREMENT PRIMARY KEY,          -- PRI: Auto-incrementing ID
    employee_number VARCHAR(20) UNIQUE,         -- UNI: Must never be duplicated
    department_id INT,                          -- Used later for Foreign Keys
    salary DECIMAL(10,2),
    age_years INT,
    
    CONSTRAINT chk_salary CHECK (salary >= 2000.00), -- CHK: Minimum threshold
    CONSTRAINT chk_age CHECK (age_years >= 18),      -- CHK: Age verification
    
    INDEX idx_department (department_id)        -- MUL: Faster searching for departments
);

2. Referential Integrity (FK Actions)

If you delete or modify a record in the main (parent) table, these four rules decide the fate of the child tables:

1. CASCADE

The domino effect. Automatically deletes or modifies the children as well.
Use case: Delete order items when the order is deleted.

2. SET NULL

The decoupling. The child remains but loses the reference to the parent (ID becomes NULL).
Use case: Keep posts when the author profile is deleted.

3. RESTRICT

The bouncer. Prevents the deletion of parents as long as children still exist.
Use case: Protect categories that still contain products.

4. NO ACTION

Identical to RESTRICT in MySQL/MariaDB. The check is performed strictly at the end of the statement.

Practical Example: ON DELETE & ON UPDATE combined

In reality, these actions are often mixed. Here is a classic scenario from a webshop:

CREATE TABLE orders (
    order_id INT AUTO_INCREMENT PRIMARY KEY,
    customer_id INT,
    total_amount DECIMAL(10,2),
    
    -- Definition of the Foreign Key
    CONSTRAINT fk_customer_order
    FOREIGN KEY (customer_id) REFERENCES customers(id)
    
    -- RULE 1 (Delete):
    -- If the customer profile is deleted, keep the order for the tax office, 
    -- but remove the assignment to the customer (set ID to NULL).
    ON DELETE SET NULL 
    
    -- RULE 2 (Update):
    -- If the ID of the customer changes in the main table, 
    -- automatically adjust the ID here in the orders as well.
    ON UPDATE CASCADE
);
🔍

3. Abstraction: Views & CTEs

Views (The permanent glasses)

Saves a complex query (like JOINs) as a virtual table. Ideal for reports or to block access to certain columns (like passwords).

-- 1. Create View:
CREATE VIEW v_sales_report AS
SELECT c.name, SUM(o.amount) AS total
FROM customers c
JOIN orders o ON c.id = o.customer_id
GROUP BY c.id;

-- 2. Simply query as if it were a table:
SELECT * FROM v_sales_report WHERE total > 500;

CTEs (The temporary help)

With WITH you define an intermediate query that exists only for this single statement. Makes code very readable.

-- Define a CTE (top_customers) and use it immediately:
WITH top_customers AS (
    SELECT id FROM customers WHERE revenue > 1000
)
SELECT o.order_id, o.total_amount 
FROM orders o
WHERE o.customer_id IN (SELECT id FROM top_customers);
🤖

4. Automation: Triggers & Cron Jobs

Triggers (The automatic reflexes)

Triggers "fire" fully automatically when an INSERT, UPDATE or DELETE is executed on a table. Perfect for logging or strict validations.

Practical Example: The "No negative inventory" barrier

DELIMITER //

CREATE TRIGGER tr_stock_check
BEFORE UPDATE ON inventory
FOR EACH ROW
BEGIN
  -- Check if the new value (NEW) falls below 0
  IF NEW.quantity < 0 THEN
    -- If yes: Immediate abort with error message!
    SIGNAL SQLSTATE '45000' 
    SET MESSAGE_TEXT = 'Critical error: Inventory must not fall below 0!';
  END IF;
END //

DELIMITER ;

Database-internal Cron Jobs Important

The biggest misconception: Many developers think a database is "dumb" and only works when called from the outside. False! MariaDB/MySQL has an internal background service (Event Scheduler). Once activated, the database completely independently takes care of scheduled tasks (e.g., log rotation).

Step 1: Turn on service

This command wakes up the internal "cron daemon" of the database:

SET GLOBAL event_scheduler = ON;
Step 2: Define the job

An example of a cleanup job that runs every day:

CREATE EVENT ev_daily_session_cleanup
ON SCHEDULE EVERY 1 DAY          -- Interval
STARTS '2026-01-01 03:00:00'     -- Start time
DO
BEGIN
  -- Everything written here is executed independently by the database!
  DELETE FROM user_sessions WHERE expires_at < NOW();
END;
⚙️

5. Stored Procedures & Functions

While Views only store queries, Stored Procedures are real programs within the database. You can use variables, write loops, check IF conditions, and start complex processes with a single call.

Stored Procedures (Workflows)

They perform actions (e.g., move records). They are called with CALL and can receive parameters.

Example: Customer Archiving

DELIMITER //

CREATE PROCEDURE sp_archive_customers(IN p_months INT)
BEGIN
    -- 1. Copy
    INSERT INTO customer_archive 
    SELECT * FROM customers 
    WHERE last_login < DATE_SUB(NOW(), INTERVAL p_months MONTH);
    
    -- 2. Delete
    DELETE FROM customers 
    WHERE last_login < DATE_SUB(NOW(), INTERVAL p_months MONTH);
END //

DELIMITER ;

-- CALL:
CALL sp_archive_customers(12);

Stored Functions (Calculations)

Must mandatorily return a value (RETURNS). Used directly in normal SELECT queries.

Example: Tax Calculation

DELIMITER //

CREATE FUNCTION fn_gross(p_net DECIMAL(10,2), p_tax INT)
RETURNS DECIMAL(10,2) DETERMINISTIC
BEGIN
    DECLARE v_result DECIMAL(10,2);
    SET v_result = p_net * (1 + (p_tax / 100));
    RETURN v_result;
END //

DELIMITER ;

-- CALL:
SELECT name, price_net, 
       fn_gross(price_net, 19) AS gross
FROM products;

6. Transactions (ACID Principle)

Transactions guarantee that complex data changes are carried out "All or Nothing" (Atomicity). This prevents corrupted datasets if, for example, the server crashes.

Practical Example: The Bank Transfer

With START TRANSACTION the DB waits. Only upon COMMIT is it written. In case of error: ROLLBACK.

-- Starts the protected space
START TRANSACTION;

-- Step 1: Deduct money
UPDATE accounts SET balance = balance - 500 WHERE id = 1;

-- Step 2: Credit money
UPDATE accounts SET balance = balance + 500 WHERE id = 2;

-- SUCCESS: Save both steps permanently in one go!
COMMIT;
🧬

7. JSON & NoSQL Features

Working with JSON

You can store JSON documents directly in columns and query them with special functions. Perfect for dynamic attributes.

-- 1. Store JSON
INSERT INTO products (name, meta) 
VALUES ('Laptop', '{"color": "silver", "ram": "16GB"}');
-- 2. Search and extract in JSON
SELECT JSON_VALUE(meta, '$.color') AS color 
FROM products 
WHERE JSON_EXTRACT(meta, '$.ram') = '16GB';

Metadata

auto_increment, on update CURRENT_TIMESTAMP, virtual columns.

Precision

DECIMAL(10,2) – Absolute precision for currencies.

Self-Documentation

Use COMMENT '...' to attach the logic directly to the column.

🔐

8. Permissions & Roles (RBAC)

Instead of giving permissions to each user individually, you create roles (groups), define their permissions, and assign users to these roles.

-- 1. Create Role CREATE ROLE 'marketing_team'; -- 2. Assign Permissions GRANT SELECT ON shop_db.customers TO 'marketing_team'; -- 3. Assign User GRANT 'marketing_team' TO 'max'@'localhost';