Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto increment feature in Database

I use SQL Server and when I create a new table I make a specific field an auto increment primary key. The problem is some people told me making the field an auto increment for the primary key means when deleting any record (they don't care about the auto increment field number) the field increases so at some point - if the type of my field is integer for example - the range of integer will be consumed totally and i will be in trouble. So they tell me not to use this feature any more.

The best solution is making this through the code by getting the max of my primary key then if the value does not exist the max will be 1 other wise max + 1.

Any suggestions about this problem? Can I use the auto increment feature?

I want also to know the cases which are not preferable to use auto increment ..and the alternatives...

note :: this question is general not specific to any DBMS , i wanna to know is this true also for DBMSs like ORACLE ,Mysql,INFORMIX,....

Thanks so much.

like image 682
Anyname Donotcare Avatar asked Nov 02 '10 07:11

Anyname Donotcare


People also ask

What is auto increment in database?

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.

Where is AUTO_INCREMENT typically used?

Auto Increment is a field used to generate a unique number for every new record added into a table. This is generally used for the primary key column as it becomes easy for the developers to automatically generate a unique number for every new record.

How does the AUTO_INCREMENT work in MySQL?

Auto-increment allows a unique number to be generated automatically whenever a new record is inserted into a table. This feature is especially useful in the primary key field so that the key can be set automatically every time a new record is inserted.

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

You should use identity (auto increment) columns. The bigint data type can store values up to 2^63-1 (9,223,372,036,854,775,807). I don't think your system is going to reach this value soon, even if you are inserting and deleting lots of records.

If you implement the method you propose properly, you will end up with a lot of locking problems. Otherwise, you will have to deal with exceptions thrown because of constraint violation (or even worse - non-unique values, if there is no primary key constraint).

like image 116
Marek Grzenkowicz Avatar answered Oct 18 '22 14:10

Marek Grzenkowicz