MySQL
Chapter 5 - DDL (Data Definition Language)
ALTER TABLE
The ALTER TABLE statement in MySQL is used to modify the structure of an existing table without losing any data. This includes adding, modifying, or dropping columns, as well as renaming columns or tables and adding constraints. Modifying tables is a common task as application requirements evolve.
Below is a guide on how to use the ALTER TABLE command, with practical examples for a company database.
Common Uses of ALTER TABLE
- Add Columns
- Use
ADD COLUMNto add new fields to an existing table.
- Use
- Modify Columns
- Use
MODIFY COLUMNto change the data type or constraints of an existing column.
- Use
- Drop Columns
- Use
DROP COLUMNto remove unnecessary columns.
- Use
- Rename Columns
- Use
CHANGE COLUMNto rename a column or change its definition.
- Use
- Add or Drop Constraints
- Use
ADD CONSTRAINTorDROP CONSTRAINTto manage table constraints.
- Use
Code Samples
- Add a New Column to the
employeesTableALTER TABLE employees ADD COLUMN phone_number VARCHAR(20);- Adds a new column
phone_numberto theemployeestable to store the employee's contact number.
- Adds a new column
- Modify an Existing Column in the
departmentsTableALTER TABLE departments MODIFY COLUMN location VARCHAR(150) NOT NULL;- Changes the
locationcolumn to be of typeVARCHAR(150)and sets it asNOT NULL.
- Changes the
- Drop a Column from the
branchesTableALTER TABLE branches DROP COLUMN postal_code;- Removes the
postal_codecolumn from thebranchestable as it is no longer needed.
- Removes the
- Rename a Column in the
companyTableALTER TABLE company CHANGE COLUMN founded established DATE;- Renames the
foundedcolumn toestablishedin thecompanytable, keeping the data type asDATE.
- Renames the
- Add a Foreign Key Constraint to the
employeesTableALTER TABLE employees ADD CONSTRAINT fk_department FOREIGN KEY (department_id) REFERENCES departments(department_id);- Adds a foreign key constraint to the
department_idcolumn in theemployeestable, linking it to thedepartment_idin thedepartmentstable.
- Adds a foreign key constraint to the
By using the ALTER TABLE command with these examples, beginners can easily modify their table structures as needed. Adjust the commands based on your specific requirements and database design.
To gain complete access, login with gmail or outlook, no need of signup, click here


Comments Not Found