Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add timestamp column with default NOW() for new rows only

Tags:

postgresql

People also ask

How do I add a default value to a timestamp column?

Use of DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP is specific to TIMESTAMP. The DEFAULT clause also can be used to specify a constant (nonautomatic) default value; for example, DEFAULT 0 or DEFAULT '2000-01-01 00:00:00'.

How do I add a column to a timestamp in SQL?

You need to use ALTER command to add a created at column to an already created table in MySQL. Now implement the above syntax to add a “created at” column with type timestamp and default with CURRENT_TIMESTAMP. Note - Keep in mind if you are giving a space between created at then you need to use the backtick symbol.

How do I set the default time in PostgreSQL?

We can provide the default value of the current timestamp to a column in PostgreSQL by using the default keyword. We can provide default current timestamp value to the column at the time of table creation.

How do I set a default column in a snowflake?

Adding default values in Snowflake is carried out using the “ALTER” command. Alter commands change the table name and column name.


You need to add the column with a default of null, then alter the column to have default now().

ALTER TABLE mytable ADD COLUMN created_at TIMESTAMP;
ALTER TABLE mytable ALTER COLUMN created_at SET DEFAULT now();

You could add the default rule with the alter table,

ALTER TABLE mytable ADD COLUMN created_at TIMESTAMP DEFAULT NOW()

then immediately set to null all the current existing rows:

UPDATE mytable SET created_at = NULL

Then from this point on the DEFAULT will take effect.


For example, I will create a table called users as below and give a column named date a default value NOW()

create table users_parent (
    user_id     varchar(50),
    full_name   varchar(240),
    login_id_1  varchar(50),
    date        timestamp NOT NULL DEFAULT NOW()
);

Thanks


minor optimization.

select pg_typeof(now());   --returns: timestamp with time zone. So now include timezone.        

So better with timestamptz.

begin;
ALTER TABLE mytable ADD COLUMN created_at TIMESTAMPTZ;
ALTER TABLE mytable ALTER COLUMN created_at SET DEFAULT now();
commit;