Loading learning content...
When a relation has multiple candidate keys, we designate one as the primary key. But what happens to the others? They don't simply disappear or lose their significance. These remaining candidate keys become alternate keys—equally valid identifiers that maintain their uniqueness guarantees.
Consider our familiar Employee example with candidate keys {EmployeeID}, {SSN}, and {Email}. If we choose EmployeeID as the primary key:
{SSN} becomes an alternate key{Email} becomes an alternate keyBoth still uniquely identify employees. Both still require uniqueness enforcement. They simply weren't designated as primary.
Alternate keys are not second-class citizens in your schema—they're essential components of data integrity, often representing real-world identification systems that exist independently of your database design.
By the end of this page, you will understand the formal definition and purpose of alternate keys, master the implementation of alternate key constraints in SQL, appreciate the practical applications and importance of alternate keys in database design, and recognize the relationship between alternate keys, unique constraints, and business rules.
An alternate key (also called a secondary key) is a candidate key that was not selected as the primary key. It possesses all the properties of a candidate key—uniqueness and minimality—but serves as an alternative means of tuple identification.
Mathematical relationship:
Let R be a relation with candidate keys CK = {K₁, K₂, ..., Kₙ} where n > 1 (more than one candidate key exists).
If PK is designated as the primary key, then:
CK - {PK} = {K₁, K₂, ..., Kₙ} - {PK}Each alternate key AK satisfies:
AK → R (superkey property)∀A ∈ AK: (AK - {A})⁺ ≠ R (minimality)AK ≠ PK (not the primary key)Terminological equivalences:
| Term | Definition | Usage |
|---|---|---|
| Alternate Key | Candidate key that's not primary | Formal database theory |
| Secondary Key | Same as alternate key | Some textbooks |
| Unique Key | Any attribute set with uniqueness constraint | SQL implementations (broader) |
| Natural Key | Domain-meaningful identifier | When contrasting with surrogate |
Note: In SQL, the term "UNIQUE constraint" is often used for alternate keys, but UNIQUE can apply to any attribute set, not just candidate keys. A candidate key that becomes an alternate key is typically enforced via UNIQUE.
The term 'alternate' might suggest these keys are less important or optional. This is incorrect! Alternate keys are critical for data integrity—they represent real-world uniqueness requirements that must be enforced regardless of which key was designated primary.
Alternate keys serve several crucial purposes in database systems, extending far beyond simply being 'the keys we didn't pick'.
Example: Multi-System Identity
Consider a Product table in a retail system:
| ProductID (PK) | SKU (AK) | UPC (AK) | ASIN (AK) | Name |
|---|---|---|---|---|
| 1001 | WDG-BLU-001 | 012345678901 | B07XYZ123 | Blue Widget |
| 1002 | WDG-RED-001 | 012345678902 | B07XYZ124 | Red Widget |
| 1003 | GAD-GRN-001 | 012345678903 | B07ABC789 | Green Gadget |
This product has:
ProductID: Internal database identity (primary key)SKU: Warehouse and inventory system identifier (alternate key)UPC: Point-of-sale scanner code (alternate key)ASIN: Amazon product code for e-commerce integration (alternate key)Each alternate key represents a different domain's perspective:
All four keys are valid identifiers. One is primary; three are alternate. All require uniqueness enforcement.
In SQL, alternate keys are implemented using the UNIQUE constraint. This ensures the DBMS enforces uniqueness on the specified column(s), just as it does for primary keys.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
-- Inline UNIQUE constraint (single column)CREATE TABLE Employee ( EmployeeID INT PRIMARY KEY, SSN CHAR(11) NOT NULL UNIQUE, -- Alternate key (inline) Email VARCHAR(255) NOT NULL UNIQUE, -- Another alternate key FirstName VARCHAR(50) NOT NULL, LastName VARCHAR(50) NOT NULL, HireDate DATE NOT NULL); -- Table-level UNIQUE constraint (preferred for clarity)CREATE TABLE Employee ( EmployeeID INT NOT NULL, SSN CHAR(11) NOT NULL, Email VARCHAR(255) NOT NULL, FirstName VARCHAR(50) NOT NULL, LastName VARCHAR(50) NOT NULL, HireDate DATE NOT NULL, PRIMARY KEY (EmployeeID), UNIQUE (SSN), -- Named implicitly by DBMS UNIQUE (Email)); -- Named UNIQUE constraints (best practice)CREATE TABLE Employee ( EmployeeID INT NOT NULL, SSN CHAR(11) NOT NULL, Email VARCHAR(255) NOT NULL, FirstName VARCHAR(50) NOT NULL, LastName VARCHAR(50) NOT NULL, HireDate DATE NOT NULL, CONSTRAINT pk_employee PRIMARY KEY (EmployeeID), CONSTRAINT ak_employee_ssn UNIQUE (SSN), CONSTRAINT ak_employee_email UNIQUE (Email)); -- Composite alternate keyCREATE TABLE CourseOffering ( OfferingID INT PRIMARY KEY, -- Surrogate primary key CourseCode VARCHAR(10) NOT NULL, Semester VARCHAR(20) NOT NULL, Year INT NOT NULL, InstructorID INT NOT NULL, RoomID INT NOT NULL, CONSTRAINT ak_offering_natural UNIQUE (CourseCode, Semester, Year)); -- Adding alternate key to existing tableALTER TABLE EmployeeADD CONSTRAINT ak_employee_badge UNIQUE (BadgeNumber);Use consistent naming for constraints: 'pk_' prefix for primary keys, 'ak_' or 'uq_' prefix for alternate/unique keys, 'fk_' for foreign keys. This makes schema navigation and error messages clearer. Example: 'ak_employee_ssn' immediately indicates an alternate key on SSN in the Employee table.
One critical difference between primary keys and alternate keys involves NULL handling. While primary keys never allow NULLs (entity integrity), alternate keys have more nuanced behavior that varies by DBMS.
The SQL standard allows NULL values in UNIQUE columns, and most DBMSs permit multiple NULLs in a UNIQUE column (since NULL ≠ NULL). However, this can undermine the candidate key property. True alternate keys (candidate keys) should have NOT NULL constraints alongside UNIQUE.
DBMS-Specific NULL Behavior in UNIQUE Columns:
| DBMS | Multiple NULLs Allowed? | Notes |
|---|---|---|
| PostgreSQL | Yes (by default) | Use 'UNIQUE NULLS NOT DISTINCT' (v15+) to disallow |
| MySQL | Yes | NULLs are considered distinct |
| SQL Server | No (by default) | UNIQUE constraint treats NULL as a value |
| Oracle | Yes | Composite: NULL not included in uniqueness check |
| SQLite | Yes | Each NULL is distinct |
Best Practice: Always Pair UNIQUE with NOT NULL for True Alternate Keys
-- THIS IS A TRUE ALTERNATE KEY (candidate key property preserved)
CREATE TABLE Employee (
EmployeeID INT PRIMARY KEY,
SSN CHAR(11) NOT NULL, -- NOT NULL + UNIQUE = true alternate key
CONSTRAINT ak_ssn UNIQUE (SSN)
);
-- THIS IS JUST A UNIQUENESS CHECK (not a true alternate key)
CREATE TABLE Employee (
EmployeeID INT PRIMARY KEY,
LicenseNumber VARCHAR(20), -- Nullable, so not a candidate key
CONSTRAINT uq_license UNIQUE (LicenseNumber) -- Allows NULLs
);
When to allow NULL in UNIQUE columns:
Sometimes you need uniqueness among values that exist, but the attribute is optional:
DriversLicense: Not all employees have one, but those who do must have unique licensesPreviousEmployeeID: Only re-hires have this valueMergedFromID: Only migrated records have this referenceThese are unique constraints, not alternate keys. The distinction matters for theoretical correctness.
Alternate keys have direct implications for database indexing and query performance. Understanding these implications is essential for effective database design.
Most DBMSs automatically create a unique index to enforce UNIQUE constraints. This means your alternate keys are already indexed—queries filtering by alternate keys benefit from index-based access (typically O(log n) via B-tree).
Index creation behavior by DBMS:
| DBMS | Auto-Creates Index for UNIQUE? | Index Type | Customizable? |
|---|---|---|---|
| PostgreSQL | Yes | B-tree | Yes (can specify type) |
| MySQL | Yes | B-tree (InnoDB) | Limited |
| SQL Server | Yes | Non-clustered B-tree | Yes |
| Oracle | Yes | B-tree | Yes (can be preexisting) |
| SQLite | Yes | B-tree | No |
Performance considerations:
12345678910111213141516171819202122
-- These queries benefit from alternate key indexes: -- Lookup by SSN (alternate key)EXPLAIN ANALYZESELECT * FROM Employee WHERE SSN = '123-45-6789';-- Uses index 'ak_employee_ssn' -> Index Scan -- Lookup by Email (alternate key)EXPLAIN ANALYZE SELECT * FROM Employee WHERE Email = 'john.doe@company.com';-- Uses index 'ak_employee_email' -> Index Scan -- Existence check during insert (enforces uniqueness)INSERT INTO Employee (EmployeeID, SSN, Email, FirstName, LastName, HireDate)VALUES (1001, '123-45-6789', 'jane.doe@company.com', 'Jane', 'Doe', '2024-01-15');-- DBMS checks ak_employee_ssn index -> unique constraint violation if exists -- Covering index opportunity (PostgreSQL/SQL Server)CREATE UNIQUE INDEX ak_employee_email_coveringON Employee (Email) INCLUDE (FirstName, LastName);-- Now SELECT FirstName, LastName WHERE Email = ? doesn't need table accessSeveral common patterns emerge in how experienced database designers use alternate keys. Understanding these patterns helps you apply alternate keys effectively.
CustomerID (PK, surrogate) + TaxID (AK, natural).ProductID (PK), SKU (AK for warehouse), UPC (AK for retail), ASIN (AK for Amazon).OrderID (PK), LegacyOrderNumber (AK for compatibility with old system).PostID (PK, efficient for joins), Slug (AK, 'my-awesome-article' for URLs).CountryID (PK), CountryCode (AK, 'US'), CountryName (AK, 'United States').Complete Example: Multi-Pattern Implementation
1234567891011121314151617181920212223242526272829303132333435363738394041424344
-- E-commerce Product Table with Multiple Alternate KeysCREATE TABLE Product ( -- Surrogate Primary Key (internal use) ProductID INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, -- Natural Business Key (Alternate Key #1) SKU VARCHAR(20) NOT NULL, -- External System Identifiers (Alternate Keys #2-4) UPC CHAR(12), -- Universal Product Code EAN CHAR(13), -- European Article Number ASIN VARCHAR(10), -- Amazon Standard Identification -- Human-Readable Identifier (Alternate Key #5) Slug VARCHAR(100) NOT NULL, -- Product Details Name VARCHAR(200) NOT NULL, Description TEXT, Price DECIMAL(10,2) NOT NULL, Category VARCHAR(50) NOT NULL, -- Timestamps CreatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UpdatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP, -- Alternate Key Constraints CONSTRAINT ak_product_sku UNIQUE (SKU), CONSTRAINT ak_product_upc UNIQUE (UPC), CONSTRAINT ak_product_ean UNIQUE (EAN), CONSTRAINT ak_product_asin UNIQUE (ASIN), CONSTRAINT ak_product_slug UNIQUE (Slug)); -- Commentary:-- ProductID: Used in foreign keys (OrderLine.ProductID, InventoryItem.ProductID)-- SKU: Used by warehouse management system-- UPC: Used by POS systems for barcode scanning-- EAN: Used by European retail partners-- ASIN: Used by Amazon integration API-- Slug: Used in URLs (/products/blue-widget-large)-- -- Each alternate key enables different use cases while ProductID-- provides efficient internal relationships.While primary keys are the conventional target for foreign key references, alternate keys can also serve as foreign key targets. This capability is sometimes necessary for legacy integration or specific design requirements.
SQL allows foreign keys to reference any column(s) with a UNIQUE or PRIMARY KEY constraint. This means alternate keys can be referenced by foreign keys from other tables, though this is less common than referencing primary keys.
12345678910111213141516171819202122232425262728293031323334
-- Parent table with primary and alternate keysCREATE TABLE Customer ( CustomerID INT PRIMARY KEY, TaxID CHAR(11) NOT NULL UNIQUE, -- Alternate key Email VARCHAR(255) NOT NULL UNIQUE, -- Alternate key Name VARCHAR(100) NOT NULL); -- Child referencing PRIMARY KEY (conventional)CREATE TABLE Order_ByID ( OrderID INT PRIMARY KEY, CustomerID INT NOT NULL, OrderDate DATE NOT NULL, FOREIGN KEY (CustomerID) REFERENCES Customer(CustomerID)); -- Child referencing ALTERNATE KEY (special cases)CREATE TABLE TaxDocument ( DocumentID INT PRIMARY KEY, TaxID CHAR(11) NOT NULL, DocumentType VARCHAR(50) NOT NULL, FilingDate DATE NOT NULL, -- Foreign key references alternate key, not primary key FOREIGN KEY (TaxID) REFERENCES Customer(TaxID)); -- Another example: Legacy system integrationCREATE TABLE LegacyOrder ( LegacyOrderID INT PRIMARY KEY, CustomerEmail VARCHAR(255) NOT NULL, OrderData TEXT, -- Reference by email because legacy system didn't use CustomerID FOREIGN KEY (CustomerEmail) REFERENCES Customer(Email));If a foreign key references an alternate key, and that alternate key value changes, ON UPDATE CASCADE must propagate the change to all referencing tables. This can be expensive for frequently-updated alternate keys. Prefer immutable alternate keys as FK targets.
We've thoroughly explored alternate keys—the candidate keys that support data integrity and provide alternative identification paths alongside the primary key. Let's consolidate the key insights:
What's next:
Now that we understand primary and alternate keys within a single relation, we'll explore foreign keys—the mechanism that connects relations together. Foreign keys are the foundation of referential integrity and enable the relational model's power to represent complex, interconnected data.
You now understand alternate keys as integral components of relational integrity. You can implement alternate keys using UNIQUE constraints, apply common design patterns effectively, understand NULL handling nuances across DBMSs, and appreciate the indexing and performance implications. Next, we'll explore foreign keys—the relational glue that connects tables together.