SQL PRIMARY KEY
The PRIMARY KEY uniquely identifies each row in a table. It ensures no duplicate or NULL values exist in the key column(s). πΉ Basic Syntax πΉ Example πΉ Important Notes π§ Quick Recap Key Point Explanation PRIMARY KEY Uniquely identifies each row, no duplicates or NULLs Single or Composite Supports one or multiple columns as […]
The PRIMARY KEY uniquely identifies each row in a table. It ensures no duplicate or NULL values exist in the key column(s).
πΉ Basic Syntax
-- Single column primary key
column_name data_type PRIMARY KEY;
-- Composite primary key (multiple columns)
PRIMARY KEY (column1, column2);πΉ Example
CREATE TABLE employees (
employee_id INT PRIMARY KEY, -- unique ID, no NULLs
first_name VARCHAR(50),
last_name VARCHAR(50),
email VARCHAR(100) UNIQUE
);
-- Composite key example
CREATE TABLE orders (
order_id INT,
product_id INT,
quantity INT,
PRIMARY KEY (order_id, product_id) -- combination uniquely identifies each row
);πΉ Important Notes
- PRIMARY KEY columns must be UNIQUE and NOT NULL.
- Each table can have only one PRIMARY KEY.
- Primary key automatically creates a unique index for faster lookups.
- Often used as a reference in FOREIGN KEY constraints.
- If no primary key exists, itβs harder to uniquely identify rows and enforce data integrity.
π§ Quick Recap
| Key Point | Explanation |
|---|---|
| PRIMARY KEY | Uniquely identifies each row, no duplicates or NULLs |
| Single or Composite | Supports one or multiple columns as key |
| Unique & NOT NULL | Enforced automatically |
| One per table | Only one primary key allowed per table |
| Index created | Unique index created for fast data retrieval |
π‘ Always define a PRIMARY KEY to ensure each record is uniquely identifiable and maintain data integrity.
Was this helpful?
Thanks for your feedback!