Paramclasses Academy - Blog

Tutorials Details

←
Post 21 of 40
→

Primary Key and Foreign Key in SQL Server with Examples: A Complete Beginner's Guide

Primary Key and Foreign Key in SQL Server with Examples: A Complete Beginner's Guide

November 18, 2026

Primary Key and Foreign Key in SQL Server with Examples

Introduction

When working with relational databases, one of the most important concepts to understand is Primary Key and Foreign Key. These keys help developers uniquely identify records and establish relationships between multiple database tables.

Imagine that a college has a database containing student information and department details. The college stores student names, roll numbers, contact information, and department information in separate tables. How can SQL Server identify each student uniquely and connect students with their respective departments?

This is where Primary Keys and Foreign Keys become important.

In Microsoft SQL Server, a Primary Key uniquely identifies each record in a table, whereas a Foreign Key establishes a relationship between tables by referencing a Primary Key or a UNIQUE key in another table.

In this tutorial by Param Classes, we will understand Primary Key and Foreign Key concepts step by step with practical SQL Server queries, database examples, and a real-world Student Management System.

1. What Is a Primary Key in SQL Server?

A Primary Key is a column or combination of columns that uniquely identifies every record in a database table.

It ensures that each row has a unique identity.

Important Characteristics of a Primary Key

  • Unique Values: Every Primary Key value must be unique.

  • No NULL Values: A Primary Key cannot contain NULL values.

  • One Primary Key Constraint: A table can have only one Primary Key constraint.

  • Multiple Columns: A Primary Key can consist of one or more columns.

  • Data Integrity: It prevents duplicate records based on the key.

  • Automatic Index: SQL Server automatically creates a unique index to enforce a Primary Key.

Example of a Primary Key

Consider a Students table:

StudentID StudentName Age City
101 Rahul Sharma 21 Raipur
102 Priya Verma 22 Bilaspur
103 Amit Kumar 20 Durg
104 Neha Patel 23 Raipur

Here, StudentID is the Primary Key because every student has a unique identification number.

For example:

  • StudentID 101 identifies Rahul Sharma.

  • StudentID 102 identifies Priya Verma.

  • StudentID 103 identifies Amit Kumar.

Two students cannot have the same StudentID in this table.

2. How to Create a Primary Key in SQL Server

There are different ways to define a Primary Key in SQL Server.

Method 1: Create a Primary Key While Creating a Table

Execute the following SQL query:

CREATE TABLE Students
(
    StudentID INT PRIMARY KEY,
    StudentName VARCHAR(100),
    Age INT,
    City VARCHAR(50)
);

Explanation:

  • StudentID: Stores the unique student identification number.

  • INT: Defines the integer data type.

  • PRIMARY KEY: Makes StudentID the Primary Key.

  • StudentName: Stores the student's name.

  • Age: Stores the student's age.

  • City: Stores the student's city.

In this example, StudentID uniquely identifies every student record.

Method 2: Create a Named Primary Key Constraint

You can also provide a custom name to the Primary Key constraint.

CREATE TABLE Employees
(
    EmployeeID INT,
    EmployeeName VARCHAR(100),
    Department VARCHAR(50),

    CONSTRAINT PK_Employees
    PRIMARY KEY (EmployeeID)
);

Here, PK_Employees is the name of the Primary Key constraint.

Important: Using meaningful constraint names makes database management and maintenance easier.

Method 3: Add a Primary Key to an Existing Table

If a table already exists without a Primary Key, you can add one using ALTER TABLE.

ALTER TABLE Students
ADD CONSTRAINT PK_Students
PRIMARY KEY (StudentID);

Before executing this query, ensure that StudentID does not contain duplicate or NULL values.

3. What Is a Foreign Key in SQL Server?

A Foreign Key is a column or combination of columns that establishes a relationship between two tables.

It references a Primary Key or a UNIQUE key in another table and helps maintain Referential Integrity.

A Foreign Key ensures that a non-NULL value entered into the referencing column exists in the referenced table.

Example of a Foreign Key

Consider two tables:

Departments Table

DepartmentID DepartmentName
1 Computer Science
2 Management
3 Information Technology

Students Table

StudentID StudentName DepartmentID
101 Rahul Sharma 1
102 Priya Verma 2
103 Amit Kumar 1
104 Neha Patel 3

In this example:

  • DepartmentID in the Departments table is the Primary Key.

  • StudentID in the Students table is the Primary Key.

  • DepartmentID in the Students table is the Foreign Key.

The Foreign Key connects students with their respective departments.

For example, Rahul Sharma belongs to Computer Science because his DepartmentID is 1.

Important Characteristics of a Foreign Key

  • It establishes relationships between tables.

  • It helps maintain referential integrity.

  • A table can contain multiple Foreign Key constraints.

  • A Foreign Key can contain duplicate values.

  • It can allow NULL values if the column permits NULL.

  • It can reference a Primary Key or a UNIQUE key.

  • The referencing and referenced columns must have compatible data types.

4. How to Create a Foreign Key in SQL Server

Let's understand how to create a Foreign Key using a practical example.

Step 1: Create the Departments Table

