SQL: Structured Query LanguageSQL FundamentalsConstraints and Data Integrity

What is a UNIQUE constraint?

Question 25 of 30 · Updated

On this page

A UNIQUE constraint is a database rule that prevents conflicting duplicate values in a specified column or combination of columns. For example, a membership system can declare email UNIQUE so that two different member records cannot have the same non-NULL email under the column's comparison rules. The database enforces the constraint when data is inserted or updated, rather than depending only on application validation.

A UNIQUE constraint is a persistent part of a table's schema. It is not a SELECT modifier and does not simply hide duplicate records. Its handling of NULL depends on the database engine and constraint configuration.

1. Why UNIQUE constraints matter#

A database often has more than one identifier or business rule that requires uniqueness. Consider a member directory: the member ID identifies each row, the email is required and must be unique, and an optional badge code must not be assigned to multiple members. Other fields, such as a display name, may legitimately repeat.

AttributeIntended rule
member_idUnique, required row identifier
emailRequired and unique according to the selected comparison rules
badge_codeOptional, but assigned codes must be unique
display nameRepetition permitted

Declare uniqueness only where the business requires it. Making names, cities or ordinary descriptive attributes unique by accident can reject valid data. A UNIQUE constraint on email alone also does not validate email syntax, verify ownership, or guarantee a real person has only one account.

2. Declare a single-column UNIQUE constraint#

Use the following disposable teaching schema. The SQL is compatible with PostgreSQL and SQLite for the explicit, non-NULL integer identifiers used here. The examples that create or change data were tested in isolated SQLite 3.46.1; they were not run against production PostgreSQL.

SQL
CREATE TABLE members ( member_id INTEGER PRIMARY KEY, email TEXT NOT NULL UNIQUE, badge_code TEXT UNIQUE );

Here UNIQUE applies independently to email and badge_code. NOT NULL is a separate rule: it requires an email to be present. Without NOT NULL, ordinary PostgreSQL UNIQUE permits multiple NULL values by default. PRIMARY KEY identifies members; it is not necessary to make email a second primary key.

An equivalent way to declare named constraints on a fresh table is the table-level form below. Do not execute both CREATE TABLE examples under the same name in one database.

SQL
CREATE TABLE members ( member_id INTEGER PRIMARY KEY, email TEXT NOT NULL, badge_code TEXT, CONSTRAINT uq_members_email UNIQUE (email), CONSTRAINT uq_members_badge UNIQUE (badge_code) );

Naming constraints can make migrations, error diagnostics and documentation clearer. The second DDL form is illustrative; the inline form was used in the executed tests.

3. Worked example: valid rows and rejected duplicates#

Start with the inline-constraint definition above in a disposable database, then insert three members:

SQL
INSERT INTO members (member_id, email, badge_code) VALUES (1, 'a@example.test', NULL), (2, 'b@example.test', NULL), (3, 'c@example.test', 'B7');
SQL
SELECT member_id, email, badge_code FROM members ORDER BY member_id;
member_idemailbadge_code
1a@example.testNULL
2b@example.testNULL
3c@example.testB7

All three rows are allowed in the tested SQLite setup and are consistent with ordinary PostgreSQL UNIQUE semantics. The two missing badge codes do not conflict under default NULL handling. The known emails are different and the assigned badge B7 occurs once.

Now consider this attempted insert:

SQL
INSERT INTO members (member_id, email, badge_code) VALUES (4, 'a@example.test', 'B8');

The member_id and badge_code would be new, but the email already belongs to member 1. The UNIQUE rule rejects the insert. In the SQLite test, the error identifies a UNIQUE constraint failure on members.email. PostgreSQL normally reports SQLSTATE 23505 (unique_violation) for this class of error; the exact PostgreSQL error text was not executed here.

Loading diagram…

The diagram is a conceptual validation model, not a guarantee of the order in which a real database checks constraints. It shows why a unique row identifier does not make a conflicting email valid.

An independently attempted insertion of another member with an existing badge code is rejected as well:

SQL
INSERT INTO members (member_id, email, badge_code) VALUES (4, 'd@example.test', 'B7');

Here the email would be unique, but B7 conflicts with member 3. Each UNIQUE constraint must be satisfied.

4. UNIQUE is enforced on updates too#

Uniqueness is not merely an insertion-time rule. An update can make a previously valid row conflict with another row:

SQL
UPDATE members SET email = 'a@example.test' WHERE member_id = 2;

The tested statement fails because member 1 already uses that email. Changing a non-key business attribute does not bypass its uniqueness requirement. A successful write is possible only when it satisfies all applicable constraints at their required check time. Ordinary constraints in these examples are immediate; PostgreSQL also supports some deferrable unique constraints, a more advanced transaction topic.

