Adding column to PostgreSQL with default value but without impacting current rows

Viewed 188

I want to add a column in a Postgres table. I want that the value for existing rows will be null but for new rows, it will take the default value that I'll specify in the query.

I'm running this query-

ALTER TABLE events 
ADD COLUMN event_timestamp timestamp default current_timestamp

This is running fine but it is populating the current timestamp for existing rows as well. How to change the query so that it will not add a default value for existing rows?

1 Answers

Do it with two statements:

ALTER TABLE events ADD COLUMN event_timestamp timestamp;
ALTER TABLE events ALTER event_timestamp SET DEFAULT current_timestamp;
Related