简体   繁体   中英

MySQL change column default to not null

ALTER TABLE `pages` MODIFY `views` INT(11) NOT NULL DEFAULT 0

Trying to alter a column in a table which is currently allows NULL and has no default.

I want it to be NOT NULL and have a default of 0 .

The Error message I get is

Invalid use of NULL value

This is because the table already has a row or more with null value, you might need to update those to 0 before executing ALTER table, eg:

UPDATE test SET views = 0 WHERE views IS NULL;
ALTER TABLE test MODIFY COLUMN views int NOT NULL DEFAULT 0;

Here's the SQL Fiddle (commenting out update statement will result in the same error).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM