Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

What Are The Types of Keys in DBMS? Examples, Usage, and Benefits

By Rohan Vats

Updated on Feb 13, 2025 | 19 min read

Share:

Keys in DBMS (Database Management System) serve as the direct link between data accuracy and data retrieval. They make every record in a table stand out by assigning a unique identifier and maintain orderly relationships when multiple tables interact. You can think of them as the guiding force that ensures your database doesn’t mix up rows, lose important details, or pile up duplicate information.

You might wonder why they hold so much importance. Different types of Keys prevent confusion when you deal with large datasets. They also define how different tables should connect, which supports more efficient searches.

This article will walk you through the different types of keys in a DBMS. By the end, you will understand how each key type fits into the bigger picture of reliable database design.

What’s the Need for Keys in DBMS?

Data in a DBMS can turn disorganized if every record looks alike or repeats. You might have tried tracking one person’s details among hundreds of rows, only to discover entries that seem identical. DBMS Keys prevent that confusion and help you draw clear boundaries between records.

Here are some main reasons they matter:

  • Unique identificationA key ensures you don’t mix up two rows or treat them as the same entry.
  • Accurate relationships: Different tables can connect in an orderly way, preventing stray links or mismatched data.
  • Quicker searches: You can find specific rows more easily, which means less scrolling and more precision.
  • Fewer duplicatesA unique marker keeps the table from piling on identical rows that only add clutter.
  • Reliable integrity: If you rely on correct data for projects or queries, a key makes each record trustworthy and consistent.

Also Read: DBMS Tutorial For Beginners: Everything You Need To Know

8 Types of Keys in DBMS in a Glance

Relational databases, also known as SQL databases, rely on different key types to keep each record distinct and to connect data across multiple tables. Each type handles its own task, such as avoiding duplicates or linking related tables. 

Below is a quick view of eight fundamental types of keys in DBMS and what they do.

Keys in DBMS

Description

Super Key One or more columns that can single out every row, even if they include extra attributes not strictly needed for uniqueness.
Primary Key The minimal set of attributes needed to identify a row without any duplicates or null values.
Candidate Key Any key that qualifies to become a primary key because it’s both unique and minimal.
Alternate Key A candidate key not used as the primary key. It still uniquely identifies rows, but it isn’t the main choice for the table.
Foreign Key A column in one table that matches a primary key in another table to keep their data aligned.
Composite Key Two or more columns combined to form a unique identifier. Helpful when no single column can do the job on its own.
Unique Key Demands that all values differ within a column (or set of columns), though it typically allows one null. It prevents repeated entries.
Surrogate Key A system-generated key with no direct real-world meaning, often auto-incremented or assigned by the database itself.

Now that you know the main keys in SQL, let’s explore them in detail.

What’s a Super Key in DBMS? Learn With Examples

A super key is a collection of one or more columns that can identify every row in a table without confusion. It may include extra columns that are not strictly necessary for uniqueness, but any row that matches all the columns in the super key is guaranteed to be one of a kind. 

This differs from a candidate key, which is also unique but contains no redundant attributes.

Let’s understand this with an example:

  • Assume there is a ‘Students table’ that stores registration data.
  • A single column like StudentID can uniquely identify rows, and combining StudentID with other columns (such as Email or ContactNumber) also forms a super key.
  • A super key does not have to be minimal. That is why StudentID + Email is still a valid super key, even if StudentID already does the job by itself.

Below is a sample table that stores basic student information:

StudentID

StudentName

ContactNumber

Email

1 Arun 98765XXXXX arun@example.com
2 Meera 99887XXXXX meera@example.com
3 Kirti 98767XXXXX kirti@example.com

Examples of Super Key in Relational Database

  • (StudentID + Email) in a Students table, where StudentID is already unique, but including Email still maintains uniqueness.
  • (EmployeeID + DepartmentID) in an Employees table, even if EmployeeID alone identifies rows, that extra department column does not break uniqueness.
  • (ProductCode + BatchNumber) in an Inventory table, which ensures each product-batch pair is distinct.

Importance of Super Key

  • Guarantees Uniqueness: Every row is always distinct as long as it matches the super key attributes.
  • Supports Flexible Design: Extra columns in the key allow more detailed queries, even if only one column was needed for uniqueness.
  • Eases Data ValidationInsertion of a record by duplicating every super key column is not allowed, which helps maintain clean data.
  • Forms a Base for Candidate Keys: A candidate key comes from a super key once any unnecessary attributes are removed.

