Add new column in mysql
To add a new column in MySQL, you can use the ALTER TABLE
statement. Here is the basic syntax:
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
,DATE
, etc.).
For example, to add a new column called age
with a data type of INT
to a table called users
, you would use the following query:
ALTER TABLE users
ADD COLUMN age INT;
This will add a new column called age
with a data type of INT
to the users
table.
You can also specify additional options when adding a 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
orINDEX
: specifies whether the new column should be indexed or unique.
For example:
ALTER TABLE users
ADD COLUMN email VARCHAR(255) NOT NULL DEFAULT '[email protected]';
This will add a new column called email
with a data type of VARCHAR(255)
, not null, and a default value of '[email protected]'
.
Note that you can only add a column to the end of the table, not in the middle. If you want to add a column in a specific position, you can use the ALTER TABLE
statement with the ADD COLUMN
clause and specify the position using the AFTER
or BEFORE
keyword. For example:
ALTER TABLE users
ADD COLUMN new_column_name INT AFTER existing_column_name;
This will add the new column after the existing_column_name
column.