How can a field be added to a table in MySQL?
You can use the ALTER TABLE statement to add a new field to a table in a MySQL database.
The grammar is as follows:
Add a column with a specified data type and constraints to the table.
Example:
Sample:
The above example adds a field named email with a data type of VARCHAR(50) to the users table.
To set constraints for a field, you can add constraints after the data type. For example:
The above example adds a field called email to the users table and sets a NOT NULL constraint, meaning the field cannot be empty.
For setting a default value for a field, you can use the DEFAULT keyword. For example:
The above example adds a field called email to the users table, with a NOT NULL constraint and a default value of ‘无’.
It is important to note that when adding a new field to a table, if there is already existing data in the table, the new field will default to NULL. If you want to set a default value for existing data, you can use the UPDATE statement. For example:
The above query will update the email field of all user records in the users table where the email field is NULL to a value of ‘无’.
It is important to note that to add a primary key field to an existing table, you can use the following syntax:
Add a column with a specified data type as a primary key to the table. For example:
Add a column named “id” to the table “users” with the data type INT and set it as the primary key.