What’s a Primary Key in DBMS? Learn With Examples

A primary key is the minimal set of columns that pinpoint a row in a table. It does not allow duplicates or empty values, which makes it the firmest boundary, preventing confusion between records. This key is the preferred choice for queries that count on accurate and immediate results.

Let’s understand this with an example:

  • Picture a ‘Books table’ holding details such as BookID, Title, Author, and Price.
  • You can assign BookID as the primary key.
  • When you insert or update entries, BookID guarantees each book is distinct, avoiding any messy overlaps.

Below is a sample table for your reference:

BookID

Title

Author

Price

101 A Tale of Two Cities Charles Dickens INR 300
102 Pride and Prejudice Jane Austen INR 280
103 The Great Gatsby F. Scott Fitzgerald INR 350

Examples of a Primary Key in Relational Database

  • StudentID in a Students table
  • EmployeeNumber in an Employees table
  • OrderID in an Orders table

Rules for Primary Keys in DBMS

  • No duplicates: You cannot repeat the same primary key value across rows.
  • No null values: A primary key field must always contain data.
  • Minimal attributes: It should include only the columns you need for unique identification.
  • One per table: You cannot define two primary keys in the same table.

Primary Key Operations

  • Creation: You assign a primary key when you create a table or alter its structure later.
  • ModificationIf you need to change it, you must remove it and set up a new primary key.
  • Deletion: You drop it through an ALTER statement if you want to pick a different primary key.

Importance of Primary Key

  • Clear identification: Ensures no two rows share the same value, keeping data unambiguous.
  • Foundation for relationships: Other tables can safely use it as a reference, making linkages more reliable.
  • Streamlined queries: Speeds up lookups because the database knows each key is distinct.
  • Stable integrity: Protects your table from duplicates or confusion, strengthening the overall data structure.

Did you know? Any column already unique enough to be a primary key automatically qualifies as a super key. However, the reverse might not always be true because a super key can hold extra columns that aren’t strictly needed for identifying a row.

What’s a Candidate Key in DBMS? Learn With Examples

A candidate key is a minimal group of columns that guarantee a row’s uniqueness in a table. Unlike a super key, which can hold extra columns that aren’t required for uniqueness, a candidate key includes only what’s strictly necessary. 

You may find several candidate keys in a single table, but each one meets the same standard: no duplicates and no extra fields that could be removed without losing uniqueness.

Let’s understand this with an example:

  • Imagine a ‘Flights table’ that stores FlightNumber, DepartureTime, ArrivalTime, and GateNumber.
  • You might see that FlightNumber by itself is enough to identify any row uniquely.
  • If your airline system generates special IDs, then FlightID might also qualify as a distinct marker.

Below is a sample table that highlights these columns:

FlightID

FlightNumber

DepartureTime

ArrivalTime

GateNumber

1 AI-203 8:30 AM 10:45 AM B5
2 AI-204 9:00 PM 11:15 PM B7
3 AI-205 10:00 AM 12:20 AM C1

Examples of Candidate Key in Relational Database

  • (Email) in a Users table, assuming no one shares the same email
  • (PhoneNumber) in a Contacts table, if it remains unique for each row
  • (FlightID) in an airline’s flight details table

Rules for Candidate Keys in DBMS

  • Minimal attributes: Only the columns needed for uniqueness should be part of the candidate key
  • No duplicates: Every candidate key combination must be distinct in each row
  • No nulls: Usually, these columns should be filled so they can keep each record separate
  • Multiple possibilities: A table can hold more than one candidate key

Candidate Key Operations

  • Definition: You can declare a column or set of columns as unique when creating or altering a table
  • Change: If you switch a candidate key, you must ensure it still meets the uniqueness requirement
  • Removal: Dropping a candidate key is possible through an ALTER statement, although you must confirm another valid candidate key remains

Importance of Candidate Key

  • Establishes main identifier choices: It offers multiple ways to pinpoint rows, giving you flexibility beyond a single primary key.
  • Supports data accuracy: When users attempt to insert a duplicate combination, the database prevents it if the candidate key is enforced.
  • Simplifies design decisions: Designers can pick which candidate key best fits as the primary key or keep alternates in reserve.
  • Reinforces referential links: Other tables can reliably reference these columns, knowing they lead to exactly one row in the main table.

What’s an Alternate Key in DBMS? Learn With Examples

