Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I alter a mysql table column defaults?

I have a table with a column of type timestamp which defaults current_timestamp and updates to current_timestamp on every update.

I want to remove the "on update" feature on this column. How do I write the alter statement?

I tried the following:

ALTER TABLE mytable alter column time  set DEFAULT now(); 

but this didn't work.

like image 647
Tihom Avatar asked Nov 20 '09 12:11

Tihom


People also ask

How do I change the default value of a column in a table?

Changing a Column's Default Value. To set a new default for a column, use a command like: ALTER TABLE products ALTER COLUMN price SET DEFAULT 7.77; Note that this doesn't affect any existing rows in the table, it just changes the default for future INSERT commands.

Can we ALTER column with default value?

You cannot alter a column to specify a default value if one of the following conditions exists: The table is referenced by a view.

How do I change my default value?

Set a default valueRight-click the control that you want to change, and then click Properties or press F4. Click the All tab in the property sheet, locate the Default Value property, and then enter your default value.

How do I change column properties in MySQL?

To change a column's definition, use MODIFY or CHANGE clause along with the ALTER command. mysql> ALTER TABLE testalter_tbl MODIFY c CHAR(10); With CHANGE, the syntax is a bit different. After the CHANGE keyword, you name the column you want to change, then specify the new definition, which includes the new name.


2 Answers

Pete was almost correct but used the wrong syntax for 'change':

ALTER TABLE mytable CHANGE `time` `time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP 

Notice that you must repeat the column name. Also, make sure you are using backticks instead of single quotes to escape the column name time, which prevents it from being interpreted as the mysql column type of time.

By specifying the DEFAULT of CURRENT_TIMESTAMP, MySQL will no longer automatically update the column. From the MySQL Manual:

With a DEFAULT CURRENT_TIMESTAMP clause and no ON UPDATE clause, the column has the current timestamp for its default value but is not automatically updated.

like image 139
jonstjohn Avatar answered Sep 20 '22 20:09

jonstjohn


You can't AFAIK use functions such as NOW() as a default.

Try

ALTER TABLE `mytable` CHANGE `time` `time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP 

(Edited to add escaping and second use of field name)

like image 29
Pete Avatar answered Sep 23 '22 20:09

Pete