Foreign Keys in SQL: Linking Tables Together, Explained

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

← 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 →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

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.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

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.

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?
A foreign key is a column, or set of columns, in a child table whose non-null values must match a key in a parent table, usually its primary key. If orders.customer_id references customers, an order for a customer who does not exist is rejected. This guarantee is called referential integrity. A null foreign key makes no claim about a parent, so add NOT NULL when every child row needs one.
What is the difference between ON DELETE CASCADE, SET NULL, and NO ACTION?
These referential actions decide what happens to child rows when their parent row is deleted. NO ACTION, the default in MySQL, SQL Server, and SQLite, blocks a delete that would leave orphaned child rows. CASCADE deletes the dependent child rows as well. SET NULL keeps the child rows but clears their reference, so the child column must allow nulls. SQL Server has no RESTRICT keyword, while MySQL and SQLite accept it.
Why isn't my foreign key being enforced?
Two common causes are that enforcement is switched off for the connection or that the storage engine ignores the declaration. SQLite leaves foreign key checks off by default on each new connection, so run PRAGMA foreign_keys = ON; before working. In MySQL, InnoDB enforces foreign keys, but some other storage engines may ignore them. Also confirm the constraint was actually declared, since a column that merely shares a name protects nothing.
Does creating a foreign key also create an index?
It depends on the system: MySQL's InnoDB creates an index on the child columns when no suitable one already exists, but SQLite and SQL Server do not. In those two, choose and create the child index separately. An index on the child column helps the database find matching child rows when a parent row is deleted or its key changes, and it can also speed up joins between the tables.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

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

Database Programming
3 credits · NCCRS
Enroll →