Software Training Institute in Chennai with 100% Placements – SLA Institute

Easy way to IT Job

Share on your Social Media

Primary Key and Foreign Key in SQL

Published On: December 7, 2023

SQL, or Structured Query Language, is a powerful tool for handling relational databases. In the world of designing databases, two crucial concepts—Primary Keys and Foreign Keys—stand out for ensuring data integrity and building connections between tables. In this article, we’ll explore what these terms mean, their purposes, and how they work in SQL. 

We’ll use examples to make it clearer. So, let’s dive into the basics of Primary Key and Foreign Key in SQL with examples and see how they play a vital role in creating effective and well-connected database systems. Enhance your knowledge with SQL Training in Chennai for a comprehensive learning experience. Join to deepen your understanding and proficiency in SQL.

Primary Key in SQL

In SQL, think of a Primary Key like a special tag for each row in a table. This tag, usually a number or a combination of values, is unique for every row, making sure no two rows are tagged with the same label. We apply the Primary Key to one or more columns in a table, and its main job is to help us easily spot and tell apart each piece of information in that table.

Imagine it like giving each item in your to-do list a unique number. That way, you can quickly find, update, or refer to a specific task without any mix-ups. The Primary Key does something similar for rows in a database table—it makes each row stand out with its own special identifier, ensuring a tidy and organized database.

Let’s imagine a list of students in a school database. To keep things organized, we give each student a special number, like an ID card. This special number is what we call the Primary Key.

For example:

StudentID

FirstName

LastName

Grade

1

Alice

Johnson

A

2

Bob

Smith

B

3

Charlie

Brown

C

Here, the “StudentID” is the Primary Key. Each student has a unique ID, and we make sure no two students share the same ID. It’s like each student having their own special badge number.

If we want to find details about a particular student, like Bob Smith, we just need to look at his ID, which is 2. So, by searching for “StudentID = 2,” we can quickly get all the information about Bob Smith from the list. In simple terms, the Primary Key is like a unique tag for each student, making it easy to find and keep track of everyone in the database.

Foreign Key in SQL

In SQL, a Foreign Key is pivotal for establishing connections between tables, complementing the unique identification provided by the Primary Key within a table. This link is essential for data consistency and enforcing relationships. Learn more about Foreign Keys and how to create SQL tables for effective database management.Now, let’s extend our school database example to understand the concept of a Foreign Key. Imagine we have another table in our database called “Grades,” which stores information about the grades students received in their exams. To connect the “Grades” table with the “Students” table, we can use a Foreign Key.

Here’s how it might look:

Students Table:

StudentID

FirstName

LastName

Grade

1

Alice

Johnson

A

2

Bob

Smith

B

3

Charlie

Brown

C

Grades Table:

GradeID

StudentID

ExamType

Score

101

1

Midterm

95

102

2

Midterm

88

103

3

Midterm

75

In this example:

  • The “Students” table has a Primary Key, “StudentID,” which uniquely identifies each student.
  • The “Grades” table has a column called “StudentID,” which is a Foreign Key. This Foreign Key references the “StudentID” column in the “Students” table.
  • The Foreign Key establishes a connection between the “Grades” table and the “Students” table. It ensures that the values in the “StudentID” column of the “Grades” table correspond to valid “StudentID” values in the “Students” table.

For instance, let’s say we want to find the exam scores for Bob Smith. We know Bob’s “StudentID” is 2. By searching for “StudentID = 2” in the “Grades” table, we can retrieve all the exam scores associated with Bob Smith.

SELECT * FROM Grades WHERE StudentID = 2;

This Foreign Key relationship helps maintain consistency between the two tables. If a student is added to the “Grades” table, their “StudentID” must match a valid ID in the “Students” table, ensuring that the information stays accurate and connected across the database.

In simpler terms, the Foreign Key acts like a link between tables, connecting related information and allowing us to navigate through the database to gather comprehensive details about students and their grades.

Syntax for Primary Key and Foreign Key in SQL

Primary Key Syntax:

When defining a table, you designate a column or a set of columns as the Primary Key. Here’s the syntax:

CREATE TABLE TableName (

 Column1 DataType PRIMARY KEY,

 Column2 DataType,

 …

);

Example:

CREATE TABLE Students (

 StudentID INT PRIMARY KEY,

 FirstName VARCHAR(50),

 LastName VARCHAR(50),

 Grade CHAR(1)

);

In this example, the StudentID column is designated as the Primary Key for the “Students” table.

Foreign Key Syntax:

When creating a table with a Foreign Key, you specify the column as a Foreign Key and indicate which table and column it references. Here’s the syntax:

CREATE TABLE TableName (

 Column1 DataType,

 Column2 DataType,

 Foreign Key (Column3) REFERENCES AnotherTable(AnotherColumn),

 …

);

Example:

CREATE TABLE Grades (

 GradeID INT PRIMARY KEY,

 StudentID INT,

 ExamType VARCHAR(50),

 Score INT,

 FOREIGN KEY (StudentID) REFERENCES Students(StudentID)

);

In this example, the StudentID column in the “Grades” table is a Foreign Key that references the StudentID column in the “Students” table.

Differentiating Primary Key and Foreign Key in SQL

Feature

Primary Key

Foreign Key

Definition

Uniquely identifies each record within the table.

Establishes relationships by referencing the Primary Key in another table.

Column Location

Resides within the same table it is defined.

Exists in the same table but refers to the Primary Key in another table.

Uniqueness

Must be unique within the table; without any duplicates.

Values can be duplicated within the table; uniqueness is enforced across tables.

Null Values

Cannot contain null values.

Can contain null values, indicating optional or undefined relationships.

Data Integrity within the Table

Ensures data integrity by preventing duplicate or null values within its own table.

Can coexist with duplicate values but maintains referential integrity by linking to a Primary Key.

Syntax within a Table

Declared using the PRIMARY KEY constraint on one or more columns within the same table.

Declared using the FOREIGN KEY constraint on a column within the same table, referencing the Primary Key in another table.

Association

Associated with the table where it is defined.

Links to and associates with the Primary Key in another table.

Use Case

Identifies unique records within the table.

Facilitates connections and relationships between tables.

Conclusion

In summary, mastering Primary Key and Foreign Key in SQL is fundamental for creating well-organized databases. The Primary Key ensures each record’s uniqueness, while the Foreign Key builds connections between tables, maintaining data consistency. These key concepts, exemplified by real-world examples, form the backbone of effective SQL databases. Understanding Primary Key and Foreign Key in SQL with examples is essential for creating reliable and interconnected databases. To explore more fascinating methods in SQL, delve into this captivating blog Joins in SQL.

Share on your Social Media

Just a minute!

If you have any questions that you did not find answers for, our counsellors are here to answer them. You can get all your queries answered before deciding to join SLA and move your career forward.

We are excited to get started with you

Give us your information and we will arange for a free call (at your convenience) with one of our counsellors. You can get all your queries answered before deciding to join SLA and move your career forward.