Creating a sequence on an existing table

Set the default value when you add the new column:

create sequence rid_seq;
alter table test add column rid integer default nextval('rid_seq');

Altering the default value for existing columns does not change existing data because the database has no way of knowing which values should be changed; there is no “this column has the default value” flag on column values, there’s just the default value (originally NULL since you didn’t specify anything else) and the current value (also NULL) but way to tell the difference between “NULL because it is the default” and “NULL because it was explicitly set to NULL”. So, when you do it in two steps:

  1. Add column.
  2. Change default value.

PostgreSQL won’t apply the default value to the column you just added. However, if you add the column and supply the default value at the same time then PostgreSQL does know which rows have the default value (all of them) so it can supply values as the column is added.

By the way, you probably want a NOT NULL on that column too:

create sequence rid_seq;
alter table test add column rid integer not null default nextval('rid_seq');

And, as a_horse_with_no_name notes, if you only intend to use rid_seq for your test.rid column then you might want to set its owner column to test.rid so that the sequence will be dropped if the column is removed:

alter sequence rid_seq owned by test.rid;

Leave a Comment

deneme bonusudeneme bonusu veren sitelerOnwin Güncel Giriştürkçe altyazılı pornocanlı bahis casino