Alternate Key in SQL
? Alternate Key in SQL
An Alternate Key is any candidate key not chosen as the Primary Key in a table.
? Understanding with Definitions
Candidate Key: A column (or combination of columns) that can uniquely identify each row.
Primary Key: The candidate key chosen to uniquely identify rows.
Alternate Key: The candidate key(s) not selected as the primary key.
? Example Table: students
| student_id | roll_no | name | |
|---|---|---|---|
| 101 | a@example.com | 1001 | Alice |
| 102 | b@example.com | 1002 | Bob |
Candidate Keys:
student_idemailroll_no
If we choose:
Primary Key =
student_idThen Alternate Keys =
email,roll_no
? Declaring an Alternate Key
In SQL, you enforce an alternate key using a UNIQUE constraint.
CREATE TABLE students ( student_id INT PRIMARY KEY, email VARCHAR(100) UNIQUE, roll_no INT UNIQUE, name VARCHAR(50));Here:
student_idis the Primary Keyemailandroll_noare Alternate Keys (withUNIQUEconstraint)
? Why Use Alternate Keys?
To ensure uniqueness on other columns besides the primary key.
Helps prevent duplicate data (e.g., no duplicate emails or roll numbers).
Can be used to define foreign key relationships in other tables.
Let me know if you want to practice with queries or explore composite alternate keys too!