After the rejected writes, the tested table still contains exactly the original three rows with their original email and badge values. In PostgreSQL, an error inside an explicit transaction normally requires rolling back the transaction or recovering with an appropriate savepoint before executing further statements. Run intentional failure examples independently in disposable databases; do not test them on live application tables.

5. UNIQUE on a combination of columns#

Sometimes uniqueness belongs to a pair of attributes, not either attribute independently. A student may enroll in multiple courses, and a course may have multiple students, but the same student-course enrollment must not be recorded twice.

SQL
CREATE TABLE enrollments ( student_id INTEGER NOT NULL, course_id INTEGER NOT NULL, CONSTRAINT uq_enrollment UNIQUE (student_id, course_id) );

This teaching table uses a composite UNIQUE constraint to illustrate the rule without selecting a primary key. In a production schema, choose a suitable primary key and foreign keys based on the data model; the pair could itself be a candidate for a composite primary key.

SQL
INSERT INTO enrollments (student_id, course_id) VALUES (1, 10), (1, 20), (2, 10);
SQL
SELECT student_id, course_id FROM enrollments ORDER BY student_id, course_id;
student_idcourse_id
110
120
210

Student 1 appears twice and course 10 appears twice. Both are valid because the complete pairs differ. Attempting the following insert fails:

SQL
INSERT INTO enrollments (student_id, course_id) VALUES (1, 10);

The pair (1, 10) already exists. The isolated test confirmed the existing three rows remain. This is different from declaring UNIQUE (student_id) and UNIQUE (course_id) separately: those two separate constraints would prohibit valid repeat enrollment by a student or valid enrollment of two students in a course.

For a multi-tenant application, the same principle can express a rule such as UNIQUE (tenant_id, slug), allowing a slug to be reused across tenants but not repeated within a tenant. The constraint does not itself enforce tenant access isolation; authorization is a separate requirement.

6. What happens when a UNIQUE column contains NULL?#

NULL represents missing or unknown information. Ordinary PostgreSQL UNIQUE treats NULLs as distinct for uniqueness checking by default, allowing multiple NULLs in a nullable single-column unique key. SQLite exhibits the same behavior in the tested badge_code example. This is a constraint-specific rule and should not be confused with ordinary SQL equality or DISTINCT's duplicate-elimination semantics.

Combining UNIQUE with NOT NULL requires each row to contain a nonmissing, nonconflicting value. This attempted insert fails because email is required:

SQL
INSERT INTO members (member_id, email, badge_code) VALUES (4, NULL, 'B8');
SituationOrdinary nullable UNIQUE in PostgreSQLUNIQUE plus NOT NULL
New non-NULL valueAllowed if other rules passAllowed if other rules pass
Duplicate non-NULL valueRejectedRejected
Multiple NULL valuesAllowed by defaultRejected, including first NULL

PostgreSQL 15 and newer also support a UNIQUE NULLS NOT DISTINCT constraint option, which treats NULLs as not distinct for uniqueness enforcement. Other engines have different rules for nullable unique constraints; never assume the default behavior is universal. For example, SQL Server ordinarily permits only one NULL under an unfiltered single-column unique constraint. These are explanatory dialect distinctions, not executed cross-engine tests. Detailed nullable composite keys and alternative NULL policies are reserved for a later lesson.

7. UNIQUE versus PRIMARY KEY and DISTINCT#

PropertyUNIQUE constraintPRIMARY KEY constraintSELECT DISTINCT
PurposePrevent conflicting stored valuesIdentify rows uniquelyEliminate duplicate result rows
ScopeOne column or a combinationOne column or a combinationSelected output expressions
Number per tableMultiple possibleAt most one primary-key constraintNot a table constraint
NULLDepends on definition and engineDisallowed by SQL primary-key semanticsDuplicate NULL-containing outputs may collapse
Future writesEnforces declared ruleEnforces row-identity ruleDoes not enforce future writes

A table can have one chosen primary key and several alternate unique business identifiers. UNIQUE does not automatically turn a column into the primary key. PostgreSQL PRIMARY KEY enforces both uniqueness and non-nullness; SQLite has some legacy primary-key exceptions outside the explicit integer-ID examples used here. The full key-design comparison belongs to the intermediate constraint lesson.

SELECT DISTINCT is entirely different: it changes the rows returned by a query. It cannot prevent two conflicting values from being inserted later. If invalid duplicates must never be committed, express the business rule as an appropriate constraint rather than adding DISTINCT to every read query.

8. Adding a uniqueness rule to an existing table#

In PostgreSQL, a named table constraint can be added using ALTER TABLE. For example, the following is an illustrative migration template for a legacy table that does not already have the same rule:

SQL
ALTER TABLE legacy_members ADD CONSTRAINT uq_legacy_members_email UNIQUE (email);

Before adding it, find existing duplicate known email values. The following is a preflight query template for the same legacy table:

