Reputation: 3461
I have read most of the posts concerning MySQL ALTER TABLE but can't find an answer to my issue.
I have a script that adds a new column to a table, this works fine but the issue I have is it is not setting the default value for the new column. Am I missing something:
ALTER TABLE Hist ADD S1 VARCHAR( 5 ) DEFAULT '1', ADD comments_S1 TEXT
The above is the code I am using.
Any idea's
Many thanks in advance for your time.
Upvotes: 0
Views: 2344
Reputation: 19372
Seems like something in Your application code sets S1 field to empty string.
ALTER TABLE Hist
ADD S1 VARCHAR(5) DEFAULT '1' NOT NULL,
ADD comments_S1 TEXT;
it will prevent S1 from being empty and automatically change NULL
fields to '1'
Upvotes: 0
Reputation: 1269803
Alas, the default
value gets used only for new rows. The old rows get NULL
. So, simply update them after the alter table:
update hist
set s1 = '1';
This is not really well documented in MySQL, but it is sort-of suggested . .
Alterations that modify only table metadata and not table data are immediate because the server only needs to alter the table .frm file, not touch table contents. The following changes are fast alterations that can be made this way:
. . . - Changing the default value of a column (except for NDB tables).
Adding a column does require a table copy. But the old values are not affected.
Upvotes: 1
Reputation: 521259
I believe the syntax for adding a column to a MySQL table is:
ALTER TABLE table_name ADD COLUMN col type DEFAULT 'default';
You are missing the keyword COLUMN
from your syntax. Try the following:
ALTER TABLE Hist
ADD S1 VARCHAR(5) DEFAULT '1',
ADD comments_S1 TEXT;
Upvotes: 0