简体   繁体   中英

MySQL Alter table add column with default of 1

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.

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.

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;

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'

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