Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
MySQL + SQL · Lesson 18

Primary Key and Foreign Key in MySQL

In this lesson: Create primary and foreign keys in MySQL with CREATE TABLE and ALTER, rules and errors explained with output.

Why keys exist

A database is rarely one big table. Real information is split across several tables — students, courses, teachers, orders — and those tables need to connect to each other reliably. Keys are how that connection is made safe. Without keys, a database is just loose spreadsheets; with keys, it becomes a linked, trustworthy system.

There are two keys you must understand first. A primary key answers "which exact row is this?" inside one table. A foreign key answers "which row in another table does this belong to?" Together they turn separate tables into a connected whole where relationships cannot break.

💡 Note

Think of a primary key as a person's unique ID number, and a foreign key as writing that same ID number on a form to say "this form belongs to that person".

Primary key: the row identity

A primary key is a column whose value is different for every row and is never empty. It is the reliable handle you use to find, update or delete one specific row.

MySQL
CREATE TABLE customers (
    id   INT PRIMARY KEY,
    name VARCHAR(50)
);

INSERT INTO customers VALUES (1, 'Aarav'), (2, 'Diya');
INSERT INTO customers VALUES (1, 'Kabir');  -- fails, id 1 exists
Output:
ERROR 1062 (23000): Duplicate entry '1' for key 'customers.PRIMARY'

MySQL rejected the third row because id 1 is already used. That guarantee — every id is unique and present — is exactly what lets other tables safely point to a customer by id.

Foreign key: linking tables

A foreign key is a column in one table that must match a primary key value in another table. It creates and protects the link between them.

MySQL
CREATE TABLE orders (
    order_id    INT PRIMARY KEY,
    customer_id INT,
    amount      DECIMAL(8,2),
    FOREIGN KEY (customer_id) REFERENCES customers(id)
);

Here customer_id in orders is a foreign key. It must hold an id that already exists in customers. This single line stops a whole category of bugs — you can never create an order for a customer who does not exist.

Seeing both keys work together

Let us insert valid and invalid data to watch the relationship being enforced.

MySQL
INSERT INTO orders VALUES (101, 1, 500.00);   -- ok, customer 1 exists
INSERT INTO orders VALUES (102, 9, 300.00);   -- fails, customer 9 missing
Output:
Row 101 inserted.
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails

The first order linked cleanly to an existing customer. The second was blocked because customer 9 is not in customers. The primary key made customer 1 findable; the foreign key made the link trustworthy.

ON DELETE and ON UPDATE

What should happen to orders when a customer is deleted? You decide with ON DELETE rules.

OptionEffect when parent is deleted
RESTRICT (default)Blocks the delete if child rows exist
CASCADEDeletes the child rows too
SET NULLSets the child foreign key to NULL
MySQL
CREATE TABLE orders (
    order_id    INT PRIMARY KEY,
    customer_id INT,
    FOREIGN KEY (customer_id) REFERENCES customers(id)
        ON DELETE CASCADE
);

With ON DELETE CASCADE, deleting customer 1 automatically deletes all of customer 1's orders. Powerful, but use it consciously — the deletion spreads to child tables.

🏋️ Practice

Build a students and marks pair where marks.student_id is a foreign key to students.id with ON DELETE CASCADE. Insert a student and two marks, then delete the student. How many rows remain in each table?

Primary key vs foreign key

AspectPrimary keyForeign key
PurposeIdentify a rowLink to another table
NULL allowed?NeverYes (unless NOT NULL)
How many per tableExactly oneMany allowed
Duplicate valuesNot allowedAllowed

The clearest way to hold the difference: a primary key stands for the row's own identity, while a foreign key is a reference to some other row's identity.

Common mistakes

  • Mismatched data types. The foreign key and the primary key it points to must be the same type, or MySQL refuses the link.
  • Inserting the child before the parent. The parent row must exist first, otherwise the foreign key check fails.
  • Forgetting the parent's column must be a key. A foreign key can only reference a primary key or a unique column, not any random column.
  • Using CASCADE without thinking. It can delete far more than you intended if relationships chain together.

Summary

  • A primary key uniquely identifies each row and is never NULL — one per table.
  • A foreign key links to a primary key in another table — many allowed per table.
  • Foreign keys stop orphan rows and keep relationships valid automatically.
  • ON DELETE CASCADE / SET NULL / RESTRICT control what happens to child rows.
  • The two columns must share a compatible data type.

Next, protect these columns with rules in constraints in MySQL, or organize your tables cleanly with normalization in DBMS.

Frequently Asked Questions

What is the main difference between a primary key and a foreign key?
A primary key uniquely identifies each row within its own table and can never be NULL. A foreign key sits in a second table and points to a primary key in the first table, creating a link between them. In short: primary key is about identity, foreign key is about relationship.
Can a table have more than one foreign key?
Yes. A single table can have many foreign keys, each pointing to a different parent table. An orders table, for example, might have one foreign key to customers and another to products. But a table can have only one primary key.
Can a foreign key reference the same table?
Yes, this is called a self-referencing foreign key. A common example is an employees table where a manager_id column is a foreign key pointing back to the id column of the same employees table, letting each employee point to their manager.
What does ON DELETE CASCADE do?
ON DELETE CASCADE means that when a parent row is deleted, all child rows that point to it are automatically deleted too. For example, deleting a customer would delete all of that customer orders. It keeps data consistent but must be used carefully because the deletion spreads.
Do the primary key and foreign key columns need the same data type?
Yes. The foreign key column and the primary key it references must have compatible data types (for example both INT). If they differ, MySQL refuses to create the foreign key relationship.
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicCandidate Key, Super Key and Alternate Key Your progress: 18 / 151 (12%) · Lesson 19 / 151 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free