Fact-checked by Grok 2 weeks ago

Unique key

A unique key, also known as a , is a database rule that enforces on the values within one or more columns of a table, preventing duplicate entries while typically permitting values in those columns. In management systems (RDBMS) such as SQL Server, , PostgreSQL, and DB2, unique keys maintain by ensuring that no two rows share the same non-null value in the specified column or combination of columns. Unique keys differ from primary keys in that they allow null values—often only one null per column, depending on the database system—and a table can have multiple unique keys, whereas it typically has only one primary key. They can be defined on a single column for simple , such as ensuring addresses in a are distinct, or on multiple columns to form a composite key, like guaranteeing a unique combination of first name, last name, and birthdate. Implementation occurs during creation or alteration using SQL statements like CREATE TABLE with UNIQUE clauses or ALTER TABLE ADD [CONSTRAINT](/page/Constraint), and violations trigger errors to block invalid inserts or updates. In broader contexts, such as , unique keys extend this concept to environments by enforcing uniqueness within logical partitions, supporting scalable data models while preserving integrity across distributed systems. Unique keys play a critical role in by supporting indirectly—through foreign keys referencing them—and optimizing query performance via underlying indexes automatically created by most RDBMS.

Introduction

Definition

A unique key is a database constraint in relational databases that enforces uniqueness across one or more columns in a table, ensuring that no two rows contain identical values in those columns. This mechanism prevents duplicate entries while allowing the constrained columns to accept NULL values, with multiple NULLs permitted since NULL is treated as distinct from other values and from itself in standard SQL semantics. Unlike primary keys, which prohibit NULLs entirely, unique keys provide a flexible way to maintain distinctness without mandating non-nullability. Unique keys contribute to by guaranteeing the uniqueness of non-primary identifiers, such as addresses or usernames in a users table, where duplicates could otherwise lead to inconsistencies in data referencing or application logic. For instance, enforcing a unique key on an column ensures that each record has a distinct value (excluding NULLs), supporting reliable lookups and preventing errors in authentication systems. The concept of unique keys originated in the early models proposed by E.F. Codd in his 1970 paper, where they align with candidate keys—minimal sets of attributes that uniquely identify tuples and from which a is selected. These ideas were formalized in the SQL language through the ANSI SQL-86 standard, which introduced the UNIQUE constraint as part of its integrity mechanisms.

Role in Data Integrity

Unique keys contribute to data integrity within relational databases by ensuring that no two rows contain identical values in the specified column or set of columns, thereby preventing the insertion of duplicate records that could lead to data inconsistencies, such as multiple entries representing the same real-world . This mechanism upholds the uniqueness of data attributes, allowing databases to maintain accurate representations of entities without the risks associated with redundant or conflicting information. By providing reliable unique identifiers, unique keys indirectly support in database relationships, as foreign keys in other tables can reference these constraints to establish valid links between data sets. Additionally, they contribute to reducing and mitigating update or delete anomalies, where changes to duplicated values might otherwise require modifications across multiple locations, potentially leading to errors or inconsistencies. Unique keys are particularly suited to business rules that demand in non-mandatory fields, such as secondary phone numbers or addresses, where values are permissible but duplicates among non-null entries must be avoided. This flexibility makes them ideal for scenarios like customer contact management, where optional yet unique attributes enhance reliability without enforcing completeness on every record. In , the ability to apply multiple unique constraints to a single table enables the creation of flexible schemas for complex entities, accommodating various business requirements while centralizing rules in the database structure for easier maintenance and enforcement. This approach promotes scalable and robust data models that adapt to evolving needs without compromising overall .

Core Concepts in Relational Databases

SQL Specification

The unique key, formally known as a UNIQUE constraint in the SQL standard, is defined in ANSI SQL-92 (ISO/IEC 9075:1992) as a constraint that ensures all non-NULL values in a specified column or set of columns are distinct across all rows in a table. This constraint applies to either a single column or multiple columns forming a composite unique key, enforcing data uniqueness at the table level without restricting the constraint to subsets of rows or specific conditions beyond non-duplication. Subsequent standards, including SQL:2016 (ISO/IEC 9075-1:2016), maintain this core definition while incorporating refinements to SQL's foundational integrity mechanisms, such as options for NULL handling in unique constraints (NULLS DISTINCT or NULLS NOT DISTINCT), ensuring compatibility and evolution in relational database management. To declare a UNIQUE constraint, the SQL standard requires the use of the clause within a CREATE TABLE , either inline with a column definition (e.g., column_name datatype UNIQUE) or as a table-level (e.g., CONSTRAINT constraint_name UNIQUE (column_name)). Similarly, the ALTER TABLE supports adding a UNIQUE constraint post-table creation via ADD UNIQUE (column_name) or ADD CONSTRAINT constraint_name UNIQUE (column_name). While the standard does not mandate the automatic creation of an , most compliant implementations generate one to enforce the constraint efficiently, as uniqueness verification relies on rapid duplicate detection across the table. The scope of a is confined to the entire , with enforced at the individual row level during insert, , or delete operations that affect the constrained columns. values are explicitly ignored in checks, meaning multiple rows may contain in the constrained column(s) without violating the constraint, as is not considered equal to another or to any non- value. This treatment aligns with SQL's , where represents an unknown value and does not participate in comparisons for enforcement. SQL:1999 (ISO/IEC 9075-2:1999) enhanced UNIQUE constraints by introducing support for deferrable attributes, allowing the to be specified as DEFERRABLE or NOT DEFERRABLE. A DEFERRABLE permits temporary violations during a , with enforcement deferred until the commits (e.g., via INITIALLY DEFERRED or SET CONSTRAINTS), providing greater flexibility for complex data manipulations without immediate failure. This evolution from SQL-92's immediate enforcement model was carried forward and refined in later standards like SQL:2016, emphasizing transactional integrity while accommodating practical database operations.

Properties and Constraints

A unique key enforces across the values in one or more specified columns within a single table, ensuring that no two rows share the same non- combination of values in those columns. This property aligns with the , which permits multiple values per , as is not considered equal to any value, including another . Unique keys can be composite, involving multiple columns, where is evaluated based on the combined values of all included columns. In SQL's , NULL represents an unknown value, and comparisons involving NULL yield rather than TRUE or FALSE; thus, NULL ≠ NULL, allowing multiple rows to contain NULL in the constrained columns without violating the rule. Per the SQL standard, this handling allows multiple NULL values, though some implementations like SQL Server allow only one. It is commonly adopted in systems like and to support partial data scenarios. Database management systems enforce unique keys by rejecting INSERT or UPDATE operations that would introduce duplicate non-NULL values in the constrained columns, typically raising a constraint violation error. This enforcement is immediate and relies on an underlying index structure, such as a index, to efficiently check for duplicates during data modifications. Unique keys have inherent limitations: they apply only within a single and cannot enforce across multiple tables, requiring separate mechanisms like foreign keys for inter-table relationships. Additionally, unlike primary keys in some database systems, unique keys are not inherently clustered, meaning they do not automatically organize the 's physical storage order based on the key values.

Comparisons with Other Keys

Versus Primary Key

A primary key is a specialized form of unique key that enforces both uniqueness and non-nullability on one or more columns, serving as the primary identifier for rows in a , while a unique key enforces only uniqueness and permits null values (with some DBMS variations allowing multiple nulls). Unlike unique keys, which can be defined on multiple columns or sets within the same , a primary key is restricted to exactly one per to maintain a single, authoritative reference point for entity identification. Selection of a typically prioritizes a stable, efficient identifier such as an auto-incrementing column, which facilitates joins and queries across tables, whereas unique keys are applied to secondary attributes that must remain distinct but do not serve as the core row locator, such as an ISBN in a books table. This distinction ensures that primary keys support as targets for foreign keys, a role that unique keys can also fulfill. In terms of implementation implications, primary keys often default to a clustered in many management systems (DBMS), physically ordering the table for optimized queries and efficiency, while keys are usually implemented as non-clustered indexes, which maintain separate data structures for lookups without altering the table's physical order. This indexing behavior enhances primary keys' performance in join operations but may impose additional overhead for keys on large datasets.
AspectPrimary KeyUnique Key
NULL AllowanceNot allowed; all values must be non-null.Allowed (multiple NULLs in most DBMS, per SQL standard).
Multiplicity per TableOnly one allowed.Multiple allowed.
Default IndexingOften clustered by default (e.g., in SQL Server, MySQL ).Typically non-clustered.
Integrity RoleEnforces entity integrity as the main row identifier; target for foreign keys.Enforces attribute-level uniqueness; can be a target for foreign keys.

