4 min read
•Question 9 of 29easyWhat is the difference between Primary Key and Foreign Key?
Understanding table relationships.
What You'll Learn
- Primary Key definition
- Foreign Key definition
- How they relate
Primary Key
Uniquely identifies each row in a table.
query.sqlSQL
CREATE TABLE users (
id INT PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(255) UNIQUE,
name VARCHAR(100)
);
-- Composite primary key
CREATE TABLE order_items (
order_id INT,
product_id INT,
quantity INT,
PRIMARY KEY (order_id, product_id)
);Properties:
- Must be unique
- Cannot be NULL
- One per table
- Often auto-incremented
Foreign Key
References a primary key in another table.
query.sqlSQL
CREATE TABLE orders (
id INT PRIMARY KEY AUTO_INCREMENT,
user_id INT,
total DECIMAL(10,2),
FOREIGN KEY (user_id) REFERENCES users(id)
);
-- With actions
CREATE TABLE orders (
id INT PRIMARY KEY,
user_id INT,
FOREIGN KEY (user_id) REFERENCES users(id)
ON DELETE CASCADE
ON UPDATE CASCADE
);Referential Actions:
- CASCADE: Delete/update related rows
- SET NULL: Set to NULL
- RESTRICT: Prevent deletion
- NO ACTION: Similar to RESTRICT
Comparison
| Feature | Primary Key | Foreign Key |
|---|---|---|
| Uniqueness | Must be unique | Can have duplicates |
| NULL | Not allowed | Allowed (usually) |
| Per table | One only | Multiple allowed |
| Purpose | Identify row | Reference other table |