Before you can store a single record in MySQL, you must architect its container. Schema Design is the blueprinting phase of database engineering: deciding what tables to create, which data types will minimize disk storage while maximizing performance, and how constraints will guarantee data purity.
DDL (Data Definition Language) commands (CREATE, ALTER, DROP, TRUNCATE) are the SQL instructions used to construct, modify, and destroy these physical database structures.
1. Mastering MySQL Data Types
Selecting the correct data type is critical. A poorly chosen data type wastes storage, increases RAM usage in the buffer pool, and degrades query speeds.
Numeric Data Types
| Type | Storage | Min / Max Value | Best Used For |
|---|---|---|---|
TINYINT | 1 byte | -128 to 127 (or 0 to 255 UNSIGNED) | Status codes, age, boolean flags (TINYINT(1)) |
SMALLINT | 2 bytes | -32,768 to 32,767 | Small counters, year numbers |
INT | 4 bytes | -2.14 billion to 2.14 billion | Standard primary keys, user IDs, quantities |
BIGINT | 8 bytes | -9.22 quintillion to 9.22 quintillion | Global scale IDs, large event logs, financial ledgers |
DECIMAL(M,D) | Variable | Exact fixed-point math | Currency & Prices (e.g., DECIMAL(10,2) = 8 digits before decimal, 2 after) |
FLOAT / DOUBLE | 4 / 8 bytes | Approximate floating-point numbers | Scientific data where slight rounding inaccuracy is acceptable (never money!) |
Text & String Data Types
CHAR(n): Fixed-length string (1 to 255 characters). MySQL always allocates the full length on disk with spaces. Ideal for fixed-length codes like country abbreviations (CHAR(2)for'US','IN','CA') or currency codes (CHAR(3)for'USD','EUR').VARCHAR(n): Variable-length string (up to 65,535 bytes). Only consumes storage for the characters actually stored plus 1-2 prefix bytes. Ideal for names, emails, titles, and addresses.TEXT/MEDIUMTEXT/LONGTEXT: Large string blocks (up to 4 GB inLONGTEXT). Stored off-page in InnoDB. Ideal for blog post bodies, documentation, and raw markdown.ENUM('a', 'b', 'c'): String object whose value must be chosen from a predefined list of permitted values.
Date & Time Data Types
DATE: Stores dates formatted asYYYY-MM-DD(1000-01-01 to 9999-12-31).TIME: Stores time formatted asHH:MM:SS.DATETIME: Stores date and time combined (1000-01-01 00:00:00 to 9999-12-31 23:59:59). Does not convert timezones.TIMESTAMP: Stores UTC timestamp (1970-01-01 to 2038-01-19). Automatically converts to and from current session timezone. Ideal for audit columns likecreated_atandupdated_at.
2. Table Constraints: Enforcing Business Rules at the Engine Level
Constraints are rules enforced on data columns to ensure that invalid or corrupt data is physically rejected before it touches the disk:
PRIMARY KEY: Uniquely identifies each record. Automatically enforces bothUNIQUEandNOT NULL.AUTO_INCREMENT: Tells MySQL to automatically assign the next sequential integer whenever a new row is inserted.NOT NULL: Prevents a column from ever containing aNULLvalue.UNIQUE: Guarantees that all values in a column are distinct across the entire table (essential foremailandusername).CHECK (expression): Validates a boolean expression before permitting an insert or update (e.g.CHECK (price > 0)).DEFAULT value: Provides an automatic fallback value when an insert statement omits that column.FOREIGN KEY: Enforces referential integrity by linking to another table's primary key.
3. Real-World Example: Designing an E-Commerce Schema
Here is how production-grade tables are built with proper constraints and relationships:
-- 1. Create a Categories lookup table
CREATE TABLE categories (
id INT AUTO_INCREMENT PRIMARY KEY,
category_name VARCHAR(50) NOT NULL UNIQUE,
description VARCHAR(255) DEFAULT 'No description provided',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- 2. Create a Products table linked to Categories
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
category_id INT NOT NULL,
sku VARCHAR(20) NOT NULL UNIQUE,
title VARCHAR(150) NOT NULL,
price DECIMAL(10,2) NOT NULL CHECK (price >= 0),
stock_quantity INT DEFAULT 0 CHECK (stock_quantity >= 0),
is_active BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
-- Referential Integrity Constraint
CONSTRAINT fk_product_category
FOREIGN KEY (category_id) REFERENCES categories(id)
ON DELETE RESTRICT
ON UPDATE CASCADE
);
Foreign Key Actions Explained:
ON DELETE RESTRICT: Prevents anyone from deleting a category if there are still active products belonging to it.ON DELETE CASCADE: If the parent record is deleted, automatically delete all related child records.ON DELETE SET NULL: If the parent record is deleted, set the child's foreign key column toNULL.
4. Altering Existing Tables (ALTER TABLE)
Software evolves, and schemas must change over time without losing existing customer data. The ALTER TABLE statement handles migrations:
-- Adding a new column to an existing table
ALTER TABLE users ADD COLUMN phone_number VARCHAR(20);
-- Modifying a column data type or constraints
ALTER TABLE users MODIFY COLUMN email VARCHAR(320) NOT NULL;
-- Renaming a column
ALTER TABLE users RENAME COLUMN phone_number TO mobile;
-- Dropping an obsolete column
ALTER TABLE users DROP COLUMN mobile;
-- Adding a unique index
ALTER TABLE users ADD CONSTRAINT uq_user_email UNIQUE (email);
5. DROP vs TRUNCATE vs DELETE
When cleaning up tables, understand the critical architectural differences:
| Command | Type | What Happens | Speed | Can Rollback? |
|---|---|---|---|---|
DELETE FROM table; | DML | Deletes rows one-by-one, recording each row in undo logs and firing triggers. | Slowest | Yes (inside transaction) |
TRUNCATE TABLE table; | DDL | Drops and recreates the underlying data pages. Resets AUTO_INCREMENT to 1. | Extremely Fast | No |
DROP TABLE table; | DDL | Permanently destroys the data rows, schema definition, indexes, and constraints. | Instant | No |
6. Interactive Sandbox Exercise
Try running these DDL statements in the Query Input box below to create your own table in the browser sandbox:
-- Create a custom inventory table
CREATE TABLE IF NOT EXISTS product_inventory (
sku_id INTEGER PRIMARY KEY AUTOINCREMENT,
item_name TEXT NOT NULL UNIQUE,
stock INTEGER DEFAULT 0,
unit_price DECIMAL(10,2) NOT NULL
);
-- Insert sample items
INSERT INTO product_inventory (item_name, stock, unit_price) VALUES
('Mechanical Keyboard', 25, 89.99),
('Wireless Mouse', 40, 39.50),
('UltraWide Monitor', 12, 449.00);
-- Verify the new table exists
SELECT * FROM product_inventory;