Versus Foreign Key

A unique key constraint ensures that the values in one or more columns within a single are distinct, thereby preventing duplicate entries and maintaining uniqueness at the level. In contrast, a constraint establishes and enforces across multiple tables by requiring that values in a column (or set of columns) match an existing or unique key value in a referenced . This distinction is fundamental: unique keys operate internally to a to avoid redundancy in source , such as ensuring no two employees share the same , while s manage inter-table relationships, for instance, by validating that an order's product identifier corresponds to an actual entry in the products . Although foreign keys can reference either a primary key or a in the parent —allowing flexibility in scenarios where a non-primary column needs to serve as a reference point—unique keys themselves do not inherently point to or validate against other tables. For example, in a , a foreign key in an orders might link to a unique key on the product_code column in the products , ensuring that only valid, unique product codes are used without duplicating product data. This overlap enables unique keys to support relationships but underscores their primary role in intra-table enforcement rather than cross-table validation. A common pitfall arises from conflating the two: applying a where a is needed fails to check , potentially resulting in orphaned records that reference non-existent in related tables. Conversely, using a without ensuring the referenced column has a unique or constraint can lead to inconsistencies, as foreign keys require the target to enforce uniqueness to prevent multiple matches. Proper application of both constraints together strengthens overall by combining internal uniqueness with reliable relational links.

Practical Implementation

Syntax for Creation

In standard SQL, unique constraints can be defined during using the CREATE [TABLE](/page/Table) , either inline with a column definition or as a table-level constraint for single or multiple columns.<citation_url>https://courses.cms.caltech.edu/cs123/sql99std/ansi-iso-9075-2-1999.pdf For a single column, the syntax is:
sql
CREATE [TABLE](/page/Table) example (
    [id](/page/ID) INTEGER,
    email VARCHAR(255) UNIQUE
);
For composite unique constraints spanning multiple columns, the table constraint form is used:
sql
CREATE TABLE example (
    id INTEGER,
    first_name VARCHAR(100),
    last_name VARCHAR(100),
    [UNIQUE](/page/Unique) (first_name, last_name)
);
```[](https://courses.cms.caltech.edu/cs123/sql99std/ansi-iso-9075-2-1999.pdf)

To add a unique constraint to an existing table, the `ALTER TABLE` statement employs the `ADD CONSTRAINT` clause, optionally naming the constraint for easier management:

```sql
ALTER TABLE example ADD [CONSTRAINT](/page/Constraint) uk_email [UNIQUE](/page/Unique) (email);
```[](https://courses.cms.caltech.edu/cs123/sql99std/ansi-iso-9075-2-1999.pdf)

Unique constraints can be modified or removed using `ALTER TABLE`. To drop a named unique constraint, the syntax is:

```sql
ALTER TABLE example DROP CONSTRAINT uk_email;
```[](https://courses.cms.caltech.edu/cs123/sql99std/ansi-iso-9075-2-1999.pdf)

In advanced SQL implementations supporting the standard's deferrable constraint features, unique constraints may be declared as deferrable, allowing violation checks to be postponed until the end of a transaction, with options such as `DEFERRABLE INITIALLY DEFERRED` or `DEFERRABLE INITIALLY IMMEDIATE` to control timing:

```sql
ALTER TABLE example ADD CONSTRAINT uk_email UNIQUE (email) DEFERRABLE INITIALLY DEFERRED;
```[](https://courses.cms.caltech.edu/cs123/sql99std/ansi-iso-9075-2-1999.pdf)

Violations of [unique](/page/Unique) constraints during insert or update operations trigger [standard](/page/Standard) SQL error handling via [SQLSTATE](/page/SQLSTATE) codes; for example, SQLSTATE '23505' indicates a [unique](/page/Unique) violation in systems like [PostgreSQL](/page/PostgreSQL) that adhere to this convention.[](https://www.postgresql.org/docs/current/errcodes-appendix.html)

While the core syntax for creating and managing [unique](/page/Unique) constraints remains consistent across database management systems compliant with the ISO/IEC 9075 SQL standard, variations exist in naming conventions for constraints and any vendor-specific extensions.

Unique constraints allow multiple NULL values, as NULL does not compare equal to itself or any other value under standard SQL semantics.[](https://courses.cms.caltech.edu/cs123/sql99std/ansi-iso-9075-2-1999.pdf)

### Examples Across DBMS

In [MySQL](/page/MySQL), a unique key can be defined directly within a `CREATE TABLE` [statement](/page/Statement) to enforce [uniqueness](/page/Uniqueness) on a column, such as an [email](/page/Email) field in a users [table](/page/Table). For instance, the following SQL creates a table with an [integer](/page/Integer) [primary key](/page/Primary_key) and a [unique](/page/Unique) [constraint](/page/Constraint) on the email column:  
```sql
CREATE TABLE users (
    id INT [PRIMARY KEY](/page/Primary_key),
    email VARCHAR(255) [UNIQUE](/page/Unique)
);
This ensures that no two rows can have the same non- email value. MySQL unique constraints permit multiple values in the constrained column, treating each as distinct from others, which allows multiple rows with emails without violation. In , unique constraints are often added to existing s using the ALTER TABLE statement with a named for better and error . An example adds a unique constraint on the ISBN column of a products table:
sql
ALTER TABLE products ADD CONSTRAINT unique_isbn [UNIQUE](/page/Unique) (isbn);
This automatically creates a unique index to enforce the . supports partial indexes for unique constraints, enabling uniqueness enforcement only on a subset of rows that meet a specified , such as active records, which optimizes and for selective data. For example:
sql
CREATE UNIQUE INDEX active_email_idx ON users (email) WHERE active = true;
This indexes only rows where the active flag is true, allowing duplicate emails in inactive rows. In , unique constraints are implemented via unique indexes, which can be created directly to mimic constraint behavior. The syntax for a basic unique index on a column, such as a product code, is:
sql
CREATE UNIQUE INDEX IX_products_code ON products (code);
This enforces uniqueness across the specified column. Creating a unique constraint is equivalent, as SQL Server automatically generates a nonclustered unique index by default to support it, unless a clustered index is explicitly specified, providing efficient enforcement without altering the table's physical order. In Oracle Database, composite unique keys spanning multiple columns are typically added using the ALTER TABLE statement with an out-of-line constraint definition. For example, to ensure uniqueness across warehouse ID and name in a warehouses table:
sql
ALTER TABLE warehouses ADD CONSTRAINT wh_unq UNIQUE (warehouse_id, warehouse_name);
This prevents duplicate combinations in the specified columns while allowing NULLs in single-column cases. Oracle supports using Flashback Query to investigate unique constraint violations by retrieving historical data states via SELECT ... AS OF with a timestamp or SCN, enabling diagnosis of erroneous transactions that caused duplicates without full recovery.

