What is the difference between PRIMARY KEY and UNIQUE KEY in SQL?
Both seem to prevent duplicate values. My teacher said a table can have only one primary key but multiple unique keys. I am confused about why we need both.
1 Answer
PRIMARY KEY: uniquely identifies each row, cannot be NULL, only ONE per table. UNIQUE KEY: ensures all values in the column are different, but CAN have NULL values (in most databases), and a table can have MULTIPLE unique keys. Example: Student table with rollno as PRIMARY KEY (each student has one roll number, never null). email column can be UNIQUE KEY (no two students share an email, but a student might not provide email, so NULL is allowed). The primary key is the main identifier; unique keys are additional business constraints.
No comments yet — start the discussion.