π οΈ Mastering SQL DDL Commands: CREATE, ALTER, DROP, and More
When working with databases, the Data Definition Language (DDL) is your toolkit for creating and modifying database structures like tables, columns, and constraints. Whether you're building a database from scratch or evolving your schema, these commands are essential.
Letβs explore DDL commands with clear syntax examples and practical use cases.
π§ 1. CREATE β Build New Tables and Structures
π§± Create a Basic Table
sqlCopyEditCREATE TABLE Student (
S_ID NUMBER,
Name CHAR(20),
Marks NUMBER
);
π Create a Table with Primary Key
sqlCopyEditCREATE TABLE Student (
S_ID NUMBER PRIMARY KEY,
Name CHAR(20),
Marks NUMBER
);
π Create a Table with Foreign Key
sqlCopyEditCREATE TABLE Orders (
OrderID NUMBER PRIMARY KEY,
StudentID NUMBER,
FOREIGN KEY (StudentID) REFERENCES Student(S_ID)
);
π Create a Table from Another Table
This copies structure and data:
sqlCopyEditCREATE TABLE TopStudents AS
SELECT * FROM Student
WHERE Marks > 75;
π οΈ 2. ALTER β Modify Existing Tables
You can add or change columns, rename columns, or manage constraints.
β Add a Column
sqlCopyEditALTER TABLE Student
ADD Age NUMBER;
π Modify Column Data Type
sqlCopyEditALTER TABLE Student
MODIFY Name VARCHAR(30);
βοΈ Rename a Column
sqlCopyEditALTER TABLE Student
RENAME COLUMN Name TO FirstName;
β Drop a Column
sqlCopyEditALTER TABLE Student
DROP COLUMN Age;
π Adding Constraints AFTER Table Creation
π Add Primary Key
sqlCopyEditALTER TABLE Student
ADD CONSTRAINT pk_student PRIMARY KEY (S_ID);
π Add Foreign Key
sqlCopyEditALTER TABLE Orders
ADD CONSTRAINT fk_orders_student
FOREIGN KEY (StudentID) REFERENCES Student(S_ID);
π Add Unique Constraint
sqlCopyEditALTER TABLE Student
ADD CONSTRAINT unique_name UNIQUE (Name);
π Dropping Constraints
sqlCopyEditALTER TABLE Student
DROP CONSTRAINT pk_student;
π§Ή 3. DROP β Permanently Delete Tables or Views
Deletes the table and all its data and structure.
sqlCopyEditDROP TABLE Student;
If the table has dependent constraints:
sqlCopyEditDROP TABLE Student CASCADE CONSTRAINTS;
π§½ 4. TRUNCATE β Wipe All Rows (Keep Structure)
sqlCopyEditTRUNCATE TABLE Student;
β οΈ This is faster than DELETE but cannot be rolled back.
π 5. RENAME β Rename Tables
sqlCopyEditRENAME Student TO StudentRecords;
π Quick Reference Summary
| DDL Command | Purpose |
CREATE | Create a table or object |
ALTER | Modify structure (columns, constraints) |
DROP | Permanently delete a table |
TRUNCATE | Delete all rows, keep structure |
RENAME | Change the name of a table |
π Final Tips
Always name your constraints for easier management.
Use
ALTERto evolve your schema instead of dropping and recreating tables.For development, test your DDL changes in a safe environment before applying them to production.