๐ What is DDL (Data Definition Language)?
DDL (Data Definition Language) is the part of SQL used to define and manage the structure of a database โ tables, columns, indexes, constraints, schemas, etc.
If a database were a building, DDL would be the architecture and construction tools โ deciding how many rooms (tables) there are, their size (columns), and rules (constraints).
๐ง Key DDL Commands
| Command | What It Does |
|---|---|
CREATE | Creates new database objects like tables, views, indexes, schemas |
ALTER | Modifies the structure of existing objects (add/remove column, change type) |
DROP | Deletes an object permanently (e.g., table, view, index) |
TRUNCATE | Deletes all rows from a table quickly (but keeps the structure intact) |
RENAME | Renames an object like a table or column |
๐ ๏ธ Example Usage:
1. CREATE
CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(255) UNIQUE
);Creates a
userstable with 3 columns and constraints.
2. ALTER
ALTER TABLE users ADD COLUMN created_at TIMESTAMP;Adds a new column to the
userstable.
3. DROP
DROP TABLE users;Permanently deletes the
userstable and all its data.
4. TRUNCATE
TRUNCATE TABLE users;Quickly deletes all data in
users, but keeps the table.
5. RENAME
ALTER TABLE users RENAME TO customers;Renames the
userstable tocustomers.
โ ๏ธ Important Notes:
| Concept | Explanation |
|---|---|
| DDL is auto-committed | Changes are immediate and permanent โ no need to COMMIT |
| Cannot be rolled back (usually) | Once a DROP is done, the data is gone unless backups exist |
| Impacts the schema | DDL affects how the data is stored, not the data itself |
๐งช Real-World Analogy:
-
A developer uses DDL to create and design the database structure before the app even has users.
-
Changing a column name or data type later is also DDL.
๐ง Interview Line:
โDDL defines the structure of the database using commands like
CREATE,ALTER, andDROP. It controls how data is stored, not the data itself, and its changes are auto-committed.โ