![]() |
VOOZH | about |
An Alternate Key is a candidate key that is not chosen as the Primary Key but can still uniquely identify a record in a table.
Query:
CREATE TABLE CustomerInfo (
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(50),
EmailAddress VARCHAR(100) UNIQUE,
PanNumber VARCHAR(20) UNIQUE,
City VARCHAR(50)
);
INSERT INTO CustomerInfo VALUES
(1, 'James Carter', 'james.carter@example.com', 'PANA12345Z', 'New York'),
(2, 'Emily Watson', 'emily.watson@example.com', 'PANB67890Q', 'Los Angeles');
Output:
Syntax:
The ALTERNATE Keys in SQL are defined using the SQL constraint UNIQUE:
CREATE TABLE CustomerInfo (
colum_1 datatype PRIMARY KEY, -- Primary Key
column_2 datatype ,
column_3 datatype UNIQUE, -- Alternate Key
column_4 datatype UNIQUE, -- Alternate Key
. . . ,
);
Note: A candidate key should be a column that can uniquely identify any row in a table, and any of them are eligible to be selected as the Primary Key.
An Alternate Key in SQL is created using the UNIQUE constraint to enforce uniqueness on a column.
Query:
CREATE TABLE Product (
ProductID INT PRIMARY KEY,
ProductName VARCHAR(50),
ProductCode VARCHAR(20) UNIQUE -- Alternate Key
);
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
OrderNumber VARCHAR(30) UNIQUE, -- Alternate Key
ProductID INT,
Quantity INT,
FOREIGN KEY (ProductID) REFERENCES Product(ProductID)
);
-- Insert data into Product table
INSERT INTO Product VALUES
(101, 'Wireless Mouse', 'WMX-100'),
(102, 'Bluetooth Speaker', 'BTS-250');
-- Insert data into Order table
INSERT INTO Orders VALUES
(1, 'ORD-9001', 101, 2),
(2, 'ORD-9002', 102, 1);
Output:
Here are the detailed comparison between Primary and Alternate key:
| Primary Key | Alternate Key |
|---|---|
| Must be unique | Must be unique |
| Cannot contain NULL values | Can contain NULL values |
| Used to identify each row uniquely | An alternate option for uniqueness |
| The selected candidate key | Other candidate keys not selected as primary |
| One primary key per table | Multiple alternate keys possible |