An alternate key is any candidate key that did not become the primary key. It still uniquely identifies a row in a table but isn’t chosen as the main identifier. That means a table can have multiple candidate keys (like Email and PhoneNumber), but only one of them serves as the primary key. The remaining candidate keys are known as alternate keys.

Let’s understand this with an example:

  • Think of a ‘Patients’ table’ that lists each patient’s PatientID, PhoneNumber, and HealthCardID.
  • You might designate PatientID as the primary key.
  • In that case, PhoneNumber and HealthCardID become alternate keys if they both ensure no duplicates.

Below is a sample table where PatientID is primary, and you can treat HealthCardID or PhoneNumber as alternate keys.

PatientID

PatientName

PhoneNumber

HealthCardID

1 Rakesh 98765XXXXX HCI-654321
2 Kavya 99000XXXXX HCI-987654
3 Rohit 98877XXXXX HCI-112233

Examples of an Alternate Key in Relational Database

  • Email in a Users table when UserID is chosen as primary
  • LicenseNumber in a Drivers’ table when DriverID serves as primary
  • RollNumber in a Students table when StudentID is primary

Rules for Alternate Keys in DBMS

  • Must be unique: They satisfy the same uniqueness requirement as the primary key.
  • Part of candidate keys: An alternate key has the potential to be primary but isn’t selected.
  • No duplication: Rows that share the same alternate key combination cause a conflict.
  • Cannot be null: Typically, these fields shouldn’t have null entries.

Importance of Alternate Key

  • Offers backup uniqueness: Ensures there is another way to confirm a record’s identity if the primary key ever requires a revision.
  • Supports data clarity: Additional unique columns can help keep large tables more organized.
  • Preserves referential freedom: Other tables can still reference these columns, knowing that each value maps to exactly one row.
  • Minimizes collisions: The database rejects duplicate entries on these columns, which aids in preventing mistakes.

What’s a Foreign Key in DBMS? Learn With Examples

A foreign key is a column in one table that points to a primary key in another table. Its main purpose is to link two tables so that they share information in a consistent way. When you reference a foreign key, you ensure that the data in both tables stays synchronized, and entries only appear if there’s a valid match in the primary key column.

Let’s understand this with an example:

  • Consider a ‘Customers table’ that holds CustomerID as the primary key.
  • There’s another table named ‘Orders’, which has OrderID, CustomerID, and details about purchased products.
  • The CustomerID column in the Orders table becomes the foreign key, allowing you to see which customer placed a specific order.

Below is a table that references a foreign key from the ‘Customers table’:

OrderID

CustomerID

ProductName

OrderDate

5001 101 Wireless Mouse 2025-01-12
5002 102 Keyboard 2025-01-13
5003 101 Laptop Stand 2025-01-14

Examples of a Foreign Key in Relational Database

  • StudentID in an Enrollment table referencing the Students table
  • BookID in a BorrowedBooks table referencing the Books table
  • EmployeeID in a Timesheet table referencing the Employees table

Rules for Foreign Keys in DBMS

  • Valid reference: A foreign key must point to an existing primary key (or unique key) in another table.
  • No mismatch: If the parent key changes or is removed, the matching child entries need to follow the specified delete or update actions.
  • Possible null: If the relationship is optional, you can leave a foreign key column empty.
  • Multiple child entries: One key in the parent table can link to many rows in the child table.

Foreign Key Operations

  • Creation: You define a foreign key when creating or altering a child table, often referring to the parent’s primary key.
  • Cascading actions: You can specify if deleting or updating the parent row automatically affects child rows.
  • Removal: Dropping a foreign key requires an ALTER statement that targets the constraint you initially defined.

Importance of Foreign Key

  • Keeps data tied together: Rows in different tables stay connected through valid relationships.
  • Prevents random references: The database rejects any entry that doesn’t match an existing record in the parent table.
  • Maintains referential consistency: Changes in the parent row reflect in the child rows, helping you avoid orphaned data.
  • Encourages modular design: Separates data across multiple tables but keeps everything well-organized.

You can also check out upGrad’s free tutorial, Difference Between Primary Key and Foreign Key.

What’s a Composite Key in DBMS? Learn With Examples

A composite key is a combination of two or more columns that together make each row in a table unique. None of those columns alone can serve as the complete identifier, but merging them guarantees one-of-a-kind rows. 

Composite keys often appear in many-to-many relationships, where individual columns can repeat themselves, but their pairing remains distinct.

