FACTOID # 177: 61.5% of Swedes work more than 40 hours per week, but just across the border in Norway only 15.8% of people work this long.
 
 Home   Encyclopedia   Statistics   Countries A-Z   Flags   Maps   Education   Forum   FAQ   About 
 
 
 
WHAT'S NEW
RECENT ARTICLES
More Recent Articles »
 

SEARCH ALL

FACTS & STATISTICS    Advanced view

Search encyclopedia, statistics and forums:

 

 

(* = Graphable)

 

 


Encyclopedia > Foreign key

In the context of relational databases, a foreign key is a referential constraint between two tables[1]. The foreign key 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. Image File history File links Circle-question-red. ... A relational database is a database that conforms to the relational model, and refers to a databases data and schema (the databases structure of how that data is arranged). ... An example of a database that has not enforced referential integrity. ... In database design, a primary key is a value that can be used to identify a unique row in a table. ... In database design, a unique key refers to the set of columns which have a unique set of values for each row of the table. ... The ASCII codes for the word Wikipedia represented in binary, the numeral system most commonly used for encoding computer information. ... Database normalization is a design technique for structuring relational database tables. ...


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. A database management system (DBMS) is a computer program (or more typically, a suite of them) designed to manage a database, a large set of structured data, and run operations on the data requested by numerous users. ...


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

Contents

Defining Foreign Keys

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 <table identifier> ADD [ CONSTRAINT <constraint identifier> ] FOREIGN KEY ( <column expression> {, <column expression>}... ) REFERENCES <table identifier> [ ( <column expression> {, <column expression>}... ) ] [ ON UPDATE <referential action> ] [ ON DELETE <referential action> ] 

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) REFERENCES other_table(key_col) ON DELETE CASCADE, ... ) 

If the foreign key is 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), ... ) 

Referential Actions

Because the DBMS enforces referential constraints, it must ensure data integrity if rows in a referenced table are to be 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 occurrences:

CASCADE

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.


RESTRICT

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.


NO ACTION

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. An UPDATE statement in SQL changes data in one or more records in a relational database management system. ... A DELETE statement in SQL removes records in a relational database management system. ... A database trigger is procedural code that is automatically executed in response to certain events on a particular table in a database. ...


SET NULL

The foreign key 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 foreign key columns does not require a referenced row. A foreign key with a cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table with automatically be deleted. This is called a cascade delete. Columns in Relational database management systems (RDBMS) can optionally store NULL values. ...


SET DEFAULT

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


Example 1

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: DDL may be an abbreviation for: Daniel Day-Lewis, Academy Award winning Irish/English actor Data Definition Language Data Description Language (see description language) Data Design Laboratory Data Design Language Data Distribution List Dedicated Data Link Delegation Of Disclosure Authority Letter Den Danske Landinspektørforening, the Danish Association of Chartered...

 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 NOT NULL, 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 ) 

Example 2

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. A surrogate key is a unique primary key generated by the relational database management system that is not derived from any data in the database and whose only significance is to act as the primary key. ...


See also

An alternate key is any candidate key which is not selected to be the primary key. ... In the relational model a candidate key of a relation variable (relvar) is a set of attributes of that relvar such that (1) at all times it holds in the relation assigned to that variable that there are no two distinct tuples with the same values for these attributes and... In database design, a compound key (also called a composite key) is a key that consists of 2 or more attributes. ... A superkey is defined in the relational model as a set of attributes of a relation variable (relvar) for which it holds that in all relations assigned to that variable there are no two distinct tuples (rows) that have the same values for the attributes in this set. ...

References

  1. ^ For a simpler visualization, see VisualCase.com
Topics in database management systems (DBMS)view  talk  edit )