CREATE TABLE Departments
(
    DepartmentID INT PRIMARY KEY,
    DepartmentName VARCHAR(100)
);

This table stores department information.

Step 2: Create the Students Table

CREATE TABLE Students
(
    StudentID INT PRIMARY KEY,
    StudentName VARCHAR(100),
    Age INT,
    DepartmentID INT,

    CONSTRAINT FK_Students_Departments
    FOREIGN KEY (DepartmentID)
    REFERENCES Departments(DepartmentID)
);

Explanation:

  • StudentID: Primary Key of the Students table.

  • StudentName: Stores student names.

  • Age: Stores student ages.

  • DepartmentID: References the Departments table.

  • FK_Students_Departments: Name of the Foreign Key constraint.

  • REFERENCES Departments(DepartmentID): Defines the referenced table and column.

Now, the Students table is connected to the Departments table.

5. Insert Records into the Departments Table

Before inserting student records, first add department information.

INSERT INTO Departments
(DepartmentID, DepartmentName)
VALUES
(1, 'Computer Science'),
(2, 'Management'),
(3, 'Information Technology'),
(4, 'Commerce');

Execute the query to insert four department records.

To view the records:

SELECT * FROM Departments;

6. Insert Records into the Students Table

Now insert student information with valid DepartmentID values.

INSERT INTO Students
(StudentID, StudentName, Age, DepartmentID)
VALUES
(101, 'Rahul Sharma', 21, 1),
(102, 'Priya Verma', 22, 2),
(103, 'Amit Kumar', 20, 1),
(104, 'Neha Patel', 23, 3);

These records will be inserted successfully because all DepartmentID values already exist in the Departments table.

What Happens If We Insert an Invalid Foreign Key?

Try executing the following query:

INSERT INTO Students
(StudentID, StudentName, Age, DepartmentID)
VALUES
(105, 'Rohit Singh', 22, 10);

This query will generate a Foreign Key constraint error because DepartmentID 10 does not exist in the Departments table.

Important: A Foreign Key prevents inserting an invalid reference into the Students table.

7. Difference Between Primary Key and Foreign Key

Primary Key and Foreign Key are both important database concepts, but they perform different functions.

Primary Key Foreign Key
Uniquely identifies records. Establishes relationships between tables.
Does not allow NULL values. Can allow NULL values if configured.
Must contain unique values. Can contain duplicate values.
One Primary Key constraint per table. Multiple Foreign Key constraints can exist.
Identifies records within a table. References a key in another table.
Enforces entity integrity. Enforces referential integrity.

Example:

In a college database:

  • StudentID is the Primary Key of the Students table.

  • DepartmentID is the Primary Key of the Departments table.

  • DepartmentID in the Students table is a Foreign Key.

8. How to Create a Foreign Key in an Existing Table

Sometimes, you may already have two tables and want to establish a relationship between them.

You can use the ALTER TABLE command.

Example:

ALTER TABLE Students
ADD CONSTRAINT FK_Students_Departments
FOREIGN KEY (DepartmentID)
REFERENCES Departments(DepartmentID);

This query adds a Foreign Key constraint to an existing Students table.

Note: Before adding a Foreign Key, existing values in the referencing column must satisfy the relationship rules. Otherwise, SQL Server will return an error.

9. Retrieve Related Records Using INNER JOIN

After creating Primary Key and Foreign Key relationships, you can retrieve related information from multiple tables using JOIN.

For example, suppose you want to display student names along with their department names.

Execute the following query:

SELECT
    Students.StudentID,
    Students.StudentName,
    Departments.DepartmentName
FROM Students
INNER JOIN Departments
ON Students.DepartmentID = Departments.DepartmentID;

Expected Output:

StudentID StudentName DepartmentName
101 Rahul Sharma Computer Science
102 Priya Verma Management
103 Amit Kumar Computer Science
104 Neha Patel Information Technology

Explanation:

  • INNER JOIN: Combines matching records from both tables.

  • Students.DepartmentID: Contains the Foreign Key.

  • Departments.DepartmentID: Contains the Primary Key.

  • ON: Defines the relationship condition.

This example demonstrates how Primary Keys and Foreign Keys help retrieve related information from multiple database tables.

10. What Is a Composite Primary Key?

A Composite Primary Key is a Primary Key created using two or more columns together.

It is useful when a single column cannot uniquely identify every record.

Example:

Consider a StudentCourses table:

StudentID CourseID EnrollmentDate
101 1 2026-01-10
101 2 2026-01-12
102 1 2026-01-15

Here, StudentID alone is not unique because one student can enroll in multiple courses.

Similarly, CourseID alone may also repeat.

Therefore, we can use both columns together.

CREATE TABLE StudentCourses
(
    StudentID INT,
    CourseID INT,
    EnrollmentDate DATE,

    CONSTRAINT PK_StudentCourses
    PRIMARY KEY (StudentID, CourseID)
);

Now, the combination of StudentID and CourseID must be unique.

Remember: A table can have only one Primary Key constraint, but that constraint can contain multiple columns.

11. What Happens When We Delete a Parent Record?

SQL Server maintains relationships between tables and prevents changes that would violate referential integrity.