Advanced Applications

Composite and Partial Unique Keys

Composite unique keys enforce uniqueness across a combination of multiple columns in a table, ensuring that no two rows share the identical set of values in those specified columns, while allowing individual columns to contain duplicate values independently. This approach is particularly useful for modeling compound identifiers where a single column alone cannot guarantee distinctness, such as in scenarios requiring the prevention of duplicate entries based on interrelated attributes. For instance, in an order lines table, a composite unique key on (order_id, product_id) would prohibit multiple identical line items within the same order, thereby maintaining for business processes like inventory management. In SQL implementations, composite unique keys are typically defined using the UNIQUE constraint syntax applied to multiple columns, such as UNIQUE (column1, column2) during table creation or alteration. Unlike single-column unique keys, these constraints treat null values permissively: a row with nulls in all composite key columns satisfies the constraint, but partial nulls may allow duplicates depending on the database system's handling. Common limitations include restrictions on the number of columns (e.g., up to 32 in Oracle) and exclusions of certain data types like LOBs or user-defined objects, which can complicate schema design in complex environments. Additionally, enforcing uniqueness over multiple columns can increase query complexity, as joins or filters must account for the full combination to avoid unintended duplicates. Partial unique keys extend the concept of uniqueness to a selective of rows, applying the only where a specified condition holds true, which is a feature supported in certain database management systems like through partial unique indexes. In this mechanism, the index—and thus the uniqueness enforcement—is built solely over rows satisfying a (e.g., WHERE status = 'active'), allowing duplicates in rows outside that without violating the . A practical use case arises in auditing tables, where a partial unique key on (user_id, timestamp) with WHERE event_type = 'login' ensures no duplicate successful logins per user at the same time, while permitting multiple failed attempts. This selective application optimizes storage by excluding irrelevant rows from the but requires precise alignment between the and querying conditions to leverage the effectively. Limitations include the DBMS-specific nature of partial unique keys, potential for overlooked duplicates if predicates evolve, and added in maintaining across queries that may not match the index's exactly. Overall, both composite and partial unique keys enhance relational by addressing multifaceted uniqueness requirements, though they demand careful consideration to balance integrity with operational efficiency.

