Skip to content
Related Articles
Open in App
Not now

Related Articles

Foreign key in MS SQL Server

Improve Article
Save Article
  • Last Updated : 31 Jul, 2020
Improve Article
Save Article

Prerequisite – Primary key in MS SQL Server
SQL Server has different keys which serve a different purpose. In this article, the foreign key will be discussed in brief.

The foreign key has a similar purpose as the primary key yet, the foreign key is used for two tables. In a few cases, the foreign key is used for self-referencing a single table.

Foreign key :
A singular column or a set of columns of one table that uniquely identified by a singular column or a set of columns of another table is referred to as a foreign key.

Syntax –

constraint fk_constraint-name foreign key(col1, col2) 
references parent_table-name(col1, col2)
                                        (OR)
foreign key(col1, col2) 
references parent_table-name(col1, col2)

A foreign key has two tables – parent table and child table. If a user wants to insert a column in a child table, the column has to be a part of the parent table otherwise, an error is displayed. In the syntax, the constraint term is not mandatory to use.

When a foreign key is mentioned in the query, the key automatically creates a referential constraint meaning a column can be inserted in the child table only if it is a part of the parent table.

Two tables named student (parent table) and marks (child table) are considered from the university database.

Table – Student

NameRollnoAge
Aisha11118
Maya11219
Fatima11318


Table – Marks

NameRollnoMarks
Aisha1119.5
Maya1128.7
Fatima1137.7

If a user wants to insert a new column, the query is given as –

foreign key('rollno') 
references student('rollno')

insert into marks ('name', 'rollno', 'marks') 
values('Naina, '111', '7.5')

An error is displayed as the roll number is already taken by a student. (Foreign key constraint). The foreign key does not allow the value to reoccur. To avoid such errors, the values must neither be repeated nor a different column must be considered.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!