Data definition language - MySQL
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.
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:
| Command | Purpose | Example Use |
|---|---|---|
| CREATE | Creates new database objects | Create database, table, view, index |
| ALTER | Modifies existing structure | Add/drop/modify columns |
| DROP | Deletes database objects permanently | Remove a table or database |
| TRUNCATE | Removes all rows but keeps structure | Empty a table quickly |
| RENAME | Renames a database object | Rename 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)
);
PRIMARY KEY— Uniquely identifies each rowAUTO_INCREMENT— Auto-generates unique valuesNOT NULL— Column cannot be emptyUNIQUE— Ensures unique valuesDEFAULT— Sets a default value when not providedCHECK— 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;
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;
- 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) |
|---|---|---|---|
| Removes | Specific rows | All rows | Entire table |
| WHERE Clause | ✅ Yes | ❌ No | ❌ No |
| Rollback | ✅ Yes | ❌ No | ❌ No |
| Speed | Slow | Fast | Fastest |
| Structure | Kept | Kept | Removed |
| Auto Increment Reset | ❌ No | ✅ Yes | N/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.
NOT NULL
Ensures the column cannot have NULL values.
Used for mandatory fields like names or IDs that must always have a value.
UNIQUE
Ensures all values in a column are different.
Useful for fields like emails, phone numbers, or usernames where duplicates aren't allowed.
PRIMARY KEY
Combines NOT NULL + UNIQUE — uniquely identifies each record.
Every table should have one primary key for referential identity and indexing.
FOREIGN KEY
Establishes a relationship between two tables.
Links a column to the PRIMARY KEY of another table, ensuring referential integrity.
CHECK
Validates values against a condition before insertion.
For example, CHECK (age >= 18) ensures only adults can be added.
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
DROPorTRUNCATE - Use
IF EXISTS/IF NOT EXISTSto 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
DROP TABLE without backup — data is gone forever.
IF NOT EXISTS when re-running CREATE scripts — causes errors.
TRUNCATE on a table referenced by FOREIGN KEYS — MySQL will block it.
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.
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.