🔀 Alternate Key (Secondary Key)
🟢 Beginner
📖 Definition
An Alternate Key (also known as a Secondary Key) is any Candidate Key that was NOT chosen to be the table's Primary Key. Even though an alternate key is not selected as the primary key, it is still enforced in SQL using a UNIQUE NOT NULL constraint to guarantee data integrity.
🌍 Multilingual Explanations
English
An Alternate Key is a Candidate Key not selected as the Primary Key. It is enforced using a UNIQUE constraint.
Hindi
Candidate Keys me se jis key ko Primary Key nahi banaya jata, use Alternate Key kehte hain. Baki unique values ko UNIQUE constraint se guard kiya jata hai.
Marathi
Primary Key sodun rahillele baaki che Candidate Keys mhanje Alternate Keys aahat.
Hinglish
Alternate Key is the "runner up" candidate key — e.g. if `user_id` is the Primary Key, then `email` and `phone_number` are Alternate Keys.
⚡ Formula Definition
Alternate Keys = { Candidate Keys } - { Primary Key }
⚡ SQL Syntax
-- Enforcing Alternate Keys with UNIQUE constraints
CREATE TABLE accounts (
account_id INT PRIMARY KEY, -- Primary Key
email VARCHAR(100) NOT NULL UNIQUE, -- Alternate Key 1
phone_number VARCHAR(15) NOT NULL UNIQUE -- Alternate Key 2
);
💡 Production Example
-- User authentication table
CREATE TABLE application_users (
user_id SERIAL PRIMARY KEY, -- Primary Key used internally
username VARCHAR(50) NOT NULL UNIQUE, -- Alternate Key 1 (used for login)
email VARCHAR(100) NOT NULL UNIQUE, -- Alternate Key 2 (used for login/recovery)
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
-- Fast lookup by Alternate Key (PostgreSQL/MySQL automatically indexes UNIQUE columns)
SELECT * FROM application_users WHERE email = 'dev@example.com';
⚠️ Common Pitfalls & Mistakes
- Forgetting UNIQUE constraint on Alternate Keys: Leaving an alternate key like `email` unconstrained permits duplicate emails in your database.
- Using Alternate Keys for Foreign Key links unnecessarily: While SQL permits linking foreign keys to alternate keys (`UNIQUE` columns), linking foreign keys to Primary Keys (`user_id`) is significantly cleaner and faster.
🎯 Tiered Practice Exercises
- Beginner: Identify the alternate keys in a table with columns
emp_id (PK),pan_card_no (UNIQUE),passport_no (UNIQUE), andsalary. - Intermediate: Write a
CREATE TABLEstatement for avehiclestable withvehicle_idas PK andchassis_noandregistration_noas Alternate Keys. - Advanced: Explain how database index performance differs between Primary Keys and Alternate Keys.
🧭 Navigation
← Previous: Super Key | Keys Overview | Next: Composite Key →