Interaction with Indexes and Performance

In major relational database management systems (DBMS) such as , SQL Server, , and , defining a key automatically generates a on the constrained column or columns to enforce uniqueness and facilitate rapid data retrieval. This ensures that no duplicate values are inserted or updated, while also serving as an access path for queries, thereby combining enforcement with query acceleration. Unique indexes typically employ structures, which support efficient ordered access and range scans, leading to faster execution of SELECT statements and JOIN operations on the indexed columns. However, this integration introduces overhead during INSERT and UPDATE operations, as the DBMS must maintain the index by inserting, updating, or deleting index entries, though this cost is typically negligible. In read-dominant environments, the benefits often outweigh these costs, with query performance gains from index usage reducing execution times significantly—for instance, merge joins on unique indexes can lower CPU utilization compared to non-unique counterparts. To optimize , unique keys are generally implemented as non-clustered es, which avoid the row-ordering overhead associated with clustered primary keys and reduce page splits during inserts. Administrators should monitor fragmentation using tools like SQL Server's sys.dm_db_index_physical_stats or PostgreSQL's pgstattuple extension, as fragmentation above 30% can degrade performance and necessitate periodic reorganization or rebuilding. In high-write environments, unique indexes on monotonically increasing columns—such as timestamps or sequences—can lead to contention at the rightmost leaf, causing lock waits and reduced throughput in concurrent scenarios. For such cases, alternatives like filtered indexes in SQL Server allow uniqueness enforcement only on a subset of rows (e.g., WHERE active = 1), minimizing costs and by indexing fewer entries while still supporting targeted queries. This approach can reduce index size in sparse data scenarios, balancing integrity with scalability.

