In a database, I saw many tables in which the Primary-Key(PK) is AUTO_INCREMENT type.
Suppose I have a table Children created as follows:
CREATE TABLE Children(
childNo INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY,
name VARCHAR(25),
age INTEGER,
address VARCHAR(100)
)
-
ChildNoisAUTO_INCREMENT, but once I have inserted a row, how do I know which value was assigned for a child (for a name)? and bad choice forPK. -
If I search on child’s name it would be inefficient (and not guaranteed to be unique). For this reason I think keeping
AUTO_INCREMENTas primary key denotes weak schema design? -
Suppose I have another table
Parentsand there I need to keepChidNoasForeign Key (FK). Then it would be complex. -
If there is a recursive association then keeping PK an AUTO_INCREMENT would be much bad.
Keeping auto-increment field in a relation denotes that normalization is not appropriate?
In some table instead to introduce an extra AUTO_INCREMENT field I would like to keep all column as PK. Am I wrong?
Because my thoughts are against using AUTO_INCREMENT, please suggest me also usability to keep AUTO_INCREMENT field?
The auto-increment PK column can be called a surrogate key.
Using surrogate keys can be a helpful optimization in some cases:
So there are legitimate benefits for surrogate keys.
That said, surrogate keys are often over-used. Many application frameworks (e.g. Ruby on Rails) use a default that every table has an integer surrogate key named
IDregardless of whether it’s appropriate. You can specify a PK column on a table by table basis, but many programmers take the default as a rule, and this leads them to have some senseless table designs. The worst example I’ve seen is for every many-to-many table to have a superfluousIDcolumn.For what it’s worth, using a surrogate key has nothing to do with normalization. That is, rules of normalization neither encourage nor discourage using surrogate keys.
Every database that supports surrogate keys also provides a function that returns the most recently generated id value in the current session. As @JStead mentioned, in SQL Server it’s
@@IDENTITYorSCOPE_IDENTITY(). In MySQL, it’sLAST_INSERT_ID(). And so on.These functions return only a single value, so you can’t get all the generated id values if you insert multiple rows in a single INSERT statement. That’s a limitation.