Home >Database >Mysql Tutorial >MySQL Terminal: Add and delete column
The ALTER TABLE ... ADD COLUMN command in SQL is used to add one or more columns to an existing table. Here’s the syntax for adding multiple columns:
ALTER TABLE table_name ADD COLUMN column_name1 data_type1 [options], ADD COLUMN column_name2 data_type2 [options], ...;
Example
Suppose you have a table named customers and want to add two columns: email of type VARCHAR(255) and birth_date of type DATE. The command would look like this:
ALTER TABLE customers ADD COLUMN email VARCHAR(255), ADD COLUMN birth_date DATE;
This command will add the email and birth_date columns to the customers table.
The ALTER TABLE ... DROP COLUMN command in SQL is used to delete a column from an existing table. Here’s the syntax:
ALTER TABLE table_name DROP COLUMN column_name;
Example
If you have a table named customers and you want to remove a column called email, the command would look like this:
ALTER TABLE customers DROP COLUMN email;
Warning: Dropping a column is a permanent action and will remove all data stored in that column.
This command will delete the email column from the customers table.
The ALTER TABLE ... ADD COLUMN ... AFTER command in SQL is used to add one or more columns to an existing table, specifying the position of the new columns relative to an existing column. Here’s the syntax for adding multiple columns after a specific column:
ALTER TABLE table_name ADD COLUMN column_name1 data_type1 [options] AFTER existing_column_name, ADD COLUMN column_name2 data_type2 [options] AFTER existing_column_name, ...;
Example
Suppose you have a table named customers and want to add two columns, email of type VARCHAR(255) and birth_date of type DATE, placing them after an existing column called name. The command would look like this:
ALTER TABLE customers ADD COLUMN email VARCHAR(255) AFTER name, ADD COLUMN birth_date DATE AFTER name;
This command will add the email and birth_date columns to the customers table, positioning them after the name column.
The above is the detailed content of MySQL Terminal: Add and delete column. For more information, please follow other related articles on the PHP Chinese website!