Foreign key

From Wikipedia, the free encyclopedia

In the context of relational databases, a foreign key (FK) is a referential constraint between two tables. The FK identifies a column or a set of columns in one (referencing) table that refers to a column or set of columns in another (referenced) table. The columns in the referenced table must form a primary key or unique key. The values in one row of the referencing columns must occur in a single row in the referenced table. Thus, a row in the referencing table cannot contain values that don't exist in the referenced table. This way references can be made to link information together and it is an essential part of database normalization. Multiple rows in the referencing table may refer to the same row in the referenced table.

The referencing and referenced table may be the same table, i.e. the foreign key refers back to the same table. Such a foreign key is known in SQL:2003 as self-referencing or recursive foreign key.

A table may have multiple foreign keys, and each foreign key can have a different referenced table. Each foreign key is enforced independently by the database system. Therefore, cascading relationships between tables can be established using foreign keys.

Improper foreign key/primary key relationships or not enforcing those relationships are often the source of many database and data modeling problems.

Contents

Foreign keys are defined in the ANSI SQL Standard, through a FOREIGN KEY constraint. The syntax to add such a constraint to an existing table is defined in SQL:2003 like shown below. Omitting the column list in the REFERENCES clause implies that the foreign key shall reference the primary key of the referenced table.

ALTER TABLE  
   ADD [ CONSTRAINT  ] 
      FOREIGN KEY (  {, }... )
      REFERENCES 
[ ( {, }... ) ] [ ON UPDATE ] [ ON DELETE ]

Likewise, foreign keys can be defined as part of the CREATE TABLE SQL statement.

CREATE TABLE table_name (
   id    INTEGER  PRIMARY KEY,
   col2  CHARACTER VARYING(20),
   col3  INTEGER,
   ...
   CONSTRAINT col3_fk FOREIGN KEY(col3)
      REFERENCING other_table(UNIQUE(key_col) ON DELETE CASCADE,
   ... )

If the foreign key is comprised of a single column only, the column can be marked as such using the following syntax:

CREATE TABLE table_name (
   id    INTEGER  PRIMARY KEY,
   col2  CHARACTER VARYING(20),
   col3  INTEGER FOREIGN KEY REFERENCES other_table(column_name),
   ... )

Because the DBMS enforces referential constraints, it must ensure data integrity if rows in a referenced table are to deleted (or updated). If dependent rows in referencing tables still exist, those references have to be considered. SQL:2003 specifies 5 different referential actions that shall take place in such occurences:

All dependent rows are deleted if the referenced row is deleted. Likewise, the values in the foreign key columns are updated with the respective values in the referenced row.

A row in the referenced table cannot be updated or deleted if dependent rows still exist. In that case, no data change is even attempted.

The UPDATE or DELETE SQL statement is executed on the referenced table. The DBMS verifies at the end of the statement execution if none of the referential relationships is violated. The major difference to RESTRICT is that triggers or the statement semantics itself may give a result in which no foreign key relationships is violated. Then, the statement can be executed successfully.

The FK values in the referencing row are set to NULL when the referenced row is updated or deleted. This is only possible if the respective columns in the referencing table are nullable. Due to the semantics of NULL, a referencing row with NULLs in the FK columns does not require a referenced row.

Similarily to SET NULL, the FK values in the referencing row are set to the column default when the referenced row is updated or deleted.

As a first example to illustrate foreign keys, suppose an accounts database has a table with invoices and each invoice is associated with a particular supplier. Supplier details (such as address or phone number) are kept in a separate table; each supplier is given a 'supplier number' to identify them. Each invoice record has an attribute containing the supplier number for that invoice. Then, the 'supplier number' is the primary key in the Supplier table. The foreign key in the Invoices table points to that primary key. The relational schema is the following. Keys are marked in bold.

  Supplier ( SupplierNumber, Name, Address, Type )
  Invoices ( InvoiceNumber, SupplierNumber, Text )

The corresponding DDL is this:

 CREATE TABLE Supplier (
    SupplierNumber  INTEGER NOT NULL,
    Name            VARCHAR(20) NOT NULL,
    Address         VARCHAR(50) NOT NULL,
    Type            VARCHAR(10),
    CONSTRAINT supplier_pk PRIMARY KEY(SupplierNumber),
    CONSTRAINT number_value CHECK (SupplierNumber > 0) )
 
 CREATE TABLE Invoices (
    InvoiceNumber   INTEGER PRIMARY KEY,
    SupplierNumber  INTEGER NOT NULL,
    Text            VARCHAR(4096),
    CONSTRAINT invoice_pk PRIMARY KEY(InvoiceNumber),
    CONSTRAINT inumber_value CHECK (InvoiceNumber > 0),
    CONSTRAINT supplier_fk FOREIGN KEY(SupplierNumber)
       REFERENCES Supplier(SupplierNumber)
       ON UPDATE CASCADE ON DELETE RESTRICT )

A company has several departments, and each employee is a member of one department. This is enforced in the database by a foreign key on the Employee table, which refers to the Department table. Imagine there is a relation for departments. Each department has a department name, and a surrogate key for the department called "DepartmentID". The employee relation would have "DepartmentID" as an attribute, with a foreign key reference to the aforementioned surrogate key of the department relation. The DBMS would then enforce that each employee could not be created without specifiying a valid department row, and department row could not be deleted if there are employees referencing that department.


Topics in database management systems (DBMS) ( view talk edit )

Concepts
DatabaseDatabase modelRelational databaseRelational modelRelational algebraPrimary key, Foreign key, Surrogate key, Superkey, Candidate keyDatabase normalizationReferential integrityRelational DBMSDistributed DBMSACID

Objects
TriggerViewTableCursorLogTransactionIndexStored procedurePartition

Topics in SQL
SelectInsertUpdateMergeDeleteJoinUnionCreateDrop

Implementations of database management systems

Types of implementations
RelationalFlat fileDeductiveDimensionalHierarchicalObject orientedTemporalXML data stores

Components
Query languageQuery optimizerQuery planODBCJDBC

Database products

Apache DerbyBerkeley DBCachéDB2db4oDBaseeXtremeDBFilemaker ProFirebirdGreenplumH2HelixInformixIngresInterBaseLinterMicrosoft AccessMicrosoft SQL ServerMimer SQLMonetDBMySQLObjectivity/DBOpenLink VirtuosoOpenOffice.org BaseOracleOracle RdbParadoxPerstPostgreSQLSQLiteSybase IQSybaseTeradataUniVerseVisual FoxPro


Other: Object-oriented (comparison) • relational (comparison)

Advanced Search
Included Web Search Engines


Safe Search

close

Top Matching Results

Occasionally Search.com will highlight specialized results that are based on the context of your query. Examples of specialized results include specific links to news, images, or video.

Top Matching Results may highlight information from other Search.com pages, content from the CNET Network of sites, or third party content. The listings are based purely on relevance. Search.com does not receive payment for listings in this section but our partners that provide this data may get paid for listing these products.

Sponsored Links

This section contains paid listings which have been purchased by companies that want to have their sites appear for specific search terms and related content. These listings are administered, sorted and maintained by a third party and are not endorsed by Search.com.

Search Results

Search.com sends your search query to several search engines at one time and integrates the results into one list which has been sorted by relevance using Search.com's proprietary algorithm. You can customize the list of search engines included in your metasearch from the preferences.

The search engines that are used in your metasearch may allow companies to pay to have their Web sites included within the results. To view the Paid Inclusion policy for a specific search engine, please visit their Web site. Search.com does not accept payment or share revenue with any search engine partner for listings in this section.