SQL Server FOREIGN KEY: How to Create with Example

โšก Smart Summary

A foreign key in SQL Server enforces referential integrity by linking a child table to a parent table. Every foreign key value must already exist in the referenced primary key of the parent table.

  • ๐Ÿ”— What is a foreign key: A foreign key links a child table to a parent table and enforces referential integrity between them.
  • ๐Ÿ‘ช Parent and child: The referenced table is the parent; the table holding the foreign key is the child, which points to the parent primary key.
  • ๐Ÿ–ฑ๏ธ Two creation methods: SQL Server Management Studio relationships and the T-SQL CREATE TABLE … FOREIGN KEY … REFERENCES clause both define a foreign key.
  • โž• Add to an existing table: ALTER TABLE … ADD CONSTRAINT … FOREIGN KEY adds the relationship to a table that already exists.
  • ๐Ÿ”„ Referential actions: ON DELETE and ON UPDATE clauses control child rows with NO ACTION, CASCADE, SET NULL, or SET DEFAULT.
  • โœ… Integrity check: Inserting a child row whose key has no matching parent row is rejected, keeping the data consistent.

SQL Server FOREIGN KEY: How to Create in SQL Server with an Example

What is a FOREIGN KEY?

A foreign key provides a way of enforcing referential integrity within SQL Server. In simple words, a foreign key ensures that values in one table must be present in another table.

Rules for FOREIGN KEY

  • NULL is allowed in a SQL foreign key.
  • The table being referenced is called the parent table.
  • The table with the foreign key is called the child table.
  • The foreign key in the child table references the primary key in the parent table.
  • This parent-child relationship enforces the rule known as “referential integrity.”

The diagram below summarizes all the points above for the foreign key.

Diagram of a foreign key linking a child table to the parent table primary key

How to Create FOREIGN KEY in SQL

You can create a foreign key in SQL Server in two ways:

SQL Server Management Studio

Parent Table: Say we have an existing parent table named ‘Course.’ Course_ID and Course_name are two columns, with Course_Id as the primary key.

Parent table Course with Course_Id primary key and Course_name columns

Child Table: We need to create the second table as a child table. ‘Course_ID’ and ‘Course_Strength’ are its two columns. However, ‘Course_ID’ shall be the foreign key.

Step 1) Right-click on Tables > New > Table…

Right-click Tables, then New, then Table in SQL Server Management Studio

Step 2) Enter two column names as ‘Course_ID’ and ‘Course_Strength.’ Right-click on the ‘Course_Id’ column, then click Relationship.

New child table columns Course_ID and Course_Strength with the Relationship menu

Step 3) In ‘Foreign Key Relationships,’ click ‘Add.’

Foreign Key Relationships dialog with the Add button

Step 4) In ‘Tables and Columns Specification,’ click on the ‘…’ icon.

Tables and Columns Specification field with the ellipsis button

Step 5) Select the ‘Primary Key Table’ as ‘COURSE’ and the new table being created as the ‘Foreign Key Table’ from the drop-down.

Selecting COURSE as the primary key table in the relationship dialog

Step 6) For the ‘Primary Key Table,’ select the ‘Course_Id’ column as the primary key table column.

For the ‘Foreign Key Table,’ select the ‘Course_Id’ column as the foreign key table column. Click OK.

Mapping Course_Id as both the primary key and foreign key columns

Step 7) Click on Add.

Clicking Add to confirm the foreign key relationship

Step 8) Give the table name as ‘Course_Strength’ and click OK.

Naming the child table Course_Strength and clicking OK

Result: We have set a parent-child relationship between ‘Course’ and ‘Course_Strength.’

Parent-child relationship established between Course and Course_Strength

T-SQL: Create a Parent-Child Table Using T-SQL

Parent Table: Reconsider that we have an existing parent table with the name ‘Course.’ Course_ID and Course_name are two columns, with Course_Id as the primary key.

Existing parent table Course with Course_Id as the primary key

Child Table: We need to create the second table as the child table with the name ‘Course_Strength_TSQL.’ ‘Course_ID’ and ‘Course_Strength’ are its two columns. However, ‘Course_ID’ shall be the foreign key.

Below is the syntax to create a table with a FOREIGN KEY.

Syntax:

CREATE TABLE childTable
(
  column_1 datatype [ NULL |NOT NULL ],
  column_2 datatype [ NULL |NOT NULL ],
  ...

  CONSTRAINT fkey_name
    FOREIGN KEY (child_column1, child_column2, ... child_column_n)
    REFERENCES parentTable (parent_column1, parent_column2, ... parent_column_n)
    [ ON DELETE { NO ACTION |CASCADE |SET NULL |SET DEFAULT } ]
    [ ON UPDATE { NO ACTION |CASCADE |SET NULL |SET DEFAULT } ] 
);