References

  1. [1]
    constraint - Oracle Help Center
    A unique constraint prohibits multiple rows from having the same value in the same column or combination of columns but allows some values to be null. A primary ...<|control11|><|separator|>
  2. [2]
    Primary key, referential integrity, check, and unique constraints - IBM
    A unique constraint (also referred to as a unique key constraint) is a rule that forbids duplicate values in one or more columns within a table. Unique and ...
  3. [3]
    Unique constraints and check constraints - SQL - Microsoft Learn
    Feb 4, 2025 · UNIQUE constraints and CHECK constraints are two types of constraints that can be used to enforce data integrity in SQL Server tables.
  4. [4]
    Documentation: 18: 5.5. Constraints - PostgreSQL
    Unique constraints ensure that the data contained in a column, or a group of columns, is unique among all the rows in the table. The syntax is: CREATE TABLE ...
  5. [5]
    Unique constraints - IBM
    Unique constraints ensure that the values in a set of columns are unique and not null for all rows in the table.
  6. [6]
    Unique constraints - IBM
    A unique constraint is the rule that the values of a key are valid only if they are unique. A key that is constrained to have unique values is called a unique ...
  7. [7]
    Create unique constraints - SQL Server - Microsoft Learn
    Feb 4, 2025 · You can create a unique constraint in SQL Server by using SQL Server Management Studio or Transact-SQL to ensure no duplicate values are entered ...
  8. [8]
    Designing unique constraints - IBM
    Unique constraints ensure that every value in the specified key is unique. A table can have any number of unique constraints, with one unique constraint ...
  9. [9]
    Use Unique Keys in Azure Cosmos DB | Microsoft Learn
    Jul 25, 2025 · With unique keys, you make sure that one or more values within a logical partition is unique. You also can guarantee uniqueness per partition ...
  10. [10]
    [PDF] A Relational Model of Data for Large Shared Data Banks
    Whenever a relation has two or more nonredundant primary keys, one of them is arbitrarily selected and called the primary key of that re- lation. A common ...
  11. [11]
    The Evolution of SQL: From SQL-86 to SQL-2023 - Coginiti
    Jan 18, 2024 · It introduced concepts like transaction isolation levels, constraints (such as CHECK, UNIQUE, FOREIGN KEY), and declarative referential ...
  12. [12]
    7 Data Integrity - Oracle Help Center
    Unique key constraints are appropriate for any column where duplicate values are not allowed. Unique constraints differ from primary key constraints, whose ...
  13. [13]
    What is Data Integrity? | IBM
    Entity integrity relies on unique keys and values created to identify data, ensuring the same data isn't listed numerous times and table fields are correctly ...Overview · Why is data integrity important?
  14. [14]
    International Standard ISO/IEC 9075:1992
    ... unique columns. In addition, if the unique constraint was defined with PRIMARY KEY, then it requires that none of the values in the specified column or ...
  15. [15]
    Chapter 18 – SQL Table and View - SQL 99 - Read the Docs
    ... deferrable Constraint on the Column is a PRIMARY KEY Constraint ... CONSTRAINT constraint_1 UNIQUE(column_1) CONSTRAINT constraint_2 CHECK(column_3 IS NOT NULL));.
  16. [16]
    SQL Language Reference
    Summary of each segment:
  17. [17]
  18. [18]
    constraint - Oracle Help Center
    A composite unique key cannot have more than 32 columns. You cannot designate the same column or combination of columns as both a primary key and a unique key.<|separator|>
  19. [19]
    Primary and foreign key constraints - SQL Server - Microsoft Learn
    Feb 4, 2025 · Primary keys and foreign keys are two types of constraints that can be used to enforce data integrity in SQL Server tables.
  20. [20]
    Create Foreign Key Relationships - SQL Server - Microsoft Learn
    Aug 7, 2025 · Foreign keys can also be defined to reference the columns of a UNIQUE constraint in another table.Permissions · Limitations
  21. [21]
  22. [22]
    Documentation: 18: Appendix A. PostgreSQL Error Codes
    All messages emitted by the PostgreSQL server are assigned five-character error codes that follow the SQL standard's conventions for “SQLSTATE” codes.
  23. [23]
    MySQL 8.4 Reference Manual :: 15.1.20 CREATE TABLE Statement
    In the created table, a PRIMARY KEY is placed first, followed by all UNIQUE indexes, and then the nonunique indexes. This helps the MySQL optimizer to ...SHOW · Documentation · FOREIGN KEY Constraints · Create table ... select
  24. [24]
    Documentation: 18: ALTER TABLE - PostgreSQL
    UNIQUE and PRIMARY KEY constraints from the parent table will be created in the partition, if they don't already exist. If the new partition is a regular table, ...<|separator|>
  25. [25]
    Documentation: 18: 11.8. Partial Indexes - PostgreSQL
    The idea here is to create a unique index over a subset of a table, as in Example 11.3. This enforces uniqueness among the rows that satisfy the index predicate ...Chapter 11. Indexes · 11.7. Indexes on Expressions · 11.3. Multicolumn Indexes
  26. [26]
    Create a unique index - SQL Server | Microsoft Learn
    Nov 22, 2024 · This topic describes how to create a unique index on a table in SQL Server by using SQL Server Management Studio or Transact-SQL.
  27. [27]
    Create Nonclustered Indexes - SQL Server - Microsoft Learn
    Sep 4, 2025 · When you create a UNIQUE constraint, a unique nonclustered index is created to enforce a UNIQUE constraint by default. You can specify a unique ...
  28. [28]
    SQL Language Reference
    ### Summary of Unique Constraints from Oracle Database 19c SQL Reference
  29. [29]
    Database Development Guide
    ### Summary: Flashback Query with Constraints or Unique Keys
  30. [30]
    Performance Benefits of Unique Indexes - Brent Ozar Unlimited®
    Aug 18, 2015 · Unique indexes allow SQL to make better plan choices, support efficient operations, and even one unique index can make a difference. SQL likes ...Missing: relational | Show results with:relational
  31. [31]
    Create Filtered Indexes - SQL Server | Microsoft Learn
    Jun 27, 2025 · A well-designed filtered index can improve query performance and reduce index maintenance and storage costs compared with full-table indexes.