Table of Contents

    Data definition language - MySQL

    SQL CATEGORY • DDL

    Data Definition Language (DDL) in MySQL

    The Foundation Commands That Define and Structure Every Database

    What is DDL?

    Data Definition Language (DDL) is a category of SQL commands used to define, modify, and remove the structure of database objects such as databases, tables, indexes, views, and schemas. DDL commands deal with the "skeleton" of the database — not the data itself.

    Every time you create a new database, design a table, add a column, or drop an index, you're using DDL commands. These commands are auto-committed, meaning their changes are permanent and cannot be rolled back like DML operations.

    "DDL builds the house — DML furnishes it. Without DDL, there's no structure for data to live in."
    🏗️

    Easy Analogy

    Think of DDL as the architect and construction crew of a building. They design the rooms, walls, and floors (database structure). Once built, other workers (DML) move in the furniture (data). DDL defines the blueprint; DML works within it.

    Main DDL Commands in MySQL

    MySQL provides five core DDL commands to manage the structure of your database:

    DDL COMMANDS
    CREATE ALTER DROP TRUNCATE RENAME
    Command Purpose Example Use
    CREATECreates new database objectsCreate database, table, view, index
    ALTERModifies existing structureAdd/drop/modify columns
    DROPDeletes database objects permanentlyRemove a table or database
    TRUNCATERemoves all rows but keeps structureEmpty a table quickly
    RENAMERenames a database objectRename a table or column

    1. CREATE Command

    The CREATE command is used to create new database objects such as databases, tables, indexes, views, and procedures.

    🔹 CREATE DATABASE

    
    -- Create a new database
    CREATE DATABASE SchoolDB;
    
    -- Create only if it doesn't already exist
    CREATE DATABASE IF NOT EXISTS SchoolDB;
    
    -- Switch to use the new database
    USE SchoolDB;
    
    -- Show all available databases
    SHOW DATABASES;
    

    🔹 CREATE TABLE

    
    CREATE TABLE Students (
        student_id INT PRIMARY KEY AUTO_INCREMENT,
        name VARCHAR(100) NOT NULL,
        age INT CHECK (age > 0),
        city VARCHAR(50) DEFAULT 'Kolkata',
        email VARCHAR(100) UNIQUE,
        admission_date DATE DEFAULT (CURRENT_DATE)
    );
    
    📌 Key Points:
    • PRIMARY KEY — Uniquely identifies each row
    • AUTO_INCREMENT — Auto-generates unique values
    • NOT NULL — Column cannot be empty
    • UNIQUE — Ensures unique values
    • DEFAULT — Sets a default value when not provided
    • CHECK — Adds a custom validation rule

    🔹 CREATE TABLE from Another Table

    
    -- Copy structure + data from another table
    CREATE TABLE Students_Backup AS
    SELECT * FROM Students;
    
    -- Copy only structure (no data)
    CREATE TABLE Students_Empty AS
    SELECT * FROM Students WHERE 1 = 0;
    

    🔹 CREATE INDEX

    
    -- Create an index to speed up queries
    CREATE INDEX idx_name ON Students(name);
    
    -- Create a unique index
    CREATE UNIQUE INDEX idx_email ON Students(email);
    

    🔹 CREATE VIEW

    
    -- Create a virtual table (view) from a query
    CREATE VIEW ActiveStudents AS
    SELECT student_id, name, city
    FROM Students
    WHERE age >= 18;
    
    -- Use it like a normal table
    SELECT * FROM ActiveStudents;
    

    2. ALTER Command

    The ALTER command is used to modify the structure of an existing table — add, change, or remove columns and constraints.

    🔹 ADD New Column

    
    ALTER TABLE Students 
    ADD phone VARCHAR(15);
    
    -- Add multiple columns at once
    ALTER TABLE Students 
    ADD gender VARCHAR(10),
    ADD blood_group VARCHAR(5);
    

    🔹 MODIFY Column Data Type

    
    ALTER TABLE Students 
    MODIFY age TINYINT;
    
    -- Change column with NOT NULL constraint
    ALTER TABLE Students 
    MODIFY name VARCHAR(150) NOT NULL;
    

    🔹 CHANGE Column Name

    
    ALTER TABLE Students 
    CHANGE city location VARCHAR(100);
    

    🔹 DROP Column

    
    ALTER TABLE Students 
    DROP COLUMN phone;
    

    🔹 ADD / DROP Constraints

    
    -- Add a UNIQUE constraint
    ALTER TABLE Students 
    ADD CONSTRAINT uq_email UNIQUE (email);
    
    -- Add a FOREIGN KEY
    ALTER TABLE Enrollments
    ADD CONSTRAINT fk_student
    FOREIGN KEY (student_id) REFERENCES Students(student_id);
    
    -- Drop a constraint
    ALTER TABLE Students 
    DROP INDEX uq_email;
    

    🔹 RENAME Table

    
    ALTER TABLE Students 
    RENAME TO StudentsRecord;
    

    3. DROP Command

    The DROP command is used to permanently delete a database object such as a table, database, view, or index. Warning: This action cannot be undone!

    🔹 DROP TABLE

    
    -- Permanently delete a table and its data
    DROP TABLE Students;
    
    -- Drop only if it exists (avoids error)
    DROP TABLE IF EXISTS Students;
    

    🔹 DROP DATABASE

    
    -- Permanently delete an entire database
    DROP DATABASE SchoolDB;
    
    -- Drop only if exists
    DROP DATABASE IF EXISTS SchoolDB;
    

    🔹 DROP VIEW / INDEX

    
    DROP VIEW ActiveStudents;
    DROP INDEX idx_name ON Students;
    
    ⚠️ Caution DROP permanently removes the table, all its data, and its structure. It cannot be rolled back. Always take a backup before dropping critical objects.

    4. TRUNCATE Command

    The TRUNCATE command is used to delete all rows from a table while keeping its structure intact. It's much faster than DELETE because it doesn't log each row deletion.

    
    -- Removes all data but keeps the table structure
    TRUNCATE TABLE Students;
    
    🧠 TRUNCATE vs DELETE vs DROP:
    • DELETE — Removes specific rows (can use WHERE), can rollback
    • TRUNCATE — Removes all rows (faster, no WHERE), resets AUTO_INCREMENT
    • DROP — Removes entire table + structure permanently

    DELETE vs TRUNCATE vs DROP — Quick Comparison

    Feature DELETE (DML) TRUNCATE (DDL) DROP (DDL)
    RemovesSpecific rowsAll rowsEntire table
    WHERE Clause✅ Yes❌ No❌ No
    Rollback✅ Yes❌ No❌ No
    SpeedSlowFastFastest
    StructureKeptKeptRemoved
    Auto Increment Reset❌ No✅ YesN/A

    5. RENAME Command

    The RENAME command is used to rename a table or sometimes a column (via ALTER).

    
    -- Rename a single table
    RENAME TABLE Students TO StudentRecords;
    
    -- Rename multiple tables at once
    RENAME TABLE 
    Teachers TO Faculty,
    Courses TO Subjects;
    

    Common Constraints Used in DDL

    Constraints are rules applied to columns to maintain data integrity. They are defined at table creation or via ALTER.

    1

    NOT NULL

    Ensures the column cannot have NULL values.

    Used for mandatory fields like names or IDs that must always have a value.

    2

    UNIQUE

    Ensures all values in a column are different.

    Useful for fields like emails, phone numbers, or usernames where duplicates aren't allowed.

    3

    PRIMARY KEY

    Combines NOT NULL + UNIQUE — uniquely identifies each record.

    Every table should have one primary key for referential identity and indexing.

    4

    FOREIGN KEY

    Establishes a relationship between two tables.

    Links a column to the PRIMARY KEY of another table, ensuring referential integrity.

    5

    CHECK

    Validates values against a condition before insertion.

    For example, CHECK (age >= 18) ensures only adults can be added.

    6

    DEFAULT

    Sets a default value if none is provided.

    For example, DEFAULT 'Active' for a status column.

    Example: Combining All Constraints

    
    CREATE TABLE Employee (
        emp_id INT PRIMARY KEY AUTO_INCREMENT,
        name VARCHAR(100) NOT NULL,
        email VARCHAR(100) UNIQUE,
        age INT CHECK (age >= 18),
        department VARCHAR(50) DEFAULT 'General',
        manager_id INT,
        FOREIGN KEY (manager_id) REFERENCES Employee(emp_id)
    );
    

    Key Characteristics of DDL

    ✅ Features of DDL

    • Defines the database schema
    • Changes are auto-committed
    • Cannot be rolled back
    • Affects table structure, not data
    • Required before any DML can be used
    • Standardized across all RDBMS

    ⚠️ Limitations

    • Permanent changes — be careful!
    • Cannot use WHERE conditions
    • Some operations lock the table
    • Heavy changes can affect performance
    • Backups recommended before DROP

    Real-World Applications of DDL

    🌍 When DDL is Used

    • Database Design Phase: Creating schemas and tables
    • Project Setup: Initializing tables for new applications
    • Schema Updates: Adding new fields when features evolve
    • Performance Tuning: Creating indexes for faster queries
    • Migrations: Renaming or restructuring tables
    • Cleanup Tasks: Dropping unused tables or test data
    • Database Versioning: Updating schema with ALTER scripts

    Best Practices for Using DDL

    💡 Pro Tips Before Running DDL Commands

    • Always take a backup before using DROP or TRUNCATE
    • Use IF EXISTS / IF NOT EXISTS to prevent errors
    • Follow consistent naming conventions (snake_case)
    • Always define a PRIMARY KEY for every table
    • Use foreign keys to maintain data integrity
    • Avoid frequent ALTERs in production — they can lock tables
    • Document your schema changes using version control
    • Test DDL scripts on a development environment first
    • Use indexes wisely — too many can slow down inserts
    • Prefer schema migrations via tools like Flyway or Liquibase

    Common Mistakes to Avoid

    ❌ Mistake #1 Running DROP TABLE without backup — data is gone forever.
    ❌ Mistake #2 Forgetting IF NOT EXISTS when re-running CREATE scripts — causes errors.
    ❌ Mistake #3 Using TRUNCATE on a table referenced by FOREIGN KEYS — MySQL will block it.
    ✅ Best Practice Always plan schema changes carefully, test them in staging, and use migrations to track every DDL operation.
    📐

    Final Analogy

    DDL is the architectural plan of your database. Once approved, you can renovate (ALTER), demolish (DROP), or build new rooms (CREATE) — but every change reshapes the structure forever.

    🎯 Key Takeaway

    DDL (Data Definition Language) is the backbone of database design. Mastering CREATE, ALTER, DROP, TRUNCATE, and RENAME means mastering the structure behind every database that powers our digital world.

    Practice Quiz 20 MCQs Smart Learning

    Master This Topic with Smart Practice

    Reinforce what you just learned by solving high-quality MCQs. Improve accuracy, boost confidence, and prepare like a topper.

    Topic-wise MCQs
    Instant Results
    Improve Accuracy
    Exam Ready Practice
    Login & Start Quiz Create Free Account
    Save progress • Track results • Learn faster