Here is a description of the above parameters:

  • childTable is the name of the table that is to be created.
  • column_1, column_2 are the columns to be added to the table.
  • fkey_name is the name of the foreign key constraint to be created.
  • child_column1, child_column2 … child_column_n are the child table columns that reference the primary key in parentTable.
  • parentTable is the name of the parent table whose key is referenced in the child table.
  • parent_column1, parent_column2 … parent_column_n are the columns making up the primary key of the parent table.
  • ON DELETE is an optional parameter that specifies what happens to the child data after the parent data is deleted. Values include NO ACTION, SET NULL, CASCADE, or SET DEFAULT.
  • ON UPDATE is an optional parameter that specifies what happens to the child data after the parent data is updated. Values include NO ACTION, SET NULL, CASCADE, or SET DEFAULT.
  • NO ACTION means nothing happens to the child data after the parent data is updated or deleted.
  • CASCADE means the child data is deleted or updated after the parent data has been deleted or updated.
  • SET NULL means the child data is set to null after the parent data is updated or deleted.
  • SET DEFAULT means the child data is set to its default value after an update or delete on the parent data.

Let us see a foreign key example that creates a table with one column as a FOREIGN KEY, using a data type for each column.

Foreign Key in SQL Example

Query:

CREATE TABLE Course_Strength_TSQL
(
Course_ID Int,
Course_Strength Varchar(20) 
CONSTRAINT FK FOREIGN KEY (Course_ID)
REFERENCES COURSE (Course_ID)	
)

Step 1) Run the query by clicking Execute.

Executing the CREATE TABLE query that defines the Course_ID foreign key

Result: We have set a parent-child relationship between ‘Course’ and ‘Course_Strength_TSQL.’

Parent-child relationship created between Course and Course_Strength_TSQL

Using ALTER TABLE

Now we will learn how to add a foreign key in SQL Server to a table that already exists using the ALTER TABLE statement. We will use the syntax given below:

ALTER TABLE childTable
ADD CONSTRAINT fkey_name
    FOREIGN KEY (child_column1, child_column2, ... child_column_n)
    REFERENCES parentTable (parent_column1, parent_column2, ... parent_column_n);

Here is a description of the parameters used above:

  • childTable is the name of the table that is to be created.
  • column_1, column_2 are the columns to be added to the table.
  • fkey_name is the name of the foreign key constraint to be created.
  • child_column1, child_column2 … child_column_n are the child table columns that reference the primary key in parentTable.
  • parentTable is the name of the parent table whose key is referenced in the child table.
  • parent_column1, parent_column2 … parent_column_n are the columns making up the primary key of the parent table.

ALTER TABLE add foreign key example:

ALTER TABLE department
ADD CONSTRAINT fkey_student_admission
    FOREIGN KEY (admission)
    REFERENCES students (admission);

We have created a foreign key named fkey_student_admission on the department table. This foreign key references the admission column of the students table.

Example Query FOREIGN KEY

First, let us see our parent table data, COURSE.

Query:

SELECT * from COURSE;

SELECT result showing the parent table COURSE data

Now let us insert some rows in the child table ‘Course_Strength_TSQL.’ We will try to insert two types of rows:

  • The first type, for which Course_Id in the child table exists in Course_Id of the parent table, that is, Course_Id = 1 and 2.
  • The second type, for which Course_Id in the child table does not exist in the Course_Id of the parent table, that is, Course_Id = 5.

Query:

Insert into COURSE_STRENGTH values (1,'SQL');
Insert into COURSE_STRENGTH values (2,'Python');
Insert into COURSE_STRENGTH values (5,'PERL');

Inserting child rows, including Course_ID 5 that has no matching parent

Result: Let us run the query together to see our parent and child tables.

The rows with Course_ID 1 and 2 exist in the Course_Strength table. Course_ID 5, however, is an exception, because it has no matching row in the parent table.

Parent and child tables compared; Course_ID 5 violates referential integrity

FAQs

A primary key uniquely identifies each row inside its own table and cannot be NULL. A foreign key references that primary key from another table to enforce referential integrity. This primary key versus foreign key comparison explains every distinction.

Yes. A foreign key can reference either a primary key or any column that carries a UNIQUE constraint in the parent table. The referenced column must hold unique values so each child row matches exactly one parent row.

ON DELETE CASCADE automatically deletes the matching child rows whenever their parent row is deleted, keeping the tables consistent. Alternatives are SET NULL, which clears the child foreign key, and NO ACTION, which blocks the delete.

Yes. A self-referencing foreign key points to a primary key in the same table, which models hierarchies such as an employee row referencing its manager. For self-references, SQL Server recommends ON DELETE NO ACTION to avoid cascade cycles.

Yes, unless the column is declared NOT NULL. A NULL foreign key means the child row is not yet linked to any parent row, and SQL Server skips the referential check for that NULL value.

Run ALTER TABLE child_table DROP CONSTRAINT fkey_name. You must supply the constraint name, which you can find in sys.foreign_keys. Dropping the foreign key removes the relationship but leaves both tables and their data unchanged.

Yes. GitHub Copilot can write FOREIGN KEY constraints inside CREATE TABLE or ALTER TABLE statements from a natural-language prompt and suggest the parent table and referenced column. Always review the keys, referential actions, and data types before running the script.

AI and machine learning tools examine sample data and query patterns to suggest which columns should become foreign keys, detect missing or orphaned relationships, and recommend suitable ON DELETE actions. The developer reviews each suggestion before applying it.

Summarize this post with: