Tuesday, December 11, 2012

Add auto increment column in PostgreSQL

In PostgreSQL, we cannot just add an column and mark it as auto increment like in MySQL or SQL Server. Instead, we have to create an sequence and link it to the specified column.
1. Assume that we have a table called [testtbl] with an unique column called [id]
2. Generate sequence

1CREATE SEQUENCE <Sequence name>

==>

1CREATE SEQUENCE <testtbl_id_seq>

※After the sequence’s already created, we can call NEXTVAL(‘<Sequence name>’) to generate a new value automatically.

3. Link the sequence to the unique column 

 

1ALTER TABLE <Table name>
2ALTER COLUMN <Column name>
3SET DEFAULT NEXTVAL(<Created sequence name>);     ==> 
1ALTER TABLE testtbl
2ALTER COLUMN id
3SET DEFAULT NEXTVAL('testtbl_id_seq');
 

No comments:

Post a Comment