Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would primary keys be stored in another table, instead of using auto-increment?

In a third party software that uses a relational database (mssql, but this question is not limited to this specific database) I have seen the following construct:

Several tables have integer primary keys, which are not auto-increment. Instead, the currently highest primary-key (per table) is stored inside another table. That table contains only two columns: tableName und currentPrimaryKey.

Whenever a new row is inserted in one of the tables, a stored procedure is used to lock the primary-key-table, obtain the next-primary-key-to-be-used, und unlock the primary-key-table again.

My question is: Are there any advantages this construct offers, compared to simply using an auto-increment primary key?

like image 943
Majiy Avatar asked Dec 31 '25 15:12

Majiy


1 Answers

It will guarantee sequential assignment with no gaps, which IDENTITY doesn't guarantee, and may be required under certain legal/regulatory regimes.

At the cost of serializing all inserts, which is a high cost to pay if the lack of gaps isn't a requirement. (IDENTITY instead acts "outside" of any transaction and so if a transaction is rolled back, that particular identity value is unused)

like image 142
Damien_The_Unbeliever Avatar answered Jan 03 '26 21:01

Damien_The_Unbeliever



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!