PostgreSQL – How to Add a New Column with Auto Increment, Increment Factor, Min-Value, and Max-Value

auto-incrementpostgresql

I have table t1 and I would like to add a new column app_id with the properties given below

  • auto increment
  • increment factor(increment by 4)
  • min-value/initial value(100)
  • max-value(2000)

I have tried

alter table t4 
add column app_id int not null auto_increment = 100 ;

but which is not worked.is it possible to add such a column with the properties mentioned above?

Best Answer

Here, you can use sequence to increase app_id value. Please noted if the sequence reach to its maxvalue, you will face this error ERROR: nextval: reached maximum value of sequence .

For example

create table t1 (a int, b int);

create sequence seq_t1
increment by 4
minvalue 100
maxvalue 2000;

alter table t1 add column app_id int default nextval('seq_t1');
insert into t1(a) select generate_series(1, 100) ;

  a  | b | app_id
-----+---+--------
   1 |   |    100
   2 |   |    104
   3 |   |    108
   4 |   |    112
   5 |   |    116
   6 |   |    120
   7 |   |    124