How to set the default value for a field in MySQL to 0?

In MySQL, you can use the DEFAULT keyword to set a field’s default value to 0. The specific steps are as follows:

  1. When creating a table, add DEFAULT 0 after the field definition.

For example, create a table called students with a field called score, its default value is 0.

CREATE TABLE students (
    id INT,
    name VARCHAR(255),
    score INT DEFAULT 0
);

This way, when inserting a new record, if the value of the score field is not specified, it will automatically be set to 0.

  1. If a table has already been created, you can use the ALTER TABLE statement to modify the default value of a field.

For example, change the default value of the score field in the students table to 0.

ALTER TABLE students ALTER COLUMN score SET DEFAULT 0;

In this way, the originally empty score field will be set to 0.

Please note that if a record already exists in the table and a field value is not specified, the default value will not be applied. Only when inserting a new record will the default value be used if a field value is not specified.

广告
Closing in 10 seconds
bannerAds