A Primary Key is a fundamental concept in relational database management systems (RDBMS). It is used to uniquely identify each record (or row) in a database table.
What is a Primary Key?
A Primary Key is a column or a set of columns in a table that uniquely identifies each row in that table.
Key Characteristics of a Primary Key:
- Uniqueness: Each value in the primary key column(s) must be unique.
- Not Null: A primary key column cannot contain NULL values.
- Single Per Table: A table can have only one primary key.
- Immutable: The value of a primary key should not change frequently.
- Automatic Indexing: Most database systems automatically create an index on the primary key for faster access.
📋 Example of Primary Key
Consider a table named Students:
| student_id | name | age | class |
|---|---|---|---|
| 101 | Rahul Sharma | 16 | 10-A |
| 102 | Neha Verma | 15 | 9-B |
| 103 | Amit Singh | 17 | 11-C |
In this table:
student_idis the Primary Key.- It uniquely identifies each student in the table.
- No two students can have the same
student_id. student_idcannot be NULL.
SQL Syntax to Define a Primary Key
While creating the table:
CREATE TABLE Students (
student_id INT PRIMARY KEY,
name VARCHAR(100),
age INT,
class VARCHAR(10)
);
Or, define primary key separately:
CREATE TABLE Students (
student_id INT,
name VARCHAR(100),
age INT,
class VARCHAR(10),
PRIMARY KEY (student_id)
);
Composite Primary Key
A Composite Primary Key uses more than one column to uniquely identify a row.
Example:
CREATE TABLE CourseEnrollment (
student_id INT,
course_id INT,
enrollment_date DATE,
PRIMARY KEY (student_id, course_id)
);
In this case, neither student_id nor course_id alone is sufficient to identify a unique row. But together, they do.
Violations of Primary Key Rules
| student_id | name | age | class |
|---|---|---|---|
| 101 | Rahul Sharma | 16 | 10-A |
| 101 | Neha Verma | 15 | 9-B |
- Duplicate student_id: Violates uniqueness.
- If
student_idis NULL: Violates not-null property.
Primary Key vs Unique Key
| Feature | Primary Key | Unique Key |
|---|---|---|
| Uniqueness | Must be unique | Must be unique |
| NULL values | Not allowed | Allowed (one NULL only) |
| Number per table | Only one allowed | Multiple allowed |
| Purpose | Identifies records uniquely | Ensures uniqueness of column |
Summary
- A Primary Key ensures each record in a table is unique and not null.
- It can be a single column or a combination of columns.
- It is crucial for data integrity and relationships in relational databases.
