de said:
Hi,
I'm kinda new to db building and I was wondering why a primary key
should be an ID (AutoNumber). I have a table with users where the
field Username should also be unique. Why shouldn't I set the
Username field as primary key?
Somewhat of a "religious" topic. There are fanatics on both ends of this
spectrum. Some that would NEVER use anything but natural data fields for their
PKs and others who just automatically use an AutoNmber on every table they ever
build and wouldn't consider doing anything else.
Theoritically, any field (or combination of fields) that is unique can be your
primary key. It is a big advantage though if the PK is also very unlikely to
ever change. This is not actually such a big deal in Access/Jet databases since
Jet supports building relationships which will automatically cascade updates and
deletions to PK values. Still, there are advantages to PKs which don't change.
"Natural" keys consisting of real data columns often fall short in that regard.
Also, with natural keys you often need to use more than one column to create a
unique value for a PK. There's nothing wrong with that (in theory), but it
means that you have to build more foreign key columns in related tables to build
the relationships.
For these reasons many people prefer using a numeric "surrogate" key for the PK
and for relating to other tables because it is always a single numeric column
that need never change (since it has nothing to do with the data). Of course,
you should still put unique indexes on the natural fields that would otherwise
have been your PK to maintain data integrity.
If you have a good natural candidate field for your PK there is no reason at all
not to use it as long as you consider the above and don't foresee any problems.
Personally I will use natural keys if I don't have to use more than two fields
(neither of which is a DateTime or imprecise Numeric) and where I can use RI or
triggers to cascade updates. If that criteria is not met, then I use a numeric
Surrogate field. This is not always an AutoNumber or IDENTITY field though.