Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL sequence that ensure a unique ID

Tags:

postgresql

Having a table with a columnn ID as primary key, and a column MyNumber that contains integers defined by the sequence myUniqueSequence. I would like to define myUniqueSequence in PostgreSQL that will return the next free and unique number for the column MyNumber.

This means, the next time a new row is created programatically will start by number 1, if it's free it will use it for the column myNumber, if not, it tries with 2 and so on.

like image 336
Hectoret Avatar asked May 18 '11 14:05

Hectoret


1 Answers

Use the serial data type for your column (instead of your own sequence):

http://www.postgresql.org/docs/9.0/static/datatype-numeric.html#DATATYPE-SERIAL

like image 77
Lukas Eder Avatar answered Oct 14 '22 17:10

Lukas Eder