tlre0952b
tlre0952b

Reputation: 751

MySQL ALTER/UPDATE table

I have a table that contains NULL values. This table is meant only to store numerical values, except the second column which contains a time-stamp for each record. This table has been in use for some time and so has accumulated a lot of NULL values in varying columns. Here's the table's description:

+-----------------------------------------+-----------+------+-----+-------------------+----------------+
| Field                                   | Type      | Null | Key | Default           | Extra          |
+-----------------------------------------+-----------+------+-----+-------------------+----------------+
| results_id                              | int(11)   | NO   | PRI | NULL              | auto_increment |
| time_stamp                              | timestamp | NO   |     | CURRENT_TIMESTAMP |                |
| test_col                                | int(11)   | YES  |     | NULL              |                |
| test_col-total                          | int(11)   | YES  |     | NULL              |                |
| test_col_B                              | int(11)   | YES  |     | NULL              |                |
| test_col_B-total                        | int(11)   | YES  |     | NULL              |                |
+-----------------------------------------+-----------+------+-----+-------------------+----------------+

12 rows in set (0.01 sec)

I now want to UPDATE/ALTER the table so that:

I am entirely stuck with this because on the one hand I want my SQL query to update a new rule to the table while on the other change current NULL values and as a novice this is a little more intermediate for my current understanding.

So far I have:

ALTER TABLE `results` MODIFY `<col_name>` INT(11) NOT NULL;

And I will do this for each column that currently allows NULL values. However, I do not know how to change stored NULL values to '0'.

Any input appreciated.

Upvotes: 1

Views: 1556

Answers (2)

Tin Tran
Tin Tran

Reputation: 6202

to change NULL values to 0 try

UPDATE results SET `col_name` = 0 WHERE `col_name` IS NULL;


to change columns to have NOT NULL and default to 0 try

ALTER TABLE results MODIFY `col_name` INT(11) NOT NULL DEFAULT 0;


you have to do it in the above order, i just tested this on http://sqlfiddle.com/

Upvotes: 2

Filipe Silva
Filipe Silva

Reputation: 21657

First change your values to 0 where they are null:

UPDATE results SET col1 = 0 WHERE col1 IS NULL;
...

Then you can add a DEFAULT of 0, that will be added whenever you supply no values to that table on an insert

ALTER TABLE `results` MODIFY `<col_name>` INT(11) NOT NULL DEFAULT 0;

Upvotes: 0

Related Questions