computer science

What is the difference between PRIMARY KEY and UNIQUE KEY in SQL?

SPSuresh Pillai · 9 Asked 14d ago 333 views 1 answer

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

RVRohit Verma ✓ Accepted · 14d ago ▲ 7

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.

Log in to post your own answer or join the discussion.

Discussion (0)

No comments yet — start the discussion.

← Back to all questions