Saturday, May 1, 2010

Foreign key

0 comments
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 set of columns in another (referenced) table. The columns in the referencing table must be the primary key or other candidate key in the referenced table. 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 (except potentially NULL). This way references can be made to link information together and it is an essential part of database normalizationExample:


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

Example:
in the example below c.coutnry_id is the primary key in the reference table of Country while representing here in this query as a foreign key in the  customer tabel.
Select ct.cus_name,ct.cus_address,c.country_name
from customer ct
innner join country c on ct.country_id=c.coutnry_id
 
 

0 comments: