How can you add a column to a table in MySQL and set a default value for it?

One way to add a new column with a default value in MySQL is by using the ‘ALTER TABLE’ statement. Here is an example:

ALTER TABLE 表名

ADD 列名 数据类型 DEFAULT 默认值;

In this case, ‘table name’ refers to the name of the table where the field is being added, ‘column name’ is the name of the field being added, ‘data type’ refers to the data type of the new field, and ‘default value’ is the default value for the new field.

For example, suppose there is a table called `users`, and now we want to add a new field called `age` to this table with a default value of `18`, you can execute the following SQL statement:

ALTER TABLE users

ADD age INT DEFAULT 18;

This will add a new field called `age` to the `users` table in the database, with an integer data type (INT), and set the default value to `18`.

Note that when adding a new field with default values to a table that already contains data, the default value will automatically be applied to existing data rows where this field is missing.

bannerAds