Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

auto-increment

Status
Not open for further replies.

smatguy

Instructor
Mar 20, 2005
1
MY
how to create auto_increment like we have in mysql in postgresql?
 
First the bad news :-0

It is handled in a separate function, called a SEQUENCE. Sequences are created separately from the table, but can be used to increment values in a column. This may seem like more of a pain than MySQL, but they actually provide a lot more flexibility and interesting functionality. For example, a sequence can be used by more than one table, but at each use the sequence progresses, so that the columns in each table using those keys would have numbers that are not only unique inside that column, but unique among all the other columns. Also, a sequence does not need to be just 1,2,3,4,etc... It could be 5,10,15,etc...

Then the good news ;-)

Fortunately, if you use the datatype serial in your column creation statement, a sequence is implicitly created for your table, so for basic stuff, you don't even have to think about it. Also, PostgreSQL automatically creates an index on the first column if you don't specify any sort of key.

Here's an example. If I entered the following into the psql console:

Code:
CREATE TABLE myinfo(id serial, Thing varchar(50), Description text);

The response I would get is:

Code:
NOTICE: CREATE TABLES will create implicit sequence 'myinfo_id_seq' for SERIAL column 'myinfo.id'
NOTICE: CREATE TABLE/UNIQUE will create implicit index 'myinfo_id_key' for table 'myinfo';
CREATE
So you can see that PostgreSQL gives you a lot more freedom to do other things, but is optimized for quickly entering defaults.
-------------------------------------------

"Calculus is just the meaningless manipulation of higher symbols"
                          -unknown F student
 
You can also change the field you like to auto_increment to type serial. This auto_increments automatically and creates that sequence for you...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top