UPI Study › Courses › Database Programming › Free lessons › Lesson 2.6 Free with a free account
Foreign Keys in SQL: Linking Tables Together
Database Programming · Chapter 2: Normalization and Data IntegritySection 2.6 · lesson 13 of 7610 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Database Programming.
Lesson complete
Earn the 3 college credits for Database Programming
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: SQL Constraints: Enforcing Rules on Your Data →← Primary Keys in SQL: What They Are and How to Use ThemNext lesson: SQL Constraints: Enforcing Rules on Your Data →
A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →
In this lesson
Protect links between tables with foreign keys and referential actions.
- Define parent and child tables, foreign keys, and referential integrity
- Compare NO ACTION, RESTRICT, CASCADE, and SET NULL referential actions
- Explain how InnoDB, SQLite, and SQL Server enforce and index foreign keys
- Order inserts and deletes so parent and child rows stay valid
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (1,158 words). Read along, or search it.
Opening Problem
An Order for a Missing Customer
An order points to customer ninety-nine, but Lantern Books has no such customer. Should the database accept the order and hope someone fixes it later? A foreign key protects that connection. Our fictional customer and order subset stores each customer's identity in the order, rather than copying their details. We will try missing parents, parent deletion, and optional links. Each experiment starts in a fresh memory database.
Key Terms
Parent, Child, and Orphan Rows
Customers is the parent relation, and Orders is the child. A foreign key is the child column, or columns, referencing a permitted parent key. Referential integrity requires non-null references to match. A non-null child value with no matching parent would be an orphan. A nullable reference allows an optional link. Add not null when every order must name a customer, as our canonical shop requires. Parent and child describe this particular relationship. The same relation can be a child of one table and parent of another.
Declaring the Key
Constraint, Foreign Key, and References Clauses
Read the definition in parts: constraint names the rule, foreign key names the child column, and references names the parent key. Use a primary or suitable unique parent key, with matching column types for portable designs. Composite references need all components in the correct order. This SQLite connection explicitly enables foreign keys before doing work. Enforcement is connection-specific; an undeclared or disabled relationship cannot protect the data. Parent-first creation is the portable workflow. SQLite can accept a child definition before its parent, but valid writes still need the referenced structure and rows.
Orphan Test
Rejecting a Reference to an Absent Parent
The new order attempts to reference an absent parent. A foreign key enforces the relationship. Ninety-nine claims a specific customer exists. It is not a null marker. The original orders reference customers one and two. Those references are valid. Run the orphan insert, then inspect the stored orders. The SQLite shell reports its own foreign-key diagnostic. The insert fails; the original orders remain. Correct the reference or register the actual customer, rather than inventing a parent.
Blocked Deletes
No Action Protects Asha's Order
Try removing Asha while her order still refers to her. No cascade is configured. The default no-action policy rejects a change that would break the reference. In InnoDB, no action behaves like restrict for these ordinary immediate checks. SQL Server uses no action and has no restrict keyword. SQLite also supports restrict; deferred constraints can make timing differences matter. Run the parent deletion, then inspect customers. Removing the parent cannot leave a dangling non-null child reference. Both customers remain after rejection. The relationship is protected; choosing the business policy remains your responsibility.
Engine Support
InnoDB Enforcement and Child Indexes
InnoDB is MySQL's usual storage engine for these examples, and it enforces foreign keys. Some other engines may ignore declarations. InnoDB supplies a suitable child index if needed. SQLite and SQL Server need a separately chosen child index; declaring the foreign key does not create it. For MySQL error recognition, fourteen fifty-two indicates an invalid child reference; fourteen fifty-one indicates a blocked parent change. These are vendor meanings, not local terminal output.
ON UPDATE CASCADE
Following a Changed Parent Key
On update cascade follows a changed parent key. This disposable variant explicitly configures update and delete cascading. Changing customer one to one hundred one should carry Asha's order reference. Stable keys make this uncommon. Unrelated references stay unchanged. Ben's order still refers to customer two. Run the temporary parent-key update, then inspect the order references. The course baseline remains unchanged. Asha's order now references one hundred one, while Ben's still references two. The configured update action preserved the link.
ON DELETE CASCADE
Removing Dependent Orders with Their Parent
On delete cascade removes dependent children. It may suit items that have no independent meaning without their order. Cascading customer deletion can destroy valuable history. If invoices must remain, choose a policy that preserves them. A longer cascade follows only relationships configured to cascade. Run this cascading variant, then inspect the remaining orders. The experiment is isolated in memory. Only Ben's order remains. Asha's order disappeared with its parent, exactly as this particular foreign key requested.
ON DELETE SET NULL
Optional Customer Links for Draft Orders
On delete set null preserves children while removing their links. This separate draft-order design permits an optional customer. This draft design leaves its customer column nullable, so unlinking is possible. A foreign key also permits an initially null optional link. Null makes no claim that a particular parent identifier exists. Run the optional-link example, then inspect the retained draft. Coalesce displays the word unlinked for its null reference. Draft nine thousand one remains unlinked. This optional variant differs from canonical shop orders, which require a customer.
Quick Check
Set Null Meets a Required Reference
A new jobs table combines a required owner reference with on delete set null. The script inserts a matching owner and job, then deletes the owner. Which outcome follows: rejection with both rows retained, a cascading job deletion, or an unlinked job? Pause, and decide. Deletion is rejected, leaving the owner and job. Setting the child reference to null would violate its required-value rule. Run this combined-rule example. The definition can be accepted in SQLite, but the incompatible action fails when the delete is attempted. The diagnostic reports the required reference, and the owner count stays one. Cascade was never requested, and an unlinked job would break not null.
Action Summary
Choosing Actions the Engine Supports
Restrict or no action blocks a referenced parent change. Cascade propagates the configured change; set null retains children with optional references. SQL Server also supports set default. The resulting reference must still match a parent, so a default is not an escape from integrity checks. InnoDB rejects set default, and SQL Server uses no action instead of restrict. Choose from the actions supported by the actual engine.
Quick Check
A Cascade That Stops at Leaves
A fresh three-level example cascades from roots to branches. Leaves refer to branches with the default no-action policy. The script deletes the root. Will the entire chain vanish, will the delete be refused, or will the leaf be silently unlinked? Pause, and predict which rule decides the outcome. The delete is refused, and the root remains. Removing its branch would break the leaf reference protected by no action. Run the chain example, following both relationships. A cascading edge does not turn the next relationship into a cascade. The foreign-key diagnostic appears, and root count remains one. Unlinking would require a different explicit policy, rather than happening automatically.
Ordering Changes
Insert Parents First, Remove Children First
Insert parent rows before dependent children under ordinary immediate checks. In our shop chain, that means customers, then orders, then order items. Remove children before their parents unless the configured actions do that work. Delete items, then orders, then customers when removal is appropriate. Use a transaction for a related unit of work. Check constraint timing before relying on deferred behavior; the examples here use immediate checks. An existing-table foreign key can be added in supporting dialects with alter table. Detailed alteration and table-drop ordering are later topics.
Key Takeaways
Missing, Protected, and Optional Links
A foreign key enforces a relationship to a permitted parent key. Non-null references must match, while required links also need not null. Declare the relationship explicitly, enable enforcement where needed, and choose parent-change actions according to business meaning and engine support. Order related changes correctly. A missing parent, a protected child, and an optional link are different situations, with different repairs.
About Database Programming at UPI Study
Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every credit course with PRO →
Why take it here
Why students take Database Programming with UPI Study
Where the credit goes
Universities that work with NCCRS
Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Foreign Keys in SQL: Linking Tables Together
What is a foreign key in SQL?
What is the difference between ON DELETE CASCADE, SET NULL, and NO ACTION?
Why isn't my foreign key being enforced?
Does creating a foreign key also create an index?
About the Database Programming course
How many college credits is Database Programming?
How much does Database Programming cost and what is included?
Which universities accept UPI Study credits?
How long does Database Programming take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Database Programming.
76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
Updated
3 credits · NCCRSEnroll →