Javatpoint Logo
Javatpoint Logo

SQL Server Foreign Key

In SQL Server, foreign key is used to enforce referential integrity within your SQL Server database. It specifies that a value in one table must also appear in another table.

The referenced table is called parent table while the table having foreign key is called child table. The foreign key in the child table will generally reference a primary key in the parent table.

A foreign key can be created using either a CREATE TABLE statement or an ALTER TABLE statement.


Create a Foreign Key using CREATE TABLE statement

Syntax:

Parameter Explanation

child_table: It specifies the name of the child table that you want to create.

column1, column2: It specifies the columns that you want to create in the table. Each column must have a datatype. The column should either be defined as NULL or NOT NULL and if this value is left blank, the database assumes NULL as the default.

fk_name: It specifies the name of the foreign key constraint that you want to create.

child_col1, child_col2, ... child_col_n: It specifies columns in child_table that will reference a primary key in the parent_table.

parent_table: It specifies the name of the parent table whose primary key will be used in the child_table.

parent_col1, parent_col2, ... parent_col3: It specifies columns that make up the primary key in the parent_table. The foreign key will enforce a link between this data and the child_col1, child_col2, ... child_col_n columns in the child_table.

Example:

Let's create two table "products" and "inventory" where primary key of products table is "product_id" which is foreign key in "inventory" table.

Output:

SQL Server foreign key 1

The foreign key constraint in "inventory" table is fk_inv_product_id. It will establish a relationship between the product_id column in the inventory table and the product_id column in the products table.

You can now check the both tables.

SQL Server foreign key 2 SQL Server foreign key 3

Create foreign key with more than one field

In the above example, we see how to create a foreign key having one column. Let's create foreign key having more than one field.

Let's create two table "products2" and "inventory2". In this example, "products2" table has a primary key that contains both the product_name and location columns. Therefore, the second table and foreign key must also reference these two columns.

So in this example, our foreign key called fk_inv_product references the products table based on two fields: the product_name and location fields.

Output:

SQL Server foreign key 4
Next TopicEnable Foreign Key




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA