Composite, Partial & Expression UNIQUE in SQL
Scoped uniqueness: live rows, lowered emails, pair keys
PRIMARY KEY is singular and never NULL; UNIQUE repeats across columns and (in PG/standard) allows multiple NULLs. Composite keys identify by combination (order_id, line_no; tenant_id, email). Partial unique (WHERE deleted_at IS NULL) scopes to live rows β the soft-delete answer. Expression unique (LOWER(email)) normalizes before comparing. Deferrable (INITIALLY DEFERRED) checks at COMMIT for cyclic inserts.
Composite identifies pairs
PK (order_id, line_no); UNIQUE (tenant_id, email) β combination carries identity.
Partial scopes liveness
WHERE deleted_at IS NULL β archived dupes allowed, live enforced.
Expression normalizes
LOWER(email) β case-insensitive without app discipline.
Defer cycles to COMMIT
DEFERRABLE INITIALLY DEFERRED β AβB inserts in one txn; sparingly (late errors).
1CREATE UNIQUE INDEX ux_active_email ON users (LOWER(email)) WHERE deleted_at IS NULL;
| tool | job |
|---|---|
| partial | live rows only |
| expression | case-insensitive |
Ada@x.com and ADA@x.com conflict (lowered); archived duplicates (deleted_at set) do not. Triggers lose to this for clarity and concurrency β the index is the validator.
Enrollment junction
Two FKs + composite PK + attribute.
1CREATE TABLE enrollments (2 student_id BIGINT REFERENCES students(id) ON DELETE CASCADE,3 course_id BIGINT REFERENCES courses(id) ON DELETE CASCADE,4 enrolled_at DATE NOT NULL DEFAULT CURRENT_DATE,5 PRIMARY KEY (student_id, course_id)6);
| element | role |
|---|---|
| PK | (student_id, course_id) |
| attrs | enrolled_at rides along |
Live-only lowered email
Conditional + normalized in one index.
1CREATE UNIQUE INDEX ux_active_email ON users (LOWER(email)) WHERE deleted_at IS NULL;
| case | verdict |
|---|---|
| live Ada vs ADA | conflict |
| archived dupes | allowed |
Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.