is it necessary for a foreign key to be primary key of another table
Yes, foreign key has to be primary key of parent table.
foreign key is not unique it may have duplicate entries
Yes, it may not be unique and may have duplicate entries in child table, but it must be unique and does not have any duplicate entries at the parent table (as it is a primary key).
For example consider below tables:
create table city (city_id int(PK), name varchar(25));
create table author (author_id int(PK), city int (FK), name varchar(25));
Here, in the author
table, the city
(foreign key) column can be non-unique as multiple authors belongs to a city. But in city
table, city_id
(primary key) must be unique as each city must have only one city_id
.
However, if you really need to reference non-primary key as foreign key to other table, make sure its a unique
column in parent table - sometimes this is helpful as well.
Have a look at my blog post for background.