Oracle FAQ | Your Portal to the Oracle Knowledge Grid |
Home -> Community -> Usenet -> c.d.o.misc -> Re: Please help with no-gap autoincrement field
g_chime_at_yahoo.com wrote:
> My boss wants to have an autoincrement index with no gaps, even when > the insert fails. > Since MySQL has this feature, some of the code depends on it. > > I am new to ORACLE and based on my limited knowledge, a "before insert" > type trigger won't do the job and was unable to make a "after > insert" type trigger work. > > My question was / is: is there an automated way to have an > autoincrement field with no gaps? > > I understand that the reason for having such a field is questionable. > Also, I know that changing the code that depends on such an index is an > option. Still, I am wondering if it can be easily implementid in > ORACLE. > > Thanks. > > Mark D Powell wrote:
The only way I can think of to ensure that you do not have gaps in the number is to implement your own scheme. Create a table with one column which contains the sequence value. When you need the "next" number, explicitly lock the table, read the value, increment it by one, then then update the table. Your transaction can then roll this back since all you are doing is DML on the table.
Note that this serializes your application. Concurrent users will have to wait for another user to unlock the table. This method is not recommended and should be avoided at all costs.
Every time my boss has insisted on no gaps in the sequence, I ask questions and find out that this is just what is expected. In all my years, I have yet to see a valid reason not to allow gaps. Even your checking account allows gaps in the check numbers when you void a check. And most companies really do not require explicitly sequential invoice numbers without gaps. These numbers are purely artificial. The only real requirement is that the numbers be unique for each instance of the entity.
If gaps are not allowed, then how do you restrict someone from deleting a record? Or updating the sequence value? While mySQL and SQL Server will use autoincrementing fields, you can easily remove a row from the table....oops...a gap in the sequence was just created.
HTH,
Brian
-- =================================================================== Brian Peasland oracle_dba_at_nospam.peasland.net http://www.peasland.net Remove the "nospam." from the email address to email me. "I can give it to you cheap, quick, and good. Now pick two out of the three" - UnknownReceived on Wed Jun 14 2006 - 11:18:31 CDT