Let’s understand this with an example:

  • Envision a ‘StudentCourse table’ that records which students sign up for which courses.
  • A single StudentID can appear many times if the same student takes multiple courses.
  • A single CourseID can also appear many times because multiple students may enroll in the same course.
  • By merging StudentID and CourseID, you get a unique composite key.

Below is a sample table to highlight how two columns can work together:

StudentID

CourseID

EnrollmentDate

101 C001 2025-02-08
101 C002 2025-02-09
102 C001 2025-02-10

Examples of a Composite Key in Relational Database

  • (OrderID + ProductID) in an OrderDetails table, which prevents duplicates of the same product line in one order
  • (StudentID + CourseID) in a StudentCourse table, as shown above
  • (FlightNumber + FlightDate) in an airline schedule table, ensuring each flight on a particular date stays unique

Importance of Composite Key

  • Ensures combined uniqueness: Multiple columns that individually repeat turn into a unique identifier when placed together.
  • Supports many-to-many relations: Composite keys are a reliable way to link multiple entries in two different tables.
  • Minimizes clutter: No need to create artificial IDs if two or more existing columns already guarantee uniqueness.
  • Keeps data consistent: You avoid confusion around repeated entries because no one can insert the exact same composite values twice.

What’s a Unique Key in DBMS? Learn With Examples

A unique key is a constraint that ensures no two rows in a table share the same value for a specified column. It functions similarly to a primary key but can allow a null value. You can mark a column or group of columns as unique if you need each record to stand out without necessarily making it the primary identifier of your table.

Let’s understand this with an example:

  • Imagine a ‘Members table’ where you record MemberID, Email, and PhoneNumber.
  • You might decide that Email should have no duplicates, even if MemberID is already the table’s main key.
  • This prevents two records from using the same email while still allowing one empty slot if someone doesn’t provide an email address.

Below is a table showing unique values in the Email column:

MemberID

Email

PhoneNumber

201 user1@example.com 98765XXXXX
202 user2@example.com 99000XXXXX
203 (null) 98767XXXXX

Examples of a Unique Key in Relational Database

  • Email in a Users table
  • Username in an Accounts table
  • LicensePlate in a Vehicles’ table

Importance of Unique Key

  • Prevents duplicate entries: Keeps data cleaner by rejecting rows that repeat existing values.
  • Allows controlled nulls: You can permit a single empty slot in many database systems, which gives more flexibility than a primary key.
  • Improves lookups: You can find records based on these unique columns without risking mismatched results.
  • Reinforces data qualityIt provides another layer of protection against errors, especially when the primary key alone isn't enough.

What’s a Surrogate Key in DBMS? Learn With Examples

A surrogate key is a system-generated column that identifies each row in a table but has no direct connection to real-world data. Many databases assign an automatically incrementing number as the surrogate key, and this approach offers a stable way to keep records distinct. It won't change over time and doesn't depend on user-provided values or business rules.

Let’s understand this with an example:

  • In a Users table, the column UserID can be auto-incremented by the system.
  • That means every time a new user is inserted, the UserID automatically increases by one and becomes the new record's surrogate key.
  • This makes sure each user has a unique identifier that’s never based on any personal details.

Below is a sample table, marking UserID as the surrogate key:

UserID

Username

Email

JoinDate

1 coder123 coder123@example.com 2025-01-09
2 devPro devPro@example.com 2025-01-10
3 designGeek designGeek@example.com 2025-01-11

Examples of a Surrogate Key in DBMS

  • System-Generated Numeric IDs: The database auto-increments an integer each time you insert a row, giving each entry a distinct number.
  • UUIDs (Universally Unique Identifiers): An algorithm creates long, random strings that are highly unlikely to repeat, giving every row a unique code.
  • Database-Assigned Tokens: Some systems issue tokens or session IDs on the fly to mark rows without relying on user data.
  • Hybrid Surrogate Keys: A numeric prefix paired with an increment counter (like ORD-0001, ORD-0002) can simplify sorting while ensuring unique identifiers.

Importance of Surrogate Key

  • Stable reference: No real-world detail can modify it, which avoids confusion if users change names, emails, or other fields.
  • Smooth relationships: Other tables can link to this ID, making updates or data migrations easier since real-world data might vary.
  • Clear data migrations: Surrogate keys remain consistent across systems, cutting down on mix-ups when you transfer records.
  • Null-safeBecause the database auto-fills the key, there's no risk of empty or repeated fields, which can sometimes happen with natural data.

