mysql: add not null constraint to existing column

Trabla: mysql: add not null constraint to existing column

Solving:

Example:
We have column "token" varchar(32) in table "my_table" with values and nulls.

1. Update table "my_table" - set some value ( NOT NULL ) to column "token"

UPDATE TABLE my_table SET token = '-1' WHERE (token IS NULL OR token = '') 
AND id >0;

2. Add NOT NULL constraint

ALTER TABLE my_table 
MODIFY token varchar(32) NOT NULL 
DEFAULT '-1' COMMENT 'Store token here';

Official Docs: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

No comments:

Post a Comment