Both Prevent Duplicates. So What's the Difference?

Imagine you are working on an employee database.
You have three employees in your table:
| employee_id | employee_name | |
|---|---|---|
| 101 | Rahul | rahul@gmail.com |
| 102 | Priya | priya@gmail.com |
| 103 | Amit | amit@gmail.com |
Your manager gives you a simple task:
- Every employee must have a different employee ID.
- Two employees should not have the same email address.
You create the table using two different constraints:
CREATE TABLE employees (
employee_id NUMBER PRIMARY KEY,
employee_name VARCHAR2(50),
email VARCHAR2(100) UNIQUE
);
Now, you try to add a new employee:
INSERT INTO employees
VALUES (104, 'Sneha', 'rahul@gmail.com');
Look carefully at the INSERT statement.
The employee ID is new, but the email address already belongs to Rahul.
What will happen?
A. The record will be inserted because employee_id 104 is new.
B. The INSERT will fail because the email address already exists.
C. Oracle will automatically change the email address.
D. Oracle will reject the table because PRIMARY KEY and UNIQUE cannot be used together.
Your turn: Which option is correct – A, B, C or D?
Here is something worth remembering:
Both PRIMARY KEY and UNIQUE prevent duplicate values, but they are not the same.
- PRIMARY KEY identifies a record and does not allow NULL.
- UNIQUE prevents duplicate values but allows NULL.
- A table can have only one PRIMARY KEY.
- A table can have multiple UNIQUE constraints.
For example, employee_id is a good choice for PRIMARY KEY, while email is a good choice for UNIQUE.
One small SQL concept, but an important one when designing real database tables.
Have you ever used both PRIMARY KEY and UNIQUE in the same table?
Top comments (0)