Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a foreign key be created on the parent table or child table?

What's the difference? If I have these two tables:

CREATE TABLE Account (Id int NOT NULL)

CREATE TABLE Customer (AccountId int NOT NULL)

And I want a foreign key linking the two, which of the following should I do and why?

Option 1:

ALTER TABLE [dbo].[Customer]  WITH CHECK 
  ADD  CONSTRAINT [FK_Accounts_Customers] FOREIGN KEY([AccountId])
  REFERENCES [dbo].[Account] ([Id])

Option 2:

ALTER TABLE [dbo].[Account]  WITH CHECK 
  ADD  CONSTRAINT [FK_Accounts_Customers] FOREIGN KEY([Id])
  REFERENCES [dbo].[Customer] ([Id])
like image 310
scottm Avatar asked Feb 21 '13 17:02

scottm


People also ask

Should foreign keys be on parent or child?

A foreign key means that values in one table must also appear in another table. The referenced table is called the parent table while the table with the foreign key is called the child table. The foreign key in the child table will generally reference a primary key in the parent table.

Which table should I put foreign key in?

As a rule of thumb, you should add a foreign key on the child table referencing the parent table.

Is foreign key unique in parent 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.

What is the foreign key in child table?

A Foreign Key is a database key that is used to link two tables together. The FOREIGN KEY constraint identifies the relationships between the database tables by referencing a column, or set of columns, in the Child table that contains the foreign key, to the PRIMARY KEY column or set of columns, in the Parent table.


2 Answers

Depends on context. Does every customer have a client? Which one is the parent? It seems like an Account has multiple Customers, in which case the reference belongs on the Customer table.

Now, that said, please call the entities CustomerID and AccountID everywhere. It may seem redundant on the primary table but the name should be consistent throughout the model.

like image 137
Aaron Bertrand Avatar answered Oct 18 '22 15:10

Aaron Bertrand


I would use a foreign key from the child to the parent. The tell tale question is: what happens if you need to delete one of the entities?

like image 40
Udo Klein Avatar answered Oct 18 '22 14:10

Udo Klein