What is a primary key?
A primary key is a column (or a set of columns) in a database table that uniquely identifies each row in that table.
π Key Characteristics of a Primary Key:
- Uniqueness: Each value must be unique β no two rows can have the same primary key value.
- Not Null: A primary key column cannot contain NULL values.
- One per table: A table can have only one primary key, but it can consist of multiple columns (called a composite key).
Example:
CREATE TABLE students (
student_id INT PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100)
);
Here:
student_id is the primary key.
- Each student must have a unique
student_id.
student_id cannot be NULL.
Composite Primary Key Example:
CREATE TABLE enrollments (
student_id INT,
course_id INT,
PRIMARY KEY (student_id, course_id)
);
Here:
- The combination of
student_id and course_id must be unique.
- This is useful when a single column isnβt enough to uniquely identify a row.
Why Use a Primary Key?
- Ensures data integrity (no duplicate or null values).
- Helps in establishing relationships with other tables (via foreign keys).
- Improves query performance through indexing (most databases automatically index the primary key).
If you want help designing a primary key for a specific use case, I can help with that too!