Skip to content
Learn Netverks

Lesson

Step 16/36 44% through track

foreign-keys-mysql

Foreign keys

Last reviewed May 28, 2026 Content v20260528
Track mode
sql_sandbox
Means
SQL sandbox
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches Foreign keys: the SQL patterns, schema habits, and query reasoning you need before advancing in MySQL.

Teams query Foreign keys on every MySQL codebase—skipping it leaves gaps in debugging and data reviews.

You will apply Foreign keys in contexts like: Web apps on shared hosting, ecommerce, and many startups’ first production DB.

Copy MySQL SQL into the mysql client, local MySQL/MariaDB, or DB Fiddle (MySQL dialect)—use DESCRIBE and EXPLAIN where lessons show them. The in-browser lab ships later; mysql client is the practice path now.

When you can explain the previous lesson's ideas without copying example queries verbatim.

InnoDB foreign keys enforce referential integrity with ON DELETE / ON UPDATE actions.

Define FK

CREATE TABLE order_lines (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  order_id BIGINT UNSIGNED NOT NULL,
  sku VARCHAR(32) NOT NULL,
  qty INT NOT NULL,
  CONSTRAINT fk_lines_order
    FOREIGN KEY (order_id) REFERENCES orders(id)
    ON DELETE CASCADE
) ENGINE=InnoDB;

Practice: Run on practice.

CASCADE caution

CASCADE DELETE removes children automatically—confirm product/ops expectations before enabling.

Important interview questions and answers

  1. Q: FK requires InnoDB?
    A: Yes—both parent and child must be InnoDB.
  2. Q: Index on FK column?
    A: Required for performance on parent lookups and deletes.

Self-check

  1. What does ON DELETE CASCADE do?
  2. Why index order_id?

Pitfall: CASCADE DELETE surprises—confirm with product team.

Interview prep

CASCADE DELETE?

Deletes child rows when parent deleted.

InnoDB required?

FK constraints only on InnoDB tables.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • CASCADE OK?
  • Index FK column?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump