Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can we have a foreign key which is not a primary key in any other table?

it is written in every book that foreign keys are actually primary key in some other table but can we have a foreign key which is not primary key in any other table

like image 843
Mac Avatar asked May 24 '10 06:05

Mac


People also ask

Can a foreign key not be a primary key in another table?

A foreign key can refer to either a unique or a primary key of the parent table. If the foreign key refers to a non-primary unique key, you must specify the column names of the key explicitly.

Is a foreign key a primary key in another table?

A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table. The table with the foreign key is called the child table, and the table with the primary key is called the referenced or parent table.


2 Answers

Yes - you can have a foreign key that references a unique index in another table.

CREATE UNIQUE INDEX UX01_YourTable ON dbo.YourTable(SomeUniqueColumn)  ALTER TABLE dbo.YourChildTable    ADD CONSTRAINT FK_ChildTable_Table    FOREIGN KEY(YourFKColumn) REFERENCES dbo.YourTable(SomeUniqueColumn) 
like image 102
marc_s Avatar answered Sep 28 '22 16:09

marc_s


By definition a foreign key must reference a candidate key of some table. It doesn't necessarily have to be the primary key.

As a matter of detail the constraint called a FOREIGN KEY in SQL isn't exactly equivalent to the textbook definition of a foreign key in the relational model. SQL's FOREIGN KEY constraint differs because:

  • it can reference any set of columns subject to a uniqueness constraint even if they are not candidate keys (superkeys or nullable columns for example).
  • it may include nulls, in which case the constraint is not enforced
  • its syntax depends on column order, so a fk constraint on (A,B) referencing (A,B) is different to a constraint on (B,A) referencing (A,B).
like image 23
nvogel Avatar answered Sep 28 '22 16:09

nvogel