SQL - Keys
SQL - Keys
Types of Keys in
SQL
for Interview
Follow For more Data Engineering ,Analytics & AI content Anil Patel
Types of Keys in SQL
1.Primary Key
2.Foreign Key
3.Unique Key
4.Composite Key
5.Candidate Key
6.Alternate Key
7. Surrogate key
Follow For more Data Engineering ,Analytics & AI content Anil Patel
Primary Key
A primary key is a unique
identifier for each record in a
table.
Example -
Suppose you have a table called
Students with the following
columns:
StudentID (Primary Key)
FirstName
LastName
DateOfBirth
Email
Follow For more Data Engineering ,Analytics & AI content Anil Patel
Foreign Key
A foreign key -Column(s)
referencing primary key of
another table for relationship
Example -
Consider two tables, "Customers" and
"Orders", with the following columns:
Customers:
CustomerID (primary key)
Name
Email
Orders:
OrderID (primary key)
CustomerID (foreign key)
OrderDate
TotalAmount
Follow For more Data Engineering ,Analytics & AI content Anil Patel
Unique Key
A unique key is a column or
combination of columns that
ensures each value is unique
within a table. It is similar to a
primary key but allows null
value
Follow For more Data Engineering ,Analytics & AI content Anil Patel
Composite Key
Composite key is a
combination of two or more
columns that collectively serve
as a unique identifier for a
record.
Follow For more Data Engineering ,Analytics & AI content Anil Patel
Candidate Key
A candidate key is a column or
combination of columns that
can uniquely identify a record
in a table. It can be chosen as
the primary key, but it is not
mandatory
Example -
Candidate key in a table called "Books":
Table: Books
ISBN (candidate key)
BookID (candidate key)
Title
Author
PublicationYear
The candidate key constraint ensures that
no two books can have the same ISBN or
BookID
Follow For more Data Engineering ,Analytics & AI content Anil Patel
Alternate Key
An alternate key is a candidate
key that is not chosen as the
primary key. It can be used as a
unique identifier for records
Example -
An alternate key in a table called
"Students":
Table: Students
StudentID (primary key)
RollNumber (alternate key)
Name
Email
the StudentID column serves as the primary
key, uniquely identifying each student
record. The RollNumber column, on the other
hand, is an alternate key
Follow For more Data Engineering ,Analytics & AI content Anil Patel
Surrogate Key
A surrogate key is a system-
generated unique identifier added
to a table for the sole purpose of
identifying records. It has no
intrinsic meaning
Example -a surrogate key in a table called
"Employees":
Table: Employees
EmployeeID (surrogate key)
FirstName
LastName
Email
Follow For more Data Engineering ,Analytics & AI content Anil Patel
Architect-Data
Engineering & Analytics
Career Transition Coach
I help to
Transition into Data Engineering &
Analytics Roles
Anil Patel
@aniltppatel
Follow For more Data Engineering ,Analytics & AI content Anil Patel