0

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.

1
  • seems like something in Your application code sets S1 field to empty string Commented Jul 17, 2016 at 13:44

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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;

Comments

0

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.