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

Postgresql

Postgresql Problem Overview


I have a table that has thousands of rows. Since the table wasn't constructed with created_at column initially, there is no way of getting their creation timestamp. It is crucial though to start getting the timestamps for future rows.

Is there a way I can add a timestamp column with default value NOW() so that it won't populate the values to previous rows but only for the future ones?

If I do the ALTER query, it populates all rows with timestamp:

ALTER TABLE mytable ADD COLUMN created_at TIMESTAMP DEFAULT NOW()

Postgresql Solutions


Solution 1 - Postgresql

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();

Solution 2 - Postgresql

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.

Solution 3 - Postgresql

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

Solution 4 - Postgresql

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;

Solution 5 - Postgresql

Try something like:-

ALTER TABLE table_name ADD  CONSTRAINT [DF_table_name_Created] 
DEFAULT (getdate()) FOR [created_at];

replacing table_name with the name of your table.

Solution 6 - Postgresql

This code worked for me

> ALTER TABLE ABC ADD COLUMN recievedon TIMESTAMP DEFAULT NOW()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArturView Question on Stackoverflow
Solution 1 - PostgresqlPhilip CoulingView Answer on Stackoverflow
Solution 2 - PostgresqlRenzoView Answer on Stackoverflow
Solution 3 - PostgresqlMustafa Ahmad FathyView Answer on Stackoverflow
Solution 4 - PostgresqlMarkView Answer on Stackoverflow
Solution 5 - PostgresqlMichael Gungaram-SmithView Answer on Stackoverflow
Solution 6 - PostgresqlChathuranga RanasinghaView Answer on Stackoverflow