Oracle – Using SELECT MAX(PK) Instead of SEQUENCE.NEXTVAL

best practicesoracle

I have a client/superior who keeps suggesting that I select max(primary_key)
when I insert a new row.

I gut says it's VERY wrong but I don't have exact reasons to support my suggestion.
The only thing so far I can think of is when two people are trying to insert into the same table and getting data mixed up.

What are the reasons one should not rely on selecting max(primary_key) + 1
to generate a pk value ?

Best Answer

The presentation of the data should not be the determining factor in how the data is stored - especially in the case of a primary key. That would be like saying that all dates need to be stored in the database as strings so that a particular date format could be displayed.

To make the select max(pk) + 1 work in a system with more than one user is to programmatically force only one session to get the next PK value at a time - seriously compromising your concurrency. Either that or you will have to write code to intercept the PK failure and try again.

The data displayed can be formatted in the presentation layer in any way that makes sense. You can do a to_char to add the leading zero's in the select if needed - another string in the record could be appended - whatever would make it look more like a "code". In our environment we just use the generated sequence as the identifier - its more important that it is generated efficiently and is unique than how it looks.