Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use item specific prefixes and autonumber for primary keys?

We had a meeting this morning about how would should store our ID for some assets that we have in our database that we are making, the descusion generated a bit of heat so I decided to consult the experts of SO.

The table structure that I belive that we should have(short version) is like the following:

Example 1)

  • AssetId - int(32) - Primary Key
  • Type - string

so some example data is like this:

==AssetId======Type===
  12345        "Manhole"
  155415       "Pit"

etc.

Another member of the team suggested something like this:

Example 2)

  • AssetId - string - Primary Key
  • Type - string

so some example data is like this:

==AssetId======Type===
  "MH12345"    "Manhole"
  "P155415"    "Pit"

where we make a short version of the type and append it to the front of the ID and store it in the database. I have seen a few asset databases that do this and have never really this approach.

I have never really liked the idea of using strings as ID for sorting reasons. I also feel like it is storing useless information just for the sake of it when you already have the type of asset store anyway.

What approach would you take? And why? Are there any benefits to using approach 1 over 2?

EDIT: Yes I will be using AUTO_INCREMENT for approach 1.

like image 673
Nathan W Avatar asked Feb 03 '09 06:02

Nathan W


People also ask

How do I make my primary key AutoNumber?

In the Navigation Pane, right-click the table to which you want to add the primary key, and click Design View. Tip: If you don't see the Navigation Pane, press F11 to display it. Locate the first available empty row in the table design grid. In the Data Type field, click the drop-down arrow and click AutoNumber.

Should I AutoNumber primary key?

No, it does not *have to be* autonumber.

What is the best data type for a primary key?

Integer (number) data types are the best choice for primary key, followed by fixed-length character data types.


2 Answers

Usually the rule of thumb is that never use meaningful information in primary keys (like Social Security number or barcode). Just plain autoincremented integer. However constant the data seems - it may change at one point (new legislation comes and all SSNs are recalculated).

like image 148
Riho Avatar answered Sep 21 '22 07:09

Riho


This is a decision between surrogate and natural keys, the first being surrogate (or "technical") and the second being natural.

I've come to the conclusion that you should pretty much always use surrogate keys. If you use natural keys, those may change and updating primary/foreign keys is not generally a good idea.

like image 36
cletus Avatar answered Sep 18 '22 07:09

cletus