A primary key is a unique identifier for each record in a database table, ensuring that no two rows have the same value in the specified column(s) and preventing duplicate entries.
A primary key ensures that each row in a table is uniquely identifiable. It must satisfy two conditions:
- Uniqueness โ No two records can have the same primary key value.
- Not NULL โ A primary key cannot be NULL because it is used to identify records.
Primary keys can be single-column keys (one field uniquely identifies a row) or composite keys (a combination of multiple columns uniquely identifies a row).
For example, in an Employees
table, the employee_id
field can be the primary key because each employee must have a unique ID.
Example SQL Query (Defining a Primary Key):
CREATE TABLE Employees (
employee_id INT PRIMARY KEY,
name VARCHAR(100),
department VARCHAR(50),
salary DECIMAL(10,2)
);
This ensures that employee_id
is unique for every row in the Employees
table.
If a composite primary key is required, it can be defined as follows:
CREATE TABLE Enrollments (
student_id INT,
course_id INT,
PRIMARY KEY (student_id, course_id)
);
Here, the combination of student_id
and course_id
uniquely identifies each row in the Enrollments
table.
Leave a Reply