Alter table with new column mysql
To add a new column to a table in MySQL, you can use the following SQL command:
ALTER TABLE table_name
ADD COLUMN new_column_name data_type;
Here:
table_name
is the name of the table you want to modify.new_column_name
is the name of the new column you want to add.data_type
is the data type of the new column (e.g.int
,varchar
,datetime
, etc.).
For example, to add a new column called age
with a data type of int
to a table called employees
, you would use the following command:
ALTER TABLE employees
ADD COLUMN age int;
This will add a new column called age
with a data type of int
to the employees
table.
You can also specify additional options when adding a new column, such as:
DEFAULT
value: specifies the default value for the new column.NULL
orNOT NULL
: specifies whether the new column can contain null values.UNIQUE
orNOT UNIQUE
: specifies whether the new column can have duplicate values.
For example:
ALTER TABLE employees
ADD COLUMN age int DEFAULT 25 NOT NULL;
This will add a new column called age
with a data type of int
, a default value of 25, and not allowing null values.
Note: You can only add a new column to the end of the table, you can't add it in the middle of the table.
Also, you can use ALTER TABLE table_name ADD COLUMN new_column_name AFTER existing_column_name
to add a new column after a specific existing column.
For example:
ALTER TABLE employees
ADD COLUMN new_column_name int AFTER age;
This will add a new column called new_column_name
with a data type of int
after the age
column.