What is the best practise in choosing a table's primary key

Viewed 74

I used to create a column called 'id' which is auto incremented in any table I create. While in some cases I found that this column is useless while another column like 'citizen_ssn' is a better candidate to be the primary key.

So, what is the best practice in choosing the table's primary key ? Should I use what will fit the need or create the auto-increamented column or another opinion ?

3 Answers

Any attribute which is unique and not null can be used as a primary key. Generally id is used as a primary key by many developers. But there's no such rule except mentioned above.

What is a Primary Key?

Apart from Auto-Incrementing it, a primary key is used to Identify a row. As every row is unique, so is the Primary key. Two or more rows with a column number n can have the same value, let's say "Australia" but the column with Primary Key constraint will have the unique value.

So, it's not important to use the id column as a primary key.

One can use phoneNumber as a PK too. Depends on the usage.

I hope I've made myself clear.

In Realm there is no real reason to have an auto-increment primary key. (although if your server returns primary key info, then it's useful to know that you're referring to the same object).

In SQLite (or any relational database) the reason you need them is that that is the only way you can link two objects together (through JOINs) - for example, a many-many relationship is done with a Join Table that contains the primary key of both linked tables as a foreign key.

In Realm, you can link objects together as a field like private OtherObject otherObject;, and many relation as private RealmList<OtherObject> otherObjects. So you don't need primary key to create relationship.

What you might need them for in Realm is if you want to use insertOrUpdate() method to update an existing object in Realm by its primary key, overwriting it with an unmanaged object. You can also edit objects by calling the managed object's setters, so this is not entirely necessary.

Related