Databases & System Design•Part 2: Relational Databases (RDBMS / PostgreSQL / MySQL) (6 - 25)
Primary Key vs Unique Key vs Foreign Key:
In Simple Words:
- Primary Key: Uniquely identifies each row; strictly unique and cannot be
NULL(one per table). - Unique Key: Enforces unique values; allows
NULLvalues. - Foreign Key: Links a column to the Primary Key of another table to maintain referential integrity.
sql
CREATE TABLE orders (
id SERIAL PRIMARY KEY, -- Primary Key (NOT NULL & UNIQUE)
order_number VARCHAR(50) UNIQUE NOT NULL, -- Unique Key
user_id INT REFERENCES users(id) ON DELETE CASCADE -- Foreign Key
);