MySQL DDL Table Structure
The ALTER TABLE statement in MySQL is used to modify the structure of an existing table. You can add new columns, remove existing ones, or change their definitions without dropping the table.
FIRST or AFTER column_name.Basic syntax to add a new column:
-- Add a new column to an existing table
ALTER TABLE table_name
ADD column_name datatype;
Other common ALTER TABLE operations:
-- Add a column at a specific position
ALTER TABLE table_name
ADD new_column datatype AFTER existing_column;
-- Change datatype or definition of an existing column
ALTER TABLE table_name
MODIFY column_name new_datatype;
-- Remove a column from the table
ALTER TABLE table_name
DROP COLUMN column_name;
Suppose you have an Employees table and you want to store the email address of each employee.
-- Add an Email column to the Employees table
ALTER TABLE Employees
ADD Email VARCHAR(255);
Employees table for modification.Email with a maximum length of 255 characters.NULL in the new column (unless you later update them).ADD, e.g., VARCHAR(255), INT, DATE.AFTER column_name to control where the new column appears in the table structure.DROP COLUMN carefully; once a column is dropped, its data is permanently lost.ALTER TABLE statements on a backup or test database before changing production tables.Students and then:
PhoneNumber with type VARCHAR(15).DateOfBirth with type DATE after the StudentName column.ALTER TABLE to:
INT to BIGINT.
-- Example practice task on your own table
ALTER TABLE YourTableName
ADD CreatedAt DATETIME;
ALTER TABLE YourTableName
MODIFY CreatedAt TIMESTAMP;