faqts : Computers : Databases

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

6 of 7 people (86%) answered Yes
Recently 6 of 7 people (86%) answered Yes


Is it good practice to generate a random number to be used as primary key when inserting?

Jan 31st, 2008 09:56
dman, Geir Pedersen, Arsen Yeremin, http://sturly.com

All primary key values in a table must be unique. If you have an 
integer primary key field, the same value can not appear in this field 
in two different records. Random number generators give no guaranty 
that they will not produce an already generated number, so they are not 
suitable as a source for primary key values. 
In general you should look at the data you want to store in your table 
and look for any piece of information that is naturally unique for all 
records. Use this as your primary key.  
If you need to generate a primary key value, use some form of 
sequential number generator built into your database system. Many 
database systems, including PostgreSQL, supports creating sequential 
number generators using the CREATE SEQUENCE command.