Concepts
Database • Database models • Database storage • Relational model • Distributed DBMS • ACID • Null
Relational database • Relational algebra • Relational calculus • Database normalization • Referential integrity • Relational DBMS 
Primary key, Foreign key, Surrogate key, Superkey, Candidate key  A database management system (DBMS) is computer software designed for the purpose of managing databases. ... In computing , a database can be defined as a structured collection of records or data that is stored in a computer so that a program can consult it to answer queries. ... A data model is not just a way of structuring data: it also defines a set of operations that can be performed on the data. ... Database tables/indexes are typically stored in memory or on hard disk in one of many forms, ordered/unordered Flat files, ISAM, Heaps, Hash buckets or B+ Trees. ... The relational model for database management is a database model based on predicate logic and set theory. ... According to Elmasri and Navathe (2004, p. ... Acidity redirects here. ... Columns in Relational database management systems (RDBMS) can optionally store NULL values. ... A relational database is a database that conforms to the relational model, and refers to a databases data and schema (the databases structure of how that data is arranged). ... Relational algebra, an offshoot of first-order logic, is a set of relations closed under operators. ... The relational calculus refers to the two calculi, the tuple calculus and the domain calculus, that are part of the relational model for databases and that provide a declarative way to specify database queries. ... Database normalization is a design technique for structuring relational database tables. ... An example of a database that has not enforced referential integrity. ... A relational database management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced by Edgar F. Codd. ... In database design, a primary key is a value that can be used to identify a unique row in a table. ... A surrogate key is a unique primary key generated by the relational database management system that is not derived from any data in the database and whose only significance is to act as the primary key. ... A superkey is defined in the relational model as a set of attributes of a relation variable (relvar) for which it holds that in all relations assigned to that variable there are no two distinct tuples (rows) that have the same values for the attributes in this set. ... In the relational model a candidate key of a relation variable (relvar) is a set of attributes of that relvar such that (1) at all times it holds in the relation assigned to that variable that there are no two distinct tuples with the same values for these attributes and...

Objects
Trigger • View • Table • Cursor • Log • Transaction • Index 
Stored procedure • Partition A database trigger is procedural code that is automatically executed in response to certain events on a particular table in a database. ... In database theory, a view is a virtual or logical table composed of the result set of a query. ... In relational databases, SQL databases, and flat file databases, a table is a set of data elements (values) that is organized using a model of horizontal rows and vertical columns. ... In database packages, the term cursor refers to a control structure for the successive traversal (and potential processing) of records in a result set as returned by a query. ... In in the field of databases in computer science, a transaction log (also database log or binary log) is a history of actions executed by a database management system to guarantee ACID properties over crashes or hardware failures. ... A database transaction is a unit of interaction with a database management system or similar system that is treated in a coherent and reliable way independent of other transactions that must be either entirely completed or aborted. ... It has been suggested that Bitmap index be merged into this article or section. ... A stored procedure is a subroutine available to applications accessing a relational database system. ... A partition is a division of a logical database or its constituting elements into distinct independent parts. ...

Topics in SQL
Select • Insert • Update • Merge • Delete • Join • Union • Create • Drop
  Begin work • Commit • Rollback • Truncate • Alter The related Category:SQL statements has been nominated for deletion, merging, or renaming. ... A SELECT statement in SQL returns a result set of records from one or more tables. ... An SQL INSERT statement adds one or more records to a table in a relational database. ... An UPDATE statement in SQL changes data in one or more records in a relational database management system. ... Wikipedia does not have an article with this exact name. ... A DELETE statement in SQL removes records in a relational database management system. ... A join combines records from two tables in a relational database and results in a new (temporary) table, also called joined table. ... In SQL the UNION operator combines the results of two SQL queries into a single table of all matching rows. ... A CREATE statement in SQL creates an object inside of a relational database management system (RDBMS). ... A DROP statement in SQL removes an object from a relational database management system (RDBMS). ... A BEGIN WORK statement in SQL starts a transaction within a relational database management system (RDBMS). ... A COMMIT statement in SQL ends a transaction within a relational database management system (RDBMS) and makes all changes visible to other users. ... In database technologies, a rollback is an operation which returns the database to some previous state. ... The Truncate statement removes all the data from a table. ... An ALTER statement in SQL changes the properties of an object inside of a relational database management system (RDBMS). ...

Implementations of database management systems

Types of implementations
Relational • Flat file • Deductive • Dimensional • Hierarchical • Object oriented • Object relational • Temporal • XML data stores A relational database is a database that conforms to the relational model, and refers to a databases data and schema (the databases structure of how that data is arranged). ... A simple diagram depicting conversion of a CSV-format flat file database table into a relational database table. ... A deductive database system is a database system which can make deductions (ie: infer additional rules or facts) based on rules and facts stored in the (deductive) database. ... A dimensional database is one which, rather than storing data in multiple two dimensional tables (as a relational databases does), represents key data entities as different dimensions. ... In a hierarchical data model, data are organized into a tree-like structure. ... In an object oriented database, information is represented in the form of objects like in object oriented programming. ... An object-relational database (ORD) or object-relational database management system (ORDBMS) is a relational database management system that allows developers to integrate the database with their own custom data types and methods. ... A temporal database is a database management system with built-in time aspects, e. ... In Software engineering, an XML database is a data persistence software system that allows data to be imported, accessed and exported in the XML format. ...

Database products
Object-oriented (comparison) • Relational (comparison) The following is a list of object-oriented database management systems. ... This article or section is not written in the formal tone expected of an encyclopedia article. ... // 4th Dimension Greenplum CA-Datacom Dataphor Daffodil database EnterpriseDB eXtremeDB DB2 FileMaker Greenplum Helix database Informix InterBase Kognitio, WX2 Linter Matisse Microsoft Jet Database Engine (part of Microsoft Access) Microsoft SQL Server Microsoft Visual FoxPro Mimer SQL mSQL Netezza NonStop SQL Openbase Oracle Oracle Rdb for OpenVMS OpenLink Virtuoso Universal... The following tables compare general and technical information for a number of relational database management systems. ...

Components
Query language • Query optimizer • Query plan • ODBC • JDBC Query languages are computer languages used to make queries into databases and information systems. ... The query optimizer is a component of database management system that is used to analyzes queries submitted to database server for execution, and then determines the optimal way to execute the query. ... A query plan (or query execution plan) is an set of steps used to access information in a SQL relational database management system. ... In computing, Open Database Connectivity (ODBC) provides a standard software API method for using database management systems (DBMS). ... Java Database Connectivity, or JDBC, is an API for the Java programming language that defines how a client may access a database. ...


  Results from FactBites:
 
Database Priamry and Foreign Keys | Database Solutions for Microsoft Access | databasedev.co.uk (936 words)
Foreign keys provide a method for maintaining integrity in the data (called referential integrity) and for navigating between different instances of an entity.
Foreign keys are formed in dependent and subtype entities by migrating the entire primary key from the parent or generic entity.
Foreign key attributes are not considered to be owned by the entities to which they migrate, because they are reflections of attributes in the parent entities.
  More results at FactBites »


 
 

COMMENTARY     


Share your thoughts, questions and commentary here
Your name
Your comments

Want to know more?
Search encyclopedia, statistics and forums:

 


Lesson Plans | Student Area | Student FAQ | Reviews | Press Releases |  Feeds | Contact
The Wikipedia article included on this page is licensed under the GFDL.
Images may be subject to relevant owners' copyright.
All other elements are (c) copyright NationMaster.com 2003-5. All Rights Reserved.
Usage implies agreement with terms, 1022, m