Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I drop 'NOT NULL' from a column in MySQL?

Tags:

A show create table command shows the following:

'columnA' varchar(6) NOT NULL DEFAULT ''; 

How do I modify that column so that the not null is removed? I need it to be:

'columnA' varchar(6) DEFAULT NULL; 

I thought the following would work, but it has no effect:

ALTER TABLE tbl_name MODIFY columnA varchar(6) DEFAULT NULL; 
like image 441
Will Avatar asked Jun 08 '10 20:06

Will


2 Answers

Try this instead:

ALTER TABLE tbl_name MODIFY columnA varchar(6) NULL DEFAULT NULL;  
like image 174
Eric Petroelje Avatar answered Sep 30 '22 18:09

Eric Petroelje


Normally, Eric's answer should work:

ALTER TABLE tbl_name MODIFY columnA varchar(6) NULL DEFAULT NULL;  

(Although the 'NULL DEFAULT NULL' part is optional).

But like you, I had a case that just returned OK without doing anything. In my case it appears to be due to the fact that my key was part of the primary key. So I had to do the following:

ALTER TABLE tbl_name DROP PRIMARY KEY; ALTER TABLE tbl_name MODIFY columnA varchar(6); ALTER TABLE tbl_name ADD PRIMARY KEY (columnA); 

with that last query specifying whatever your primary key actually is.

Also, in case anyone thinks that is too verbose, the following combined query does NOT work, even though it should be identical:

ALTER TABLE tbl_name DROP PRIMARY KEY, MODIFY columnA varchar(6), ADD PRIMARY KEY (columnA); 

I assume that mysql rewrites that last query into a different order so that the primary key still exists when the modify is performed, hence the need to break it out into three statements.

FYI, this is on mysql 5.1.47 but I haven't yet found any documentation indicating why this happens so I don't know what versions are affected.

like image 28
Rob Van Dam Avatar answered Sep 30 '22 18:09

Rob Van Dam