Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is difference between foreign key and reference key?

I am very confused about those two terms. Are they the same or different?

Some books and people say they are the same and others say they are different.

I tried but couldn't find a conclusive answer.

like image 763
Anderson Avatar asked Dec 21 '11 20:12

Anderson


People also ask

What is reference key and foreign key in SQL?

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.

What is a referencing key?

A key reference is a one-byte identifier that specifies a cryptographic key according to its PIV Key Type. The identifier is part of the cryptographic material used in a cryptographic protocol, such as an authentication or a signing protocol.

What is the difference between primary key foreign key and candidate key?

Alternate keys are those Candidate keys that were not chosen to be the Primary key of the table. Composite key is a Candidate key that consists of more than one attribute. Foreign key is an attribute which is a Primary key in its parent table but is included as an attribute in the host table.

Can a foreign key reference a foreign key?

A foreign key can reference any field defined as unique. If that unique field is itself defined as a foreign key, it makes no difference. A foreign key is just to enforce referential integrity.


Video Answer


2 Answers

I am supposing that you are talking about using the REFERENCES where the FOREIGN KEY keyword is not used when constraining a column inline, which is called a column-level foreign key constraint, eg.

author_id INTEGER REFERENCES author(id) 

... instead of the table-level foreign key constraint, which is placed after the column declarations ...

author_id INTEGER, FOREIGN KEY(author_id) REFERENCES author(id) 

The answer is, that it is simply shorthand syntax for the same thing. The main concern when altering between the two should be readability.

For more advanced use, it might be relevant that only table-level foreign key constraints can describe constraints on multiple keys at once, where all must be present in the referenced table.


Do note that MySQL 'parses but ignores “inline REFERENCES specifications” (as defined in the SQL standard) where the references are defined as part of the column specification', meaning that only the table-level foreign key constraint will work.

Both Postgres and Microsoft's SQL Server respect both column- and table-level foreign key constraints.

like image 197
Niels Abildgaard Avatar answered Oct 19 '22 08:10

Niels Abildgaard


A foreign key must refer to a primary key. When using REFERENCES constraint simply, then it isn't necessary that the referenced key be a primary key.

like image 20
alpha Avatar answered Oct 19 '22 07:10

alpha