For example, suppose DepartmentID 1 is already assigned to students.

Try executing:

DELETE FROM Departments
WHERE DepartmentID = 1;

SQL Server will normally prevent this deletion because DepartmentID 1 is referenced by records in the Students table.

Using ON DELETE CASCADE

Sometimes, you may want related child records to be deleted automatically when a parent record is deleted.

You can define this behavior using ON DELETE CASCADE.

Example:

CREATE TABLE Departments
(
    DepartmentID INT PRIMARY KEY,
    DepartmentName VARCHAR(100)
);

CREATE TABLE Students
(
    StudentID INT PRIMARY KEY,
    StudentName VARCHAR(100),
    DepartmentID INT,

    CONSTRAINT FK_Students_Departments
    FOREIGN KEY (DepartmentID)
    REFERENCES Departments(DepartmentID)
    ON DELETE CASCADE
);

Now, deleting a department will also delete the related student records.

Important: Use CASCADE carefully because deleting a parent record can automatically delete multiple related records.

12. Real-World Applications of Primary Key and Foreign Key

Primary Keys and Foreign Keys are widely used in real-world database applications.

A. Student Management System

  • Students table: StudentID as Primary Key.

  • Departments table: DepartmentID as Primary Key.

  • Students table: DepartmentID as Foreign Key.

B. E-Commerce Website

  • Customers table: CustomerID as Primary Key.

  • Orders table: OrderID as Primary Key.

  • Orders table: CustomerID as Foreign Key.

C. Hospital Management System

  • Patients table: PatientID as Primary Key.

  • Doctors table: DoctorID as Primary Key.

  • Appointments table: PatientID and DoctorID as Foreign Keys.

D. Banking Management System

  • Customers table: CustomerID as Primary Key.

  • Accounts table: AccountID as Primary Key.

  • Accounts table: CustomerID as Foreign Key.

These relationships help maintain accurate and organized information across different database tables.

13. Common Mistakes Beginners Should Avoid

While working with Primary Keys and Foreign Keys, beginners may encounter several common problems.

1. Inserting Duplicate Primary Key Values

A Primary Key does not allow duplicate values. Always use a unique identification number.

2. Inserting Invalid Foreign Key Values

A Foreign Key value must match an existing referenced key unless it is NULL and the column permits it.

3. Deleting Parent Records Without Checking Relationships

SQL Server may prevent deletion when child records reference the parent record.

4. Using Incompatible Data Types

Ensure that referencing and referenced columns have compatible data types.

5. Forgetting to Create the Parent Table First

When creating a Foreign Key, the referenced table and key must already exist.

6. Not Understanding Composite Keys

When a record requires multiple columns for unique identification, consider using a Composite Primary Key.

14. Frequently Asked Questions (FAQs)

Q1. What is a Primary Key in SQL Server?

A Primary Key is a column or combination of columns that uniquely identifies every record in a database table. It does not allow duplicate or NULL values.

Q2. What is a Foreign Key in SQL Server?

A Foreign Key is a column or combination of columns used to establish a relationship between tables by referencing a Primary Key or UNIQUE key.

Q3. Can a table have multiple Primary Keys?

No. A table can have only one Primary Key constraint, but that constraint can contain multiple columns.

Q4. Can a Foreign Key contain duplicate values?

Yes. A Foreign Key can contain duplicate values because multiple records may reference the same parent record.

Q5. Can a Foreign Key contain NULL values?

Yes. A Foreign Key can contain NULL values when the referencing column allows NULL values.

Q6. What is the difference between Primary Key and Foreign Key?

A Primary Key uniquely identifies records in its own table, whereas a Foreign Key establishes a relationship with a key in another table.

Q7. What is a Composite Primary Key?

A Composite Primary Key uses two or more columns together to uniquely identify a record.

Q8. Can a Foreign Key reference a UNIQUE key?

Yes. SQL Server allows a Foreign Key to reference columns backed by a UNIQUE constraint or qualifying unique index.

Q9. What is Referential Integrity?

Referential Integrity ensures that relationships between related database tables remain valid and consistent.

Q10. Why are Primary Keys and Foreign Keys important?

They help organize relational databases, prevent invalid relationships, maintain data integrity, and connect information stored in different tables.

Conclusion

Primary Keys and Foreign Keys are fundamental concepts in Microsoft SQL Server and relational database management systems. A Primary Key uniquely identifies records in a table, while a Foreign Key establishes relationships between tables and maintains referential integrity.

In this tutorial, we learned how to create Primary Keys and Foreign Keys, insert records, retrieve related information using INNER JOIN, understand Composite Primary Keys, and manage parent-child relationships using practical SQL Server examples.

We also explored how these concepts are used in real-world applications such as Student Management Systems, E-Commerce Websites, Hospital Management Systems, and Banking Applications.

At Param Classes, our goal is to help students and beginners understand database concepts through simple explanations, practical SQL queries, and step-by-step programming tutorials. Keep practising these examples in SQL Server to strengthen your database development skills and build a strong foundation for advanced SQL concepts.

Keep Learning | Keep Practising | Keep Growing with Param Classes!

←
Post 21 of 40
→