Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create foreign key without a primary key

Why is it necessary to have a primary key on a column of one table to which a column of the other table having foreign key references.

create table D(Did int)
create table E(Eid int foreign key references D(Did))

The above query gives error:

There are no primary or candidate keys in the referenced table 'D' that match
the referencing column list in the foreign key 'FK__E__Eid__79C80F94'.
like image 394
sqlchild Avatar asked Mar 26 '11 13:03

sqlchild


People also ask

Can I create foreign key without primary key?

From Books Online: A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table. So in your case if you make AnotherID unique, it will be allowed.

How can add foreign key in SQL without primary key?

You need to have either a primary key or unique key in the column which will be referred by the foreign key. Without it you can't create the foreign key.

Can a table have foreign key but no primary key?

Yes, you can make one without a Primary Key (or, another option is a Compound Primary Key - making the two references a unique pair, and using that as the unique identifying key - but even this isn't necessary (note: just because it "isn't necessary" doesn't mean it isn't "good practice"; it wouldn't generally be a ...

Does a foreign key always reference a primary key?

Creating a foreign key is almost as easy as creating a primary key, except that SQL Server imposes several more rules on foreign keys. For example, the foreign key must reference a primary key or unique constraint, although that reference can be on the same table or on a different table.


1 Answers

Very good question. There is no fundamental reason why a referential constraint shouldn't reference something other than a candidate key. There is even a name for such constraints: Inclusion Dependencies. A foreign key is just a type of inclusion dependency where the target of the constraint happens to be a candidate key.

Unfortunately SQL doesn't provide good support for inclusion dependencies or even for referential constraints generally. SQL limits its so-called FOREIGN KEY constraints to referencing the columns of a UNIQUE or PRIMARY KEY constraint (not necessarily a candidate key though).

So what you have come up against is really a dubious limitation of SQL. It doesn't mean you are doing anything very wrong.

like image 133
nvogel Avatar answered Sep 29 '22 09:09

nvogel