Want to refresh your basics regarding data structures? Join upGrad's free Certificate Course on Data Structures & Algorithms and get your revision done in a structured way!

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?

 

Primary Key vs Unique Key: Things You Should Know

Primary keys and unique keys both keep duplicate data out of your table. They do so in slightly different ways, especially when you consider their rules on null values and how they fit into the bigger design. Understanding these differences can make your database structure more efficient and flexible.

Take a look at the table below to see how each key type stands apart:

Aspect

Primary Key

Unique Key

Definition Identifies rows by disallowing duplicates and nulls. Demands distinct values in a column but can allow one null (depending on the database system).
Number Allowed Only one per table You can create multiple unique keys in the same table.
Handling Nulls Never permits null values Typically allows one null, but disallows duplicates among non-null entries.
Role Serves as the main reference for relationships in other tables. Provides an extra layer of uniqueness without being the table’s primary reference.
Enforcement Method Declared with the PRIMARY KEY constraint Enforced via the UNIQUE constraint
Indexing Behavior Automatically indexed by most database systems for quick lookups. Generally indexed, but implementation may vary by system.
Impact on Table Design Central for a table’s identity; no two rows can share the same primary key. Improves data quality by blocking accidental repeats, while still offering some flexibility through a null field if allowed.

To build in-depth knowledge, you can also check out upGrad's free tutorial, Primary Key vs Unique Key.

What are the Properties of Different Types of Keys in SQL?

Keys in SQL relational databases go beyond simply ensuring no two rows look alike. They also help you maintain order, handle large volumes of data, and preserve vital relationships between tables. Each key must meet specific standards so that your database doesn’t run into conflicts or inconsistencies.

Here are the main properties you should keep in mind:

  • Uniqueness: No two rows share the same key value, preventing duplicates.
  • Non-Null Constraint: Most keys do not allow empty fields, so each record can be fully identified.
  • Minimality: The key has no extra attributes; if any column is removed, the key no longer guarantees uniqueness.
  • Stability: Key values shouldn’t change often (or at all). When they do, references in other tables may break.
  • Entity Integrity: A valid key ensures each record is recognized as a distinct entity, reinforcing the table’s core structure.
  • Referential Integrity: Foreign keys must match existing primary key values or be null if the relationship is optional. This prevents broken links between tables.
  • Automatic IndexingMost databases create indexes on key columns, speeding up searching and ensuring consistency checks.
  • No Redundancy: The key doesn’t include needless attributes. Each column in the key has a role in making rows distinct.

What are the Benefits of Using Different Types of Keys in DBMS?

There is a definite advantage in defining more than one type of key. Each one focuses on a particular data issue, such as removing duplication or linking related records in separate tables. This arrangement keeps a database flexible and well-prepared to handle both routine data and complex scenarios.

Here are some additional benefits you gain by using these different key types:

  • Data Accuracy: Columns dedicated to uniqueness block duplicate records and boost overall reliability.
  • Smarter Queries: Well-chosen keys speed up lookups because the database quickly locates exact matches without sifting through unnecessary information.
  • Clear Relationships: Foreign keys tie tables together in a logical way, making related records easier to update.
  • Improved Maintenance: When each table follows its own key rules, you reduce mix-ups and spend less time fixing conflicts in linked entries.
  • Room for Growth: Extra unique or alternate keys let you adapt the design later, ensuring your setup remains relevant even as data volume rises.

How Can upGrad Help You?

upGrad offers industry-relevant courses designed in partnership with leading universities and industry experts. With flexible learning, mentorship, and hands-on projects, upGrad helps you gain practical skills and stay ahead in fields like DBMS. 

You can start with the following courses:

So, if you're ready to enhance your DBMS skills, take the first step towards your dream career—book a free career counseling session today for tailored expert advice. You can also visit your nearest upGrad offline career center and start shaping your future now!

Related Blogs:

Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.

Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.

Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.

Frequently Asked Questions

1. What are 8 keys in SQL?

2. What are the types of special keys?

3. Can a foreign key be NULL?

4. Can a foreign key duplicate?

5. Can a unique key be NULL?

6. What is a tuple in SQL?

7. Can a primary key be NULL?

8. Can a candidate key be NULL?

9. Can a super key be NULL?

10. Which key cannot be NULL?

11. What is the difference between a unique key and foreign key?

Rohan Vats

419 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

Suggested Blogs