Sub topic 6
Preventing duplicates with UNIQUE
A UNIQUE constraint tells Oracle that no two rows may hold the same value, or the same combination of values, in one or more columns. This chapter assumes you can write a basic CREATE TABLE statement, know what a primary key is, and have the departments and employees tables from earlier chapters available. It covers declaring UNIQUE constraints, how they treat NULL, the index Oracle builds for them, case-insensitive uniqueness, and the errors you will see.
What a UNIQUE constraint guarantees
A UNIQUE constraint rejects any INSERT or UPDATE that would leave two rows with equal values in the constrained columns. It differs from a primary key in three ways:
| Feature | PRIMARY KEY | UNIQUE |
|---|---|---|
| Per table | At most one | As many as you need |
| Allows NULL | No (implies NOT NULL) | Yes, with rules described below |
| Typical use | The row's identity | Alternate identifiers such as email or a business code |
Use UNIQUE for any natural identifier that must not repeat but is not the table's main key. An email address, a national ID, or a department name are common examples.
Declaring UNIQUE inline and out of line
You can declare the constraint in two places. An inline declaration sits on the column definition and can only cover that one column. An out-of-line declaration sits after the column list and can cover one or several columns.
The departments table from the plan uses the out-of-line form with an explicit name:
CREATE TABLE departments (
department_id NUMBER GENERATED ALWAYS AS IDENTITY,
department_name VARCHAR2(100) NOT NULL,
CONSTRAINT departments_pk PRIMARY KEY (department_id),
CONSTRAINT departments_name_uk UNIQUE (department_name)
);The inline form, with the same explicit name, would look like this:
CREATE TABLE locations (
location_id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
location_code VARCHAR2(10) CONSTRAINT locations_code_uk UNIQUE
);If you leave out CONSTRAINT name, Oracle invents a name such as SYS_C0012345. Error messages then point at a name that tells you nothing. Name every UNIQUE constraint. A common convention is <table>_<column>_uk.
Composite UNIQUE constraints
A composite constraint treats the combination of columns as the unit of uniqueness. Individual columns may repeat as long as the whole combination does not.
CREATE TABLE project_assignments (
assignment_id NUMBER GENERATED ALWAYS AS IDENTITY,
employee_id NUMBER NOT NULL,
project_code VARCHAR2(20) NOT NULL,
badge_no VARCHAR2(20) CONSTRAINT assignments_badge_uk UNIQUE,
CONSTRAINT assignments_pk PRIMARY KEY (assignment_id),
CONSTRAINT assignments_emp_proj_uk UNIQUE (employee_id, project_code)
);Here an employee can work on many projects and a project can have many employees. The same employee cannot be assigned to the same project twice. A composite key can include up to 32 columns, but in practice two or three is typical.
How UNIQUE treats NULL
This is the part that most often surprises people. Oracle's rules differ for single-column and composite constraints.
- In a single-column UNIQUE constraint, any number of rows may contain
NULL. Oracle does not consider two NULLs equal. - In a composite constraint, a row whose columns are all
NULLnever conflicts with any other row. - In a composite constraint, a row with some columns
NULLand some not is compared on the non-null columns. Two such rows with the same non-null values andNULLin the same positions are duplicates.
A small experiment shows all three rules:
CREATE TABLE unique_demo (
a NUMBER,
b NUMBER,
CONSTRAINT unique_demo_uk UNIQUE (a, b)
);
INSERT INTO unique_demo VALUES (1, 1); -- succeeds
INSERT INTO unique_demo VALUES (1, NULL); -- succeeds
INSERT INTO unique_demo VALUES (1, NULL); -- fails with ORA-00001
INSERT INTO unique_demo VALUES (NULL, NULL); -- succeeds
INSERT INTO unique_demo VALUES (NULL, NULL); -- succeeds againThe third insert fails because (1, NULL) already exists. The two (NULL, NULL) rows coexist because all-null keys are not indexed.
The index behind the constraint
To check uniqueness quickly, Oracle needs an index. When you create a UNIQUE constraint, Oracle builds a unique index on the columns, unless a usable index already exists. By default the index takes the constraint's name, which is another reason to name constraints yourself.
The constraint and the index are linked. If Oracle created the index for the constraint, dropping the constraint also drops the index. You can control where the index lives, or reuse an existing one, with USING INDEX:
CREATE INDEX employees_email_ix ON employees (email);
ALTER TABLE employees
ADD CONSTRAINT employees_email_uk2 UNIQUE (email)
USING INDEX employees_email_ix;If you drop a constraint that reuses a pre-existing index, the index stays. This matters for storage tuning and for avoiding a slow index rebuild when you re-add the constraint.
A UNIQUE constraint declared DEFERRABLE uses a non-unique index instead. Oracle must let duplicates exist temporarily until the check runs at commit.
Where the check happens
When the check fails, the whole statement is rolled back. In a multi-row INSERT ... SELECT, one duplicate stops every row of that statement from being inserted. The rest of your transaction is untouched.
Reading the ORA-00001 error
A violation produces a message like this:
ORA-00001: unique constraint (HR.DEPARTMENTS_NAME_UK) violatedThe text names the owner and the constraint. With a good constraint name, you immediately know which rule failed. Application code can catch ORA-00001 and show a friendly message such as "That department already exists". The same error also appears for primary key violations, so check the constraint name when you need to tell them apart.
When two sessions insert the same key at the same time, the second session waits until the first commits or rolls back. If the first commits, the second gets ORA-00001. If the first rolls back, the second proceeds. This waiting is normal and is how Oracle serializes duplicate checks.
Case-insensitive and conditional uniqueness
A plain UNIQUE constraint compares values exactly. 'Sales' and 'SALES' are different, and so are '[email protected]' and '[email protected]'. If your business rule ignores case, a normal constraint will not enforce it.
The usual fix is a unique function-based index:
CREATE UNIQUE INDEX employees_email_ci_uk
ON employees (UPPER(email));This rejects [email protected] if [email protected] already exists. It is a unique index, not a constraint, so it does not appear in user_constraints, and a foreign key cannot reference it.
You can use the same technique for conditional uniqueness. Suppose an email must be unique only among active employees. Rows that evaluate to NULL are not indexed, so this index ignores inactive rows:
CREATE UNIQUE INDEX employees_active_email_uk
ON employees (CASE WHEN status = 'ACTIVE' THEN email END);Inactive employees produce NULL keys and can share an email with anyone. Active employees must have distinct emails.
Foreign keys can reference UNIQUE columns
A foreign key may point at a primary key or at a UNIQUE constraint on the parent table. The parent columns must be covered by a real constraint, not just a unique index. For example, a table of payroll records could reference employees (email) because employees_email_uk is a constraint. Referencing the primary key is still the better habit, because a key that never changes is safer to reference than a business value that someone might need to edit.
Managing UNIQUE constraints after creation
You add, disable, enable and drop a UNIQUE constraint with ALTER TABLE, using the same form as other constraints:
ALTER TABLE departments
ADD CONSTRAINT departments_code_uk UNIQUE (department_name, department_id);
ALTER TABLE departments DISABLE CONSTRAINT departments_code_uk;
ALTER TABLE departments ENABLE CONSTRAINT departments_code_uk;
ALTER TABLE departments DROP CONSTRAINT departments_code_uk;Adding a constraint to a table that already has data fails with ORA-02299 if duplicates exist. Find them first:
SELECT email, COUNT(*) AS copies
FROM employees
GROUP BY email
HAVING COUNT(*) > 1;Disabling a UNIQUE constraint that has a unique index drops that index. Re-enabling it rebuilds the index, which can take time on a large table. If a foreign key references the constraint, you cannot drop it unless you add CASCADE, which also drops the dependent foreign key.
Inspecting UNIQUE constraints
Constraint type U marks a UNIQUE constraint in the data dictionary. This query lists each one with its columns in order:
SELECT c.constraint_name, c.status, c.index_name, cc.column_name, cc.position
FROM user_constraints c
JOIN user_cons_columns cc ON cc.constraint_name = c.constraint_name
WHERE c.table_name = 'PROJECT_ASSIGNMENTS'
AND c.constraint_type = 'U'
ORDER BY c.constraint_name, cc.position;For assignments_emp_proj_uk you get two rows, with EMPLOYEE_ID at position 1 and PROJECT_CODE at position 2.
Common mistakes
- Relying on UNIQUE alone for required values. Add NOT NULL.
- Leaving the constraint name to Oracle, which makes errors and later
ALTER TABLEcommands harder to read. - Expecting case-insensitive comparison. Use a function-based unique index.
- Creating a UNIQUE constraint on the same columns as the primary key. It adds a second index and no extra protection.
- Forgetting that a composite key allows repeated rows when all columns are NULL.
Exercise
A table badges has the constraint badges_uk UNIQUE (site, badge_no). It already contains the rows ('NYC', 101) and ('NYC', NULL). Which of these inserts succeed: (1) ('LON', 101), (2) ('NYC', NULL), (3) (NULL, NULL), (4) ('NYC', 101)?
Show answer
Inserts 1 and 3 succeed. Insert 1 differs in site, so the combination is new. Insert 3 has all constrained columns NULL, so it never conflicts. Insert 2 fails with ORA-00001 because ('NYC', NULL) already exists and the non-null part matches. Insert 4 fails because it repeats ('NYC', 101).
Exercise
Your rule says email addresses must be unique ignoring case, and a foreign key from another table must reference them. Can a unique index on UPPER(email) alone satisfy both needs?
Show answer
No. The function-based unique index enforces case-insensitive uniqueness, but a foreign key needs a primary key or UNIQUE constraint on the referenced columns, and the index is neither. The index cannot be referenced. Reference the primary key instead, or store a normalized (for example upper-case) email in a separate column with its own UNIQUE constraint.