-5

I have a scenario where have two tables with unique elements and both the tables contains same sort of records. Now one table is having primary key and another doesn't. so what is the advantage of having primary key in case i have unique elements in both the tables. and how primary key is related with index.? I have been asked this question in Nokia interview. pretty confusing please answers with some sort of example.

  • Possible duplicate of [Primary key or Unique index?](https://stackoverflow.com/questions/487314/primary-key-or-unique-index) – Szymon Sep 08 '17 at 11:51
  • Possible duplicate of [difference between primary key and unique key](https://stackoverflow.com/questions/9565996/difference-between-primary-key-and-unique-key) – krokodilko Sep 08 '17 at 12:07
  • There is also an article in [Wikipedia - unique keys](https://en.wikipedia.org/wiki/Unique_key) – krokodilko Sep 08 '17 at 12:09

1 Answers1

0

what is the advantage of having primary key?

Primary key induces or rather forces the column to have two conditions-

  1. UNIQUE VALUE
  2. NOT NULL

So when a table row is inserted it must follow both conditions. In case the table has some records already it will check for uniqueness while adding the constraint. If there are duplicate entries for that attribute then you cant add the primary key constraint.

how primary key is related with index.?

When you declare an attribute as PRIMARY KEY indexing will be created on that attribute by default. This helps in faster access to the records when the number of records is too high. (=> faster fetching).

But for a small table indexing would slow down things as it needs to update the indexes every time you insert/update a row.

pro_cheats
  • 1,534
  • 1
  • 15
  • 25
  • in case if i have all the records as unique. how primary will add an advantage as i mentioned an example. can you please describe according to that – Rahul Anand Sep 08 '17 at 13:34
  • adding primary key on an attribute creates indexing on the records. So the performance will be better, which is not the case with just unique records (no indexing). Also unique columns can be null, primary can't be. I don't see any other reasons than this. Hope this helps – pro_cheats Sep 08 '17 at 16:39