Sub topic 8
Preventing duplicates with UNIQUE
A UNIQUE constraint tells the database that no two rows may hold the same value in a column, or the same combination of values in a set of columns. This chapter covers how UNIQUE works, how it treats NULL, how it differs from PRIMARY KEY, and the errors you will see when it rejects a statement.
This chapter assumes you can write a basic CREATE TABLE statement, know what NOT NULL and PRIMARY KEY do, and can run INSERT and UPDATE statements.
What UNIQUE guarantees
Some columns are not the primary key but still must not repeat. An email address on a customers table is a typical case. The surrogate key customer_id identifies the row, while the email identifies the person. Without a constraint, two sign-ups could store the same address, and application code that checks first and inserts second can still race with another session.
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
full_name VARCHAR(100) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);The database checks the rule on every INSERT and on every UPDATE that changes the column. It also checks the rows written by multiple sessions at the same time, which is something an application-level "look before you insert" check cannot guarantee.
INSERT INTO customers (email, full_name)
VALUES ('[email protected]', 'Ada Lovelace');
INSERT INTO customers (email, full_name)
VALUES ('[email protected]', 'Another Ada');The second statement fails and changes nothing. In PostgreSQL the message looks like this:
ERROR: duplicate key value violates unique constraint "customers_email_key"
DETAIL: Key (email)=([email protected]) already exists.The error names the constraint. Here PostgreSQL generated the name customers_email_key because none was given. Other systems use other wording and generated names, such as MySQL's Duplicate entry '[email protected]' for key 'customers.email'. The next section's naming advice makes these messages easier to read.
UNIQUE compared with PRIMARY KEY
Both constraints prevent duplicates, but they are not the same.
| Property | PRIMARY KEY | UNIQUE |
|---|---|---|
| Allowed per table | One | Many |
| NULL allowed | No, the column becomes NOT NULL | Yes, unless you add NOT NULL (SQL Server allows one NULL) |
| Intended role | The main identifier of the row | An alternative identifier, called a candidate key |
| Typical target of a foreign key | Yes | Yes, allowed by the standard |
A table can have several unique constraints. A users table might use user_id as the primary key and also require unique email and unique username.
Because a foreign key may reference any unique column, not only the primary key, UNIQUE is also what makes a column a valid reference target. If you try to reference a column that has no unique or primary key constraint, the database rejects the foreign key definition.
Composite UNIQUE constraints
A composite constraint covers several columns together. The rule applies to the combination, not to each column on its own.
Suppose a store allows one review per customer per product:
CREATE TABLE product_reviews (
review_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
rating INTEGER NOT NULL CHECK (rating BETWEEN 1 AND 5),
CONSTRAINT uq_reviews_customer_product UNIQUE (customer_id, product_id)
);These rows are all allowed:
| customer_id | product_id |
|---|---|
| 1 | 10 |
| 1 | 11 |
| 2 | 10 |
A second row with (1, 10) is rejected. Customer 1 may review many products, and product 10 may have many reviewers, but each pair appears once.
A composite constraint must be written at the table level, after the column list, because a column-level constraint can only mention its own column. Column-level and table-level syntax get a full chapter of their own, so here it is enough to remember the rule: more than one column means a table-level clause.
How UNIQUE treats NULL
NULL means "unknown", so the SQL standard says one NULL is not equal to another. A unique check only rejects values it can prove are equal. As a result, most systems allow many rows with NULL in a unique column.
CREATE TABLE employees (
employee_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL,
badge_number VARCHAR(20) UNIQUE
);
INSERT INTO employees (name, badge_number) VALUES ('Grace', NULL);
INSERT INTO employees (name, badge_number) VALUES ('Alan', NULL);Both inserts succeed in PostgreSQL, MySQL, SQLite, and Oracle for a single-column constraint. This is useful when the value is optional but must not repeat once it is present.
Systems differ on this point:
- SQL Server treats NULLs as equal in a unique constraint, so the table above would allow only one row with a NULL badge number. A common workaround is a unique index with a filter,
WHERE badge_number IS NOT NULL. - PostgreSQL 15 and later accept
UNIQUE NULLS NOT DISTINCTto make NULLs count as equal. The default remainsNULLS DISTINCT. - Oracle allows many NULLs in a single-column unique constraint. For a composite constraint, rows where every column is NULL are exempt, but a row with at least one non-NULL column is checked.
For a composite constraint on most systems, a row with a NULL in any of the columns usually escapes the check. In UNIQUE (customer_id, product_id), the rows (1, NULL) and (1, NULL) can both exist in PostgreSQL. If you do not want that, add NOT NULL to the columns, as the product_reviews example does.
Case, spaces, and what counts as equal
The constraint compares values using the column's comparison rules. Those rules depend on the database and its collation.
- PostgreSQL compares
VARCHARvalues case-sensitively by default, so[email protected]and[email protected]are different values. - MySQL's default collations are case-insensitive, so those same two values collide.
- Trailing spaces can matter in some systems and be ignored in others, particularly with fixed-length
CHAR.
If you want emails treated as the same regardless of case on a case-sensitive system, store them in a normalized form, such as lower case, and enforce uniqueness on that. PostgreSQL also supports a unique index on an expression, such as CREATE UNIQUE INDEX ux_customers_email_lower ON customers (LOWER(email)).
Naming and changing unique constraints
Unnamed constraints get generated names, which differ between systems and make errors harder to read and constraints harder to drop. Name the constraint with CONSTRAINT:
CREATE TABLE accounts (
account_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
username VARCHAR(50) NOT NULL,
CONSTRAINT uq_accounts_username UNIQUE (username)
);A violation now reports uq_accounts_username, which tells you the table and rule at a glance.
To change a rule on an existing table, use ALTER TABLE:
ALTER TABLE customers
ADD CONSTRAINT uq_customers_email UNIQUE (email);Adding the constraint fails if the table already contains duplicates, so you must find and fix them first. This query lists the offending values:
SELECT email, COUNT(*) AS copies
FROM customers
GROUP BY email
HAVING COUNT(*) > 1;To remove a constraint in PostgreSQL, SQL Server, and Oracle, use ALTER TABLE customers DROP CONSTRAINT uq_customers_email;. MySQL uses ALTER TABLE customers DROP INDEX uq_customers_email; for unique constraints.
Unique constraints and indexes
Checking uniqueness quickly requires an index, so the database builds one behind the scenes for each unique constraint. In PostgreSQL, MySQL, SQL Server, and Oracle, a unique constraint is backed by a unique index. This has practical effects:
- Lookups such as
WHERE email = '[email protected]'use that index and are fast without further work. - Each constraint adds storage and slightly slows
INSERTandUPDATE. - In a composite constraint, column order matters for lookups. An index on
(customer_id, product_id)serves searches oncustomer_idalone but generally not onproduct_idalone.
A unique index and a unique constraint enforce the same rule. The constraint is the better choice for a rule that belongs to the table's definition, because it is visible as a constraint in the catalog and can be referenced by foreign keys. A unique index is needed when you want features constraints lack, such as expressions or filters.
Failure modes to expect
- Updates can collide.
UPDATE customers SET email = '[email protected]' WHERE customer_id = 2;fails if another row holds that value. - Concurrent inserts. Two sessions inserting the same value at the same time: one succeeds and the other waits for it, then fails with a duplicate error once the first commits. Your application should be ready to catch that error and respond, rather than assuming a prior
SELECTmade the insert safe. - Multi-row statements. If one row in a multi-row
INSERTviolates the constraint, the whole statement is rejected, not only that row. - Upserts. To insert a row or update the existing one, use the dialect's syntax:
INSERT ... ON CONFLICT (email) DO NOTHINGin PostgreSQL and SQLite, orON DUPLICATE KEY UPDATEin MySQL. Both depend on a unique constraint to define what a conflict is.
Visualizing the check
Exercises
Exercise
A table has UNIQUE (customer_id, product_id) and contains the row (1, 10). Which of these inserts are rejected in PostgreSQL: (1, 11), (2, 10), (1, 10), (1, NULL) when the row (1, NULL) already exists? Both columns allow NULL.
Show answer
Only (1, 10) is rejected, because the exact pair already exists. (1, 11) and (2, 10) are different pairs. The second (1, NULL) is accepted because PostgreSQL treats NULL as not equal to NULL by default, so the combination cannot be proven a duplicate. Declaring both columns NOT NULL would close that gap.
Exercise
You run ALTER TABLE customers ADD CONSTRAINT uq_customers_email UNIQUE (email); and it fails. What is the most likely cause, and how do you find the problem rows?
Show answer
The table already holds duplicate email values. Find them with SELECT email, COUNT(*) FROM customers GROUP BY email HAVING COUNT(*) > 1;, then merge, correct, or delete the duplicates and run the ALTER again.