SQL
SELECT email, COUNT(*) AS row_count FROM legacy_members WHERE email IS NOT NULL GROUP BY email HAVING COUNT(*) > 1 ORDER BY email;

Do not delete duplicates blindly. Investigate which records represent the same entity, whether the uniqueness rule is correct, and how related data should be preserved. The preflight query reflects ordinary NULL-distinct uniqueness on a scalar email column; it does not validate every possible collation, expression or NULL policy. Preflight inspection alone does not prevent concurrent new duplicates. The actual database constraint must validate and enforce the rule.

Adding constraints to a populated table can require scanning data, building an index and acquiring locks. Plan the migration around workload size and availability requirements. These ALTER and preflight examples were not executed in the isolated tests. The advanced online-migration procedure is outside this basic lesson.

9. Constraints, indexes and concurrency#

In PostgreSQL, declaring an ordinary UNIQUE constraint automatically creates a unique B-tree index to enforce it. That index may also support suitable read queries. A constraint expresses a data rule; an index is a database access structure. Ordinary nonunique indexes do not prohibit duplicate values. A unique index can enforce uniqueness, but not every useful unique-index definition is expressible as an ordinary UNIQUE table constraint.

Supabase's Managing Indexes documentation explains B-tree indexes, the optimizer's choice of access path and the costs of maintaining indexes. Avoid creating a redundant second index on exactly the same key merely because you have already declared it UNIQUE. Index design, partial unique indexes and specialized uniqueness policies are separate curriculum topics. No PostgreSQL index benchmark was performed here.

Application-side checks such as SELECTing by email before INSERT can improve user feedback but cannot guarantee uniqueness under concurrent writes. Two requests may both observe that no matching email exists before either writes. Keep the database constraint as the final integrity rule and handle the specific database error at the application boundary. Depending on the business requirement, return a conflict response, retry an independently generated identifier, or use a carefully designed idempotent write. Never silently discard or overwrite another member's information merely to suppress a constraint error.

Also define what counts as equal. Text comparisons can depend on data type, collation and normalization. For a case-insensitive business identifier, a plain UNIQUE constraint on ordinary case-sensitive text may not be sufficient. Choose a consistent, documented normalization and enforcement strategy. Do not assume case-folding arbitrary personal data is always appropriate.

10. Common mistakes#

MistakeCorrect approach
Assuming a UNIQUE column must be the primary keyUse additional unique identifiers where the business needs them
Assuming UNIQUE automatically forbids NULLAdd NOT NULL if missing values are forbidden
Declaring separate UNIQUE constraints instead of a pairUse a composite UNIQUE constraint for a pair-level rule
Checking duplicates only with application codeEnforce the rule in the database as well
Using DISTINCT to prevent duplicate writesDeclare an appropriate schema constraint
Adding a constraint without inspecting existing dataAudit conflicts and plan a migration
Ignoring collation and normalizationDefine the actual business equality rule

11. Interview-ready answer#

A UNIQUE constraint ensures that nonconflicting values are maintained in a column or a combination of columns. For example, email TEXT NOT NULL UNIQUE prevents missing or duplicate emails while a separate primary key identifies each member. The rule applies to inserts and updates. Composite UNIQUE enforces uniqueness of the complete combination, not each component individually. A table may have multiple UNIQUE constraints, and NULL handling varies by engine; ordinary PostgreSQL UNIQUE allows multiple NULLs by default. Unlike DISTINCT, UNIQUE protects stored data and future writes.

Quick checks: Can a table have several UNIQUE constraints? Yes. Can two members have the same non-NULL email under the example rule? No. Can multiple missing badge codes be allowed? Yes under ordinary PostgreSQL and tested SQLite semantics. Can an existing row be updated into a duplicate? No when the applicable immediate unique constraint would be violated. Does UNIQUE(student_id, course_id) prevent a student from joining multiple courses? No; only repeated complete pairs conflict.

12. Validation and references#

Nine assertions passed in an isolated SQLite 3.46.1 in-memory database: valid member rows with repeated NULL badges; duplicate email rejection; duplicate badge rejection; required-email NULL rejection; conflicting update rejection; preservation of member rows after failures; valid composite rows; duplicate pair rejection; and preservation of composite rows after failure. The test explicitly inspected resulting rows and caught integrity errors. No educational DDL, attempted constraint violations or business-data writes were performed in production PostgreSQL. PostgreSQL-specific DDL, error codes, NULLS NOT DISTINCT, other-engine behavior and migration templates are explanatory and were not independently executed. The Mermaid diagram was structurally checked with exact triple-backtick mermaid fencing; full parser and public-page rendering were unavailable.

Official Supabase Tables and data and Managing Indexes documentation was consulted for primary-key identity and index behavior. PostgreSQL and SQLite links below are authoritative documentation destinations but were not live fetched under the established offline research exception.

Related questions

Explore other topics:Forward Deployed EngineeringPythonAI System DesignMachine Learning