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
andcourse_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!
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.