Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upper limit for autoincrement primary key in SQL Server

What is the upper limit for an autoincrement primary key in SQL Server? What happens when an SQL Server autoincrement primary key reaches its upper limit?

like image 706
Dema Avatar asked Nov 04 '08 13:11

Dema


People also ask

What is primary key Autoincrement?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

What happens if auto increment reaches limit?

When the AUTO_INCREMENT column reaches the upper limit of data type then the subsequent effort to generate the sequence number fails. That is why it is advised to use a large enough integer data type for the AUTO_INCREMENT column to hold the maximum sequence value required by us.

How do I set Autoincrement value?

In MySQL, the syntax to change the starting value for an AUTO_INCREMENT column using the ALTER TABLE statement is: ALTER TABLE table_name AUTO_INCREMENT = start_value; table_name. The name of the table whose AUTO_INCREMENT value you wish to change.

Is primary key always auto increment?

A primary key is by no means required to use the auto_increment property - it just needs to be a unique, not-null, identifier, so the account number would do just fine.


1 Answers

Joel's answer is correct, it is the upper limit of whatever datatype you use.

Here's an example of two of them:

  • int: 2^31-1 (2,147,483,647)
  • bigint: 2^63-1 (9,223,372,036,854,775,807)

I have actually hit the limit at a job I worked at. The actual error is:

     Msg 8115, Level 16, State 1, Line 1     Arithmetic overflow error converting IDENTITY to data type int.     Arithmetic overflow occurred. 

There are a couple fixes to this I can think of off the top of my head. Number 1 is probably very hard and not very likely, number 2 is easy, but will probably cause problems in your code base.

  1. If the identity column doesn't matter to you (it's not a Foreign Key, etc.) then you can just reseed the database and reset the identity column.
  2. Change your identity column to a bigger number. So for example if you've overflowed an int, change your identity column to a big int. Good luck overflowing that :)

There are probably other fixes, but there is no magic bullet easy one. I just hope this doesn't happen in a table that is the center of a bunch of relationships, because if it does, you're in for a lot of pain. It's not a hard fix, just a tedious and long one.

like image 68
CubanX Avatar answered Oct 11 '22 13:10

CubanX