What is Primary key, Foreign key & Unique key?
- PRIMARY KEY: A primary key is a unique identifier that can’t have any duplicates and it can’t be null.
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
name VARCHAR(50)
);
- FOREIGN KEY: A foreign key column is a way to establish a relationship between two tables.
-- Create the parent table
CREATE TABLE departments (
department_id INT PRIMARY KEY, -- Primary Key
department_name VARCHAR(50) NOT NULL
);
-- Create the child table with a foreign key
CREATE TABLE employees (
employee_id INT PRIMARY KEY, -- Primary Key
employee_name VARCHAR(50) NOT NULL,
department_id INT, -- Foreign Key
FOREIGN KEY (department_id) REFERENCES departments(department_id)
);
- UNIQUE KEY: A unique key in SQL makes sure that all values in a column are different and no duplicates are allowed.
CREATE TABLE users (
user_id INT UNIQUE,
email VARCHAR(100) UNIQUE
);

Differences between Primary Key, Foreign Key, and Unique Key:
| Feature |
Primary Key |
Foreign Key |
Unique Key |
| Null Values |
Cannot be NULL. |
Can contain NULL values. |
Can contain one NULL value. |
| Uniqueness |
Must be unique. |
Can have duplicate values in the child table. |
Must be unique. |
| Number per Table |
Only one per table. |
Can have multiple in a table. |
Can have multiple in a table. |