Foreign Key Constraint (4.2.2.2) - Structured Query Language (SQL) - Part 1
Students

Academic Programs

AI-powered learning for grades 8-12, aligned with major curricula

Professional

Professional Courses

Industry-relevant training in Business, Technology, and Design

Games

Interactive Games

Fun games to boost memory, math, typing, and English skills

FOREIGN KEY Constraint

FOREIGN KEY Constraint

Practice

Interactive Audio Lesson

Listen to a student-teacher conversation explaining the topic in a relatable way.

Introduction to FOREIGN KEY Constraints

πŸ”’ Unlock Audio Lesson

Sign up and enroll to listen to this audio lesson

0:00
--:--
Teacher
Teacher Instructor

Today, class, we are diving into one of the key constraints in relational databases, the FOREIGN KEY. Can anyone tell me why we use constraints in databases?

Student 1
Student 1

To ensure that the data is valid and follows certain rules, right?

Teacher
Teacher Instructor

Exactly! Constraints like FOREIGN KEY help maintain the integrity of our data by linking tables together. Now, who can explain how the FOREIGN KEY constraint functions?

Student 2
Student 2

It links a column in one table to the primary key in another table?

Teacher
Teacher Instructor

Correct! This linkage is crucial because it prevents orphaned records in our database. Let’s remember it with the acronym β€˜LINK’ β€” β€˜Local Integrity Network Key’.

Student 3
Student 3

So that means if a record is deleted in the parent table, the referencing entries in the child table can also be deleted, right?

Teacher
Teacher Instructor

That's right! There are various options like CASCADE or SET NULL that we will explore. Let’s summarize: FOREIGN KEY constraints enforce data relationships and ensure data integrity across tables.

Syntax and Examples of FOREIGN KEY

πŸ”’ Unlock Audio Lesson

Sign up and enroll to listen to this audio lesson

0:00
--:--
Teacher
Teacher Instructor

Let’s look at the syntax for a FOREIGN KEY constraint. Can anyone read the general structure for defining it?

Student 4
Student 4

It starts with FOREIGN KEY followed by the column names in parentheses, then REFERENCES with the referenced table and columns.

Teacher
Teacher Instructor

Great! Here’s an example: `FOREIGN KEY (MajorDeptID) REFERENCES Departments(DeptID)`. Why do we need to specify actions like ON DELETE or ON UPDATE?

Student 1
Student 1

To decide how changes in the parent table affect the child table, like whether to delete corresponding records.

Teacher
Teacher Instructor

Yes! Actions like CASCADE or SET NULL help manage our data efficiently. Let’s put this understanding into practice; can anyone give me scenarios where these actions would be useful?

Student 2
Student 2

If we have a department that gets deleted, using CASCADE would remove all students associated with it.

Teacher
Teacher Instructor

Exactly! Always consider the implications of these actions on your data relationships.

Practical Applications of FOREIGN KEY Constraints

πŸ”’ Unlock Audio Lesson

Sign up and enroll to listen to this audio lesson

0:00
--:--
Teacher
Teacher Instructor

Now let’s explore practical applications of FOREIGN KEY constraints. Can someone explain why it’s essential in a university database?

Student 3
Student 3

It ensures that every student is majoring in a valid department. If a department is deleted, we make sure no students are left hanging without a major!

Teacher
Teacher Instructor

Exactly! This maintains consistency and integrity in our data. Another application could be in an online store database. Can anyone think of a foreign key example there?

Student 4
Student 4

Linking an order table to a customer table! If a customer is deleted, we’d need to handle their orders too.

Teacher
Teacher Instructor

Perfect! Handling referential integrity properly supports good database design. Remember, we want to keep our data valid and meaningful.

Introduction & Overview

Read summaries of the section's main ideas at different levels of detail.

Quick Overview

The FOREIGN KEY constraint is a fundamental aspect of relational databases that enforces referential integrity between tables.

Standard

The FOREIGN KEY constraint links a column in one table to the PRIMARY KEY in another, ensuring that relationships between tables remain consistent. This prevents the creation of orphaned records and enforces business rules in database design.

Detailed

FOREIGN KEY Constraint

The FOREIGN KEY constraint plays a pivotal role in relational database design by ensuring that relationships between tables maintain referential integrity. When you define a FOREIGN KEY in a table (commonly referred to as a 'child' table), you link it to the PRIMARY KEY of another table (referred to as the 'parent' table).

Purpose

The primary purpose of the FOREIGN KEY constraint is to enforce rules that prevent invalid data from being recorded in your database. This includes ensuring that any value entered into the foreign key column in the child table corresponds to an existing value in the primary key column of the parent table.

Syntax

The typical syntax for defining a FOREIGN KEY is as follows:

Code Editor - sql

Actions

The FOREIGN KEY constraint also allows for defining actions on related records when changes occur:
- ON DELETE action determines what happens to the referencing records when a referenced record is deleted:
- CASCADE: Automatically delete the child records.
- SET NULL: Set the foreign key values to NULL.
- NO ACTION/RESTRICT: Prevent deletion of the parent record if any child records exist.

  • ON UPDATE action specifies how updates to the primary key affect the foreign key:
  • Similar actions can be defined as those for deletion.

Using the example from the Students table, the syntax shows how the MajorDeptID foreign key in the Students table references the DeptID in the Departments table. This ensures that any department ID must exist in the Departments table for it to be valid in the Students table.

Conclusion

By utilizing the FOREIGN KEY constraint, database designers can enforce business rules and maintain data integrity across related data. This mechanism enhances the reliability and accuracy of database transactions.

Youtube Videos

What is a Foreign Key Constraint? Understanding Primary & Foreign Keys
What is a Foreign Key Constraint? Understanding Primary & Foreign Keys
MySQL: FOREIGN KEYS are easy (kind of)
MySQL: FOREIGN KEYS are easy (kind of)
Lec-10: Foreign Key in DBMS | Full Concept with examples | DBMS in Hindi
Lec-10: Foreign Key in DBMS | Full Concept with examples | DBMS in Hindi
Data Types, Primary-Foreign Keys & Constraints in SQL | SQL Tutorial In Hindi 2
Data Types, Primary-Foreign Keys & Constraints in SQL | SQL Tutorial In Hindi 2
How to get Parent Table, Reference Table, Foreign Key Constraint Name and Columns in SQL Server-P 71
How to get Parent Table, Reference Table, Foreign Key Constraint Name and Columns in SQL Server-P 71
SQL - Part 71- Primary Key Integrity Constraint
SQL - Part 71- Primary Key Integrity Constraint
Primary Key and Foreign Key Constraints in SQL
Primary Key and Foreign Key Constraints in SQL
SQL FOREIGN KEY Constraint | SQL tutorial for beginners
SQL FOREIGN KEY Constraint | SQL tutorial for beginners
SQL Handson 18/25:CONSTRAINTS SQL Project  #sqltutorial #dataanalytics #SQL
SQL Handson 18/25:CONSTRAINTS SQL Project #sqltutorial #dataanalytics #SQL
Primary & Foreign Keys
Primary & Foreign Keys

Key Concepts

  • FOREIGN KEY: A constraint linking a child's table column to a primary key in a parent table, ensuring referential integrity.

  • CASCADE: An action that allows automatic deletion of child records when a parent record is deleted.

  • SET NULL: An option that sets the foreign key in child records to NULL when the parent record is deleted.

  • NO ACTION: Prevents deletion of a parent record if corresponding child records exist.

Examples & Applications

In a university database, the FOREIGN KEY constraint enforces that every student entry must relate to an existing department.

In an e-commerce database, the foreign key in the orders table references the users table, ensuring no orders exist without a corresponding user.

Memory Aids

Interactive tools to help you remember key concepts

🎡

Rhymes

When deleting what you’ll find, children go if parents unwind.

πŸ“–

Stories

Once in a village, a department oversaw students. When the department closed down, all students moved out, showing how CASCADE keeps things tidy in our database.

🧠

Memory Tools

Remember the β€˜Lifeline’ for FOREIGN KEY: Links Items for Family Integrity, keeping data intact!

🎯

Acronyms

FOREIGN

Families Ensure Referenced Integrity in Normalization.

Flash Cards

Glossary

FOREIGN KEY

A constraint that establishes a relationship between two tables by linking a column in one table to the primary key of another table.

REFERENTIAL INTEGRITY

A property of a relational database that ensures relationships between tables remain consistent.

CASCADE

An action defined in a FOREIGN KEY constraint that automatically deletes records in the child table when corresponding records in the parent table are deleted.

SET NULL

An action defined in a FOREIGN KEY constraint that sets the foreign key value in the child table to NULL when the corresponding record in the parent table is deleted.

NO ACTION

An action that prevents the deletion of a record in the parent table if there are existing foreign key references in the child table.

Reference links

Supplementary resources to enhance your learning experience.