🔍
👶 Kids📝 Blog About Contact 🚀 Get Started Free

SQL – FOREIGN KEY

Link tables together and enforce referential integrity using FOREIGN KEY constraints.

A foreign key is a column that references the primary key of another table, creating a guaranteed link between related records. The FOREIGN KEY constraint enforces referential integrity — it prevents orphaned records (e.g., an enrollment referencing a student that doesn’t exist) and prevents accidentally deleting a parent record that still has children.

In SQLite, foreign keys must be explicitly enabled per connection with PRAGMA foreign_keys = ON; — they are off by default for backward compatibility.

ON DELETE actions

OptionWhat happens to children when parent is deleted
CASCADEChildren are also deleted automatically
SET NULLChild foreign key becomes NULL
RESTRICTDelete blocked if children exist
NO ACTIONDefault — similar to RESTRICT

Try It Yourself — Interactive SQL Editor

Edit the query below and click Run Query ▶ to see live results powered by SQLite running directly in your browser.

SQLite – edit & run
Results
← Click Run Query ▶ to see results

Key Points

  • Foreign keys link child rows to valid parent rows
  • Prevents orphaned records and broken references
  • SQLite requires PRAGMA foreign_keys = ON; to enforce them
  • ON DELETE CASCADE auto-removes children when the parent is deleted

Pro Tip from CodesCompiler: The best way to learn SQL is to break things intentionally — modify the query above, change the WHERE conditions, try different columns. Every error teaches you something the docs cannot.

In the next lesson, we continue exploring SQL’s powerful feature set to build your database mastery.