0% found this document useful (0 votes)
7 views

What is a Key in Database relation

The document outlines various types of keys in SQL databases, including Primary Key, Unique Key, Foreign Key, Composite Key, Candidate Key, Alternate Key, and Super Key, each serving specific purposes for data integrity and relationships. It provides definitions, examples, and rules for each key type, along with SQL commands for creating, altering, and dropping keys. The document emphasizes the importance of these keys in maintaining data uniqueness and referential integrity within database tables.

Uploaded by

Putta Swamy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

What is a Key in Database relation

The document outlines various types of keys in SQL databases, including Primary Key, Unique Key, Foreign Key, Composite Key, Candidate Key, Alternate Key, and Super Key, each serving specific purposes for data integrity and relationships. It provides definitions, examples, and rules for each key type, along with SQL commands for creating, altering, and dropping keys. The document emphasizes the importance of these keys in maintaining data uniqueness and referential integrity within database tables.

Uploaded by

Putta Swamy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Types of Keys:

SQL offers several types of Keys, each serving a distinct purpose in the
database ecosystem:
1) Primary Key: It is an identifier for each record in a table. It ensures data
uniqueness and serves as a reference for establishing relationships.
2) Unique Key: Like a Primary Key, a Unique Key enforces uniqueness but
allows null values. It's used for columns that must be unique but might
contain missing information.
3) Foreign Key: A Foreign Key establishes a link between two tables based
on a standard column. It maintains referential integrity and enforces
relationships between tables.
4) Composite Key: A Composite Key uses multiple columns to create a
unique identifier. It's useful when a single column cannot ensure
uniqueness.
5) Candidate Key: Candidate Keys are potential options for Primary Keys.
They share the properties of uniqueness and minimal redundancy.
6) Alternate Key: An Alternate Key is a candidate key that isn't chosen as
the Primary Key. It provides additional options for uniquely identifying
records.
7) Super Key: It is a set of attributes that, taken together, uniquely identify
records. It can include more details than necessary for a primary key.
Primary key:
It is the first key used to identify one and only one instance of an
entity uniquely and not null. For each entity, the primary key selection is
based on requirements and developers.

In the PERSON table. The key which is most suitable from ID,
License_Number and Passport_Number becomes a primary key. ID can be the
primary key since it is unique for each employee. We can even select
License_Number and Passport_Number as primary keys since they are also
unique.
Rules for Primary Key
 Unique values must be present in all columns, chosen as primary key
 A single table can have only one primary key
 No NULL value must be present in the column chosen as primary key
 A new row cannot be inserted with an existing primary key
Primary Key Operations
The various operations of primary keys.
 Apply Primary Key while creating table
 Apply Primary Key on multiple columns
 Alter a Primary Key of a table
 Drop a Primary Key of a table
Apply Primary Key while creating table
#SQL Server/ MS Access/ Oracle
CREATE TABLE Patients (
PatientID INT NOT NULL PRIMARY KEY,
PatientName VARCHAR(255) NOT NULL,
Sex VARCHAR(255),
Age VARCHAR(255),
MedInsuranceNo VARCHAR(255,
AadharNo INT
);
#MySQL
CREATE TABLE Patients (
PatientID INT,
PatientName VARCHAR(255),
Sex VARCHAR(255),
Age VARCHAR(255),
MedInsuranceNo VARCHAR(255),
AadharNo INT,
PRIMARY KEY (PatientID)
);
Apply Primary Key on multiple columns
CREATE TABLE Patients (
PatientID INT,
PatientName VARCHAR(255),
Sex VARCHAR(255),
Age VARCHAR(255),
MedInsuranceNo VARCHAR(255),
AadharNo INT,
CONSTRAINT PK_Patient PRIMARY KEY (PatientID, MedInsuranceNo)
);
Alter a Primary Key of a table
[code]
–Single COLUMN
ALTER TABLE Patients
ADD PRIMARY KEY (PatientID);
–Multiple COLUMNS
ALTER TABLE Patients
ADD CONSTRAINT PK_Patient PRIMARY KEY (PatientID, MedInsuranceNo,
AadharNo);
Drop a Primary Key of a table
#SQL Server/ MS Access/ Oracle
ALTER TABLE Patients
DROP CONSTRAINT PK_Patient;
#MySQL
ALTER TABLE Patients
DROP PRIMARY KEY;

ypes of Keys in Database


The following types of keys are used in a database. Let us understand each
one of them one by one.
 Super Key
 Candidate Key
 Primary Key
 Alternate Key
 Unique Key
 Foreign Key
 Composite Key
For our understanding I am going to consider the following tables.
Patients Table
Patient ID Patient Name Sex Age MedInsuranceNo AadharNo
01 Sheela F 23 Med0291 83929231901
2
02 Rehan M 21 Med8421 12345678901
2
03 Anay M 56 Med4203 84829846920
1
04 Mahira F 42 Med4792 72472302192
2
05 Nishant M 12 Med8419 47203831109
9
Checkup Details Table
Patient ID AnnualCheckupMonth Fees
03 Feb2022 6700
04 Apr2022 8900
03 Feb2022 6700
04 Apr2022 8900
Super Key
Super Key is a set of attributes that can uniquely identify a table. A single
table can have multiple super keys. A candidate key, primary key and a
unique key can be a super key, but the reverse does not hold true.
Example:
In our above example we have chosen the PatientID, MedInsuranceNo and
Aadhar No to uniquely identify tuples. So the super key set will be as follows:
 {PatientID}
 {MedInsuranceNo}
 {AadharNo}
 {PatientID, MedInsuranceNo}
 {PatientID, AadharNo}
 {MedInsuranceNo, AadharNo}
 {PatientID, MedInsuranceNo, AadharNo}
Candidate Key
Candidate Key is a set of attributes that can uniquely identify a table. A
single table can have multiple candidate keys. Out of all the chosen
candidate keys, one of the keys is selected as the primary key.
Example:
PatientID, MedInsuranceNo, AadharNo can be chosen as the candidate keys
from the Patients table.
Rules for Candidate Key
 Unique values must be present in all columns, chosen as candidate key
 A single table can have multiple candidate keys
 Null values can be present in the column chosen as candidate key
Candidate Key Operations
In this section of the article let us understand the various operations of
candidate keys.
 Apply Candidate Key while creating table
 Alter a Candidate Key of a table
 Drop a Candidate Key of a table
Apply Candidate Key while creating table
CREATE TABLE Patients (
PatientID INT UNIQUE,
PatientName VARCHAR(255),
Sex VARCHAR(255),
Age VARCHAR(255),
MedInsuranceNo VARCHAR(255) UNIQUE,
AadharNo INT UNIQUE,
);
Alter a Candidate Key of a table
–Single COLUMN
ALTER TABLE Patients
ADD UNIQUE (PatientID);
–Multiple COLUMNS
ALTER TABLE Patients
ADD UNIQUE CK_Patient(PatientID, MedInsuranceNo, AadharNo);
Drop a Candidate Key of a table
ALTER TABLE Patients
DROP CONSTRAINT CK_Patient;
Primary Key
Primary Key is a set of attributes that can uniquely identify a table. A single
table can have only one primary key. Out of all the chosen candidate keys,
one of the keys is selected as the primary key.
Example:
PatientID, MedInsuranceNo, AadharNo are chosen as the candidate keys from
the Patients table. Either of them can be chosen as a Primary key.
Alternate Key
As the name suggests, all the candidate keys which are not selected as
primary keys are known as the Alternate Key.
Example:
If the PatientID is selected as the Primary Key, then the MedInsuranceNo and
the AadharNo are known as the alternate keys.
Rules for Alternate Key
 Unique values must be present in all columns, chosen as alternate key
 The alternate key is a part of candidate key but is not connected to
primary key
 In case a table contains a single candidate key then it will be chosen as
the primary key. In that case there won’t be any alternate key.
 It is defined by the UNIQUE keyword
Apply Alternate Key while creating table
CREATE TABLE Patients (
PatientID INT PRIMARY KEY,
PatientName VARCHAR(255),
Sex VARCHAR(255),
Age VARCHAR(255),
MedInsuranceNo VARCHAR(255) UNIQUE,
AadharNo INT
);
Unique Key
The Unique key is quite similar to primary keys in a database. The only
difference is that the unique keys allow a single NULL value in the column
and must not have any duplicate values.
Example:
MedInsuranceNo can be considered as a unique key.
Apply Unique Key while creating table
CREATE TABLE Patients (
PatientID INT,
PatientName VARCHAR(255),
Sex VARCHAR(255),
Age VARCHAR(255),
MedInsuranceNo VARCHAR(255),
AadharNo INT,
UNIQUE (MedInsuranceNo)
);
Alter a Unique Key of a table
–Single COLUMN
ALTER TABLE Patients
ADD UNIQUE (PatientID);
–Multiple COLUMNS
ALTER TABLE Patients
ADD CONSTRAINT UK_Patient UNIQUE (PatientID, MedInsuranceNo,
AadharNo);
Foreign Key
Primary Key is a set of attributes that can take values referenced to the
values of another table.
Example:
PatientID in the CheckupDetails table is referred to the PatientID in the
Patients table.
Rules for Foreign Key
 Relationship between both the tables is known as referential integrity.
 A single table can have multiple foreign keys
 A foreign key can have NULL values.
 You can duplicate foreign keys
 The table consisting of the foreign key is known as the CHILD table and
the table that is referred by the foreign key is called the parent table.
Foreign Key Operations
In this section of the article let us understand the various operations of
foreign keys.
 Apply Foreign Key while creating table
 Apply Foreign Key on multiple columns
 Alter a Foreign Key of a table
 Drop a Foreign Key of a table
Apply Foreign Key while creating table
CREATE TABLE CheckupDetails (
PatientID INT NOT NULL,
AnnualCheckUpMonth VARCHAR(255),
Price INT,
PRIMARY KEY (PatientID),
FOREIGN KEY (PatientID) REFERENCES Patients(PatientID)
);
Apply Foreign Key on multiple columns
CREATE TABLE CheckupDetails (
PatientID INT NOT NULL,
AnnualCheckUpMonth VARCHAR(255),
Price INT,
PRIMARY KEY (PatientID),
CONSTRAINT FK_Checkup FOREIGN KEY (PatientID) REFERENCES
Patients(PatientID)
);
Alter a Foreign Key of a table
–Single COLUMN
ALTER TABLE CheckupDetails
ADD FOREIGN KEY (PatientID)REFERENCES Patients(PatientID);
–Multiple COLUMNS
ALTER TABLE CheckupDetails
ADD CONSTRAINT FK_Checkup FOREIGN KEY Patients(PatientID);
Drop a Foreign Key of a table
#SQL Server/ MS Access/ Oracle
ALTER TABLE CheckupDetails
DROP CONSTRAINT FK_Checkup;
#MySQL
ALTER TABLE CheckupDetails
DROP FOREIGN KEY;
Composite Key
As the name suggests a composite key is a combination of multiple columns
that can uniquely identify tuples.
Example:
PaitentID and AnnualCheckupMonth can be considered together as a
composite key.
Apply Composite Key on multiple columns
CREATE TABLE Patients (
PatientID INT,
PatientName VARCHAR(255),
Sex VARCHAR(255),
Age VARCHAR(255),
MedInsuranceNo VARCHAR(255),
AadharNo INT,
PRIMARY KEY (PatientID, MedInsuranceNo)
);
Conclusion
With this, we end this article on the various keys used in the database. We
hope you found it informative. You can refer to the article on MySQL
Commands for a detailed walkthrough of all commands.
1. Primary key
o It is the first key used to identify one and only one instance of an entity
uniquely. An entity can contain multiple keys, as we saw in the PERSON
table. The key which is most suitable from those lists becomes a
primary key.
o In the EMPLOYEE table, ID can be the primary key since it is unique for
each employee. In the EMPLOYEE table, we can even select
License_Number and Passport_Number as primary keys since they are
also unique.
o For each entity, the primary key selection is based on requirements
and developers.
A Primary Key's Objective:
PauseNext
Mute
Current Time 0:08
/
Duration 5:27
Loaded: 14.66%
Fullscreen
o Data uniqueness is enforced by the primary key, which stops duplicate
records from being inserted. Retaining data accuracy depends on its
distinctiveness.
o It offers a rapid and effective means of gaining permission to access
particular records from the table. The main key allows the database to
locate a specific row without having to search the entire table.
2. Candidate key
o A candidate key is an attribute or set of attributes that can uniquely
identify a tuple.
o Except for the primary key, the remaining attributes are considered a
candidate key. The candidate keys are as strong as the primary key.
For example: In the EMPLOYEE table, id is best suited for the primary key.
The rest of the attributes, like SSN, Passport_Number, License_Number, etc.,
are considered a candidate key.
A Candidate Key's Objective:
o A candidate key's main goal is to make sure that no two items in a
table have the same set of attribute values combined. It offers a
dependable way to identify records individually.
o Choosing primary keys, creating database schemas, and maintaining
data integrity all depend on candidate keys.
3. Super Key
Super key is an attribute set that can uniquely identify a tuple. A super key is
a superset of a candidate key.
For example: In the above EMPLOYEE table, for(EMPLOEE_ID,
EMPLOYEE_NAME), the name of two employees can be the same, but their
EMPLYEE_ID can't be the same. Hence, this combination can also be a key.
The super key would be EMPLOYEE-ID (EMPLOYEE_ID, EMPLOYEE-NAME), etc.
The Super Key's Objective:
o Making ensuring that no two records in a database have the same
mixture of value of attributes is the main function of a super key. It
supports the preservation of data integrity.
o Candidate keys, or minimal super keys, are identified using super keys.
The characteristics or sets of characteristics that are utilized as
primary keys in the table are known as candidate keys.
4. Foreign key
o Foreign keys are the column of the table used to point to the primary
key of another table.
o Every employee works in a specific department in a company, and
employee and department are two different entities. So we can't store
the department's information in the employee table. That's why we link
these two tables through the primary key of one table.
o We add the primary key of the DEPARTMENT table, Department_Id, as a
new attribute in the EMPLOYEE table.
o In the EMPLOYEE table, Department_Id is the foreign key, and both the
tables are related.
A Foreign Key's Objective:
o Referential integrity refers to the validity and consistency of
relationships across tables, and it is the essential goal of a foreign key.
It stops acts that might jeopardize these partnerships' integrity.
o It guarantees the consistency of data across linked tables. A foreign
key may make sure that orders are linked to legitimate customer IDs,
for instance, if you have two tables: "Orders" and "Customers".
5. Alternate key
There may be one or more attributes or a combination of attributes that
uniquely identify each tuple in a relation. These attributes or combinations of
the attributes are called the candidate keys. One key is chosen as the
primary key from these candidate keys, and the remaining candidate key, if
it exists, is termed the alternate key. In other words, the total number of
the alternate keys is the total number of candidate keys minus the primary
key. The alternate key may or may not exist. If there is only one candidate
key in a relation, it does not have an alternate key.
For example, employee relation has two attributes, Employee_Id and
PAN_No, that act as candidate keys. In this relation, Employee_Id is chosen
as the primary key, so the other candidate key, PAN_No, acts as the Alternate
key.

The objective of alternate key is:


o An alternative key's main goal is to make sure that no two entries in a
table have the same set of attribute values combined. It provides a
different method of record identification from the primary key.
o By providing a variety of possibilities for uniquely identifying entries,
alternate keys facilitate flexibility in database architecture. Different
qualities may be effectively employed to identify records based on
certain use cases.
6. Composite key
Whenever a primary key consists of more than one attribute, it is known as a
composite key. This key is also known as Concatenated Key.
For example, in employee relations, we assume that an employee may be
assigned multiple roles, and an employee may work on multiple projects
simultaneously. So the primary key will be composed of all three attributes,
namely Emp_ID, Emp_role, and Proj_ID in combination. So these attributes
act as a composite key since the primary key comprises more than one
attribute.
The objective of alternate key is:
o An alternative key's main goal is to make sure that no two entries in a
table have the same set of attribute values combined. It provides a
different method of record identification from the primary key.
o By providing a variety of possibilities for uniquely identifying entries,
alternate keys facilitate flexibility in database architecture. Different
qualities may be effectively employed to identify records based on
certain use cases.
7. Artificial key
The key created using arbitrarily assigned data are known as artificial keys.
These keys are created when a primary key is large and complex and has no
relationship with many other relations. The data values of the artificial keys
are usually numbered in a serial order.
For example, the primary key, which is composed of Emp_ID, Emp_role, and
Proj_ID, is large in employee relations. So it would be better to add a new
virtual attribute to identify each tuple in the relation uniquely.
Different Types of Database Keys
Super Key
The set of one or more attributes (columns) that can uniquely identify a tuple
(record) is known as Super Key. For Example, STUD_NO, (STUD_NO,
STUD_NAME), etc.
 A super key is a group of single or multiple keys that uniquely
identifies rows in a table. It supports NULL values in rows.
 A super key can contain extra attributes that aren’t necessary for
uniqueness. For example, if the “STUD_NO” column can uniquely
identify a student, adding “SNAME” to it will still form a valid super key,
though it’s unnecessary.
Example:
Table STUDENT

STUD_NO SNAME ADDRESS PHONE

12345678
1 Shyam Delhi
9

22336579
2 Rakesh Kolkata
6

17546896
3 Suraj Delhi
5

Consider the table shown above.


STUD_NO+PHONE is a super key.
Relation between Primary Key, Candidate Key, and Super Key
Now Try Questions discussed in Number of possible Superkeys to test your
understanding.
Candidate Key
The minimal set of attributes that can uniquely identify a tuple is known as
a candidate key. For Example, STUD_NO in STUDENT relation.
 A candidate key is a minimal super key, meaning it can uniquely
identify a record but contains no extra attributes.
 It is a super key with no repeated data is called a candidate key.
 The minimal set of attributes that can uniquely identify a record.
 A candidate key must contain unique values, ensuring that no two rows
have the same value in the candidate key’s columns.
 Every table must have at least a single candidate key.
 A table can have multiple candidate keys but only one primary key.
Example:
STUD_NO is the candidate key for relation STUDENT.
Table STUDENT
STUD_NO SNAME ADDRESS PHONE

12345678
1 Shyam Delhi
9

22336579
2 Rakesh Kolkata
6

17546896
3 Suraj Delhi
5

 The candidate key can be simple (having only one attribute) or


composite as well.
Example:
{STUD_NO, COURSE_NO} is a composite
candidate key for relation STUDENT_COURSE.
Table STUDENT_COURSE

STUD_NO TEACHER_NO COURSE_NO

1 001 C001

2 056 C005

Note: In SQL Server a unique constraint that has a nullable


column, allows the value ‘ null ‘ in that column only once . That’s why the
STUD_PHONE attribute is a candidate here, but can not be a ‘null’ value in
the primary key attribute.
Primary Key
There can be more than one candidate key in relation out of which one can
be chosen as the primary key. For Example, STUD_NO, as well as
STUD_PHONE, are candidate keys for relation STUDENT but STUD_NO can be
chosen as the primary key (only one out of many candidate keys).
 A primary key is a unique key, meaning it can uniquely identify each
record (tuple) in a table.
 It must have unique values and cannot contain
any duplicate values.
 A primary key cannot be NULL, as it needs to provide a valid,
unique identifier for every record.
 A primary key does not have to consist of a single column. In some
cases, a composite primary key (made of multiple columns) can be
used to uniquely identify records in a table.
 Databases typically store rows ordered in memory according to
primary key for fast access of records using primary key.
Example:
STUDENT table -> Student(STUD_NO, SNAME, ADDRESS, PHONE) , STUD_NO
is a primary key
Table STUDENT

STUD_NO SNAME ADDRESS PHONE

12345678
1 Shyam Delhi
9

22336579
2 Rakesh Kolkata
6

17546896
3 Suraj Delhi
5

Alternate Key
An alternate key is any candidate key in a table that is not chosen as
the primary key. In other words, all the keys that are not selected as the
primary key are considered alternate keys.
 An alternate key is also referred to as a secondary key because it can
uniquely identify records in a table, just like the primary key.
 An alternate key can consist of one or more columns (fields) that can
uniquely identify a record, but it is not the primary key
 Eg:- SNAME, and ADDRESS is Alternate keys
Example:
Consider the table shown above.
STUD_NO, as well as PHONE both,
are candidate keys for relation STUDENT but
PHONE will be an alternate key
(only one out of many candidate keys).

Primary Key, Candidate Key, and Alternate Key


Foreign Key
A foreign key is an attribute in one table that refers to the primary key in
another table. The table that contains the foreign key is called
the referencing table, and the table that is referenced is called
the referenced table.
 A foreign key in one table points to the primary key in another table,
establishing a relationship between them.
 It helps connect two or more tables, enabling you to create
relationships between them. This is essential for maintaining data
integrity and preventing data redundancy.
 They act as a cross-reference between the tables.
 For example, DNO is a primary key in the DEPT table and a non-key in
EMP
Example:
Refer Table STUDENT shown above.
STUD_NO in STUDENT_COURSE is a
foreign key to STUD_NO in STUDENT relation.
Table STUDENT_COURSE

STUD_NO TEACHER_NO COURSE_NO

1 005 C001

2 056 C005

It may be worth noting that, unlike the Primary Key of any given relation,
Foreign Key can be NULL as well as may contain duplicate tuples i.e. it need
not follow uniqueness constraint. For Example, STUD_NO in the
STUDENT_COURSE relation is not unique. It has been repeated for the first
and third tuples. However, the STUD_NO in STUDENT relation is a primary
key and it needs to be always unique, and it cannot be null.
Relation between Primary Key and Foreign Key
Composite Key
Sometimes, a table might not have a single column/attribute that uniquely
identifies all the records of a table. To uniquely identify rows of a table, a
combination of two or more columns/attributes can be used. It still can give
duplicate values in rare cases. So, we need to find the optimal set of
attributes that can uniquely identify rows in a table.
 It acts as a primary key if there is no primary key in a table
 Two or more attributes are used together to make a composite key .
 Different combinations of attributes may give different accuracy in
terms of identifying the rows uniquely.
Example:
FULLNAME + DOB can be combined
together to access the details of a student.
Different Types of Keys
Conclusion
In conclusion, the relational model makes use of a number of keys:
Candidate keys allow for distinct identification, the Primary key serves as the
chosen identifier, Alternate keys offer other choices, and Foreign keys create
vital linkages that guarantee data integrity between tables. The creation of
strong and effective relational databases requires the thoughtful application
of these keys.
SQL Server Keys
 by PowerBIDocs
 1 Comment
 SQL Server
5/5 - (1 vote)
SQL Keys are a single or combination of multiple fields in a table. They allow
you to create a relationships between two or more tables and maintain
uniqueness in a table.
It is used retrieve data from the table according to the condition and also
they are responsible for to keep consistent and valid data in database.
1. Primary Key
A Primary key is a column or a group of columns that uniquely identifies
each row in a table. It contain UNIQUE values in column, and does not allows
NULL values.

Primary Key
In Table-1, Empid is a Primary Key. In SQL Server, by default primary key
creates a clustered index.
Each table can have only one Primary key and multiple Candidate keys

2. Candidate Key
Candidate Key can be defined as a set of one or more columns that can
identify a record uniquely in a table and which can be selected as a primary
key of the table.
It contains UNIQUE values in column, and does not allows NULL values.

Candidate Keys
In Table-1, Empid, EmpLicence and EmpPassport are candidate keys.
3. Unique Key
Unique key is similar to primary key and does not allow duplicate values in
the column.
Comparison with Primary Key

o It allows one null value in the column.


o By default, it creates a non-clustered index on heap tables.
4. Alternate Key
Alternate key can be defined as a key that can be work as a primary key if
required but right now it is not Primary key.
Example: In Table-1, Empid is primary key but we can
use EmpLicence & EmpPassport as a primary key to get unique record
from table, That’s why EmpLicence & EmpPassport are Alternate keys but
right now it is not primary keys.

5. Composite/ Compound Key


Composite Key is a combination of more than one columns of a table. It can
be a Candidate key and Primary key.
Example: In Table-1, we can combine Empid & EmpLicence columns to
fetch the data from table.
6. Super Key
A super key is a group of single or multiple keys which identifies rows in a
table.

Super Key
Example: In Table-1, Primary key, Unique key, Alternate key are a subset of
Super Keys.
{Empid, Empname}, {Empid, EmpPassport, Empname}, {EmpLicence,
Empname}
Any set of column which
contains EmpLicence or EmpPassport or Empid is a super key of the
table.
7. Foreign Key
Foreign creates a relationship between two or more tables, a primary key of
one table is referred as a foreign key in another table.
It can also accept multiple null values and duplicate values.
Foreign Key

Example: In Table 1, Did column(Foreign key) is points


to Did column(Primary key) of Table-2.
Your valuable feedback, question, or comments about this post are always
welcome or you can leave us message on our contact form , we will revert to
you asap.

Types of SQL Keys


We have following types of keys in SQL which are used to fetch records from
tables and to make relationship among tables or views.
1. Super Key: Super key is a set of one or more than one keys that can be
used to identify a record uniquely in a table. Example : Primary key, Unique
key, Alternate key are subset of Super Keys.
2. Candidate Key: A Candidate Key is a set of one or more fields/columns
that can identify a record uniquely in a table. There can be multiple
Candidate Keys in one table. Each Candidate Key can work as Primary
Key. Example: In below diagram ID, RollNo and EnrollNo are Candidate Keys
since all these three fields can be work as Primary Key.
3. Primary Key: Primary key is a set of one or more fields/columns of a
table that uniquely identify a record in database table. It can not accept null,
duplicate values. Only one Candidate Key can be Primary Key.
4. Alternate key: An Alternate key is a key that can be work as a primary
key. Basically it is a candidate key that currently is not primary
key. Example: In below diagram RollNo and EnrollNo becomes Alternate
Keys when we define ID as Primary Key.

5. Composite/Compound Key: Composite Key is a combination of more


than one fields/columns of a table. It can be a Candidate key, Primary key.
Advertisement
6. Unique Key: Unique key is a set of one or more fields/columns of a table
that uniquely identify a record in database table. It is like Primary key but it
can accept only one null value and it can not have duplicate values.
7. Foreign Key: Foreign Key is a field in database table that is Primary key
in another table. It can accept multiple null, duplicate values.

Hi !
Welcome to the new edition of Business Analytics Review !

Today we would be exploring SQL databases, focusing


specifically on the concepts of Primary Keys and Foreign
Keys. These fundamental components are essential for
establishing relationships between tables and ensuring data
integrity in relational databases .
Primary Key

 Unique Identifier: A primary key is a column (or a


combination of columns) that uniquely identifies each row
in a table.
 Non-Null: It cannot contain null values.
 One per Table: A table can have only one primary key.
 Purpose: Ensures data integrity by preventing duplicate
records.

Example: Consider a Customers table with


columns CustomerID, CustomerName, and City. CustomerID can be the
primary key as it uniquely identifies each customer.
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(255),
City VARCHAR(255)
)

Foreign Key
 Reference to Primary Key: A foreign key is a column (or
a combination of columns) in one table that refers to the
primary key of another table.
 Relationship: It establishes a link between two tables,
creating a parent-child relationship.
 Multiple per Table: A table can have multiple foreign
keys.
 Purpose: Enforces referential integrity by ensuring that
the values in the foreign key column match existing values
in the referenced primary key column.

Example: Consider an Orders table with


columns OrderID, CustomerID, and OrderDate. CustomerID can be a foreign
key referencing the CustomerID in the Customers table.
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustomerID INT,
OrderDate DATE,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
)

Relationship: In this example, the Orders table is the child table,


and the Customers table is the parent table. The foreign
key CustomerID in the Orders table references the primary
key CustomerID in the Customers table. This relationship ensures that
every order is associated with an existing customer.

Super Key

A Super key is any combination of fields within a table that uniquely identifies each
record within that table.

Candidate Key

A candidate is a subset of a super key. A candidate key is a single field or the least
combination of fields that uniquely identifies each record in the table. The least
combination of fields distinguishes a candidate key from a super key. Every table
must have at least one candidate key but at the same time can have several.
As an example we might have a student_id that uniquely identifies the students in a
student table. This would be a candidate key. But in the same table we might have the
student’s first name and last name that also, when combined, uniquely identify the
student in a student table. These would both be candidate keys.

In order to be eligible for a candidate key it must pass certain criteria.

 It must contain unique values


 It must not contain null values
 It contains the minimum number of fields to ensure uniqueness
 It must uniquely identify each record in the table

Once your candidate keys have been identified you can now select one to be your
primary key

Primary Key

A primary key is a candidate key that is most appropriate to be the main reference key
for the table. As its name suggests, it is the primary key of reference for the table and
is used throughout the database to help establish relationships with other tables. As
with any candidate key the primary key must contain unique values, must never be
null and uniquely identify each record in the table.

As an example, a student id might be a primary key in a student table, a department


code in a table of all departments in an organisation. This module has the code DH3D
35 that is no doubt used in a database somewhere to identify RDBMS as a unit in a
table of modules. In the table below we have selected the candidate key student_id to
be our most appropriate primary key

Primary keys are mandatory for every table each record must have a value for its
primary key. When choosing a primary key from the pool of candidate keys always
choose a single simple key over a composite key.

Foreign Key

A foreign key is generally a primary key from one table that appears as a field in
another where the first table has a relationship to the second. In other words, if we had
a table A with a primary key X that linked to a table B where X was a field in B, then
X would be a foreign key in B.

An example might be a student table that contains the course_id the student is
attending. Another table lists the courses on offer with course_id being the primary
key. The 2 tables are linked through course_id and as such course_id would be a
foreign key in the student table.
Secondary Key or Alternative Key

A table may have one or more choices for the primary key. Collectively these are
known as candidate keys as discuss earlier. One is selected as the primary key. Those
not selected are known as secondary keys or alternative keys.

For example in the table showing candidate keys above we identified two candidate
keys, studentId and firstName + lastName. The studentId would be the most
appropriate for a primary key leaving the other candidate key as secondary or
alternative key. It should be noted for the other key to be candidate keys, we are
assuming you will never have a person with the same first and last name combination.
As this is unlikely we might consider fistName+lastName to be a suspect candidate
key as it would be restrictive of the data you might enter. It would seem a shame to
not allow John Smith onto a course just because there was already another John
Smith.

Simple Key

Any of the keys described before (ie primary, secondary or foreign) may comprise one
or more fields, for example if firstName and lastName was our key this would be a
key of two fields where as studentId is only one. A simple key consists of a single
field to uniquely identify a record. In addition the field in itself cannot be broken
down into other fields, for example, studentId, which uniquely identifies a particular
student, is a single field and therefore is a simple key. No two students would have the
same student number.

Compound Key

A compound key consists of more than one field to uniquely identify a record. A
compound key is distinguished from a composite key because each field, which
makes up the primary key, is also a simple key in its own right. An example might be
a table that represents the modules a student is attending. This table has a studentId
and a moduleCode as its primary key. Each of the fields that make up the primary key
are simple keys because each represents a unique reference when identifying a student
in one instance and a module in the other.

Composite

A composite key consists of more than one field to uniquely identify a record. This
differs from a compound key in that one or more of the attributes, which make up the
key, are not simple keys in their own right. Taking the example from compound key,
imagine we identified a student by their firstName + lastName. In our table
representing students on modules our primary key would now be firstName +
lastName + moduleCode. Because firstName + lastName represent a unique reference
to a student, they are not each simple keys, they have to be combined in order to
uniquely identify the student. Therefore the key for this table is a composite key.
 Candidate Key – A set of attributes which can uniquely identify a
table can be termed as a Candidate Key. A table can have more than
one candidate key, and out of the chosen candidate keys, one key can
be chosen as a Primary Key. In the above example, since EmployeeID,
InsuranceNumber and PanNumber can uniquely identify every tuple,
they would be considered as a Candidate Key.
 Super Key – The set of attributes which can uniquely identify a tuple
is known as Super Key. So, a candidate key, primary key, and a unique
key is a superkey, but vice-versa isn’t true.
 Primary Key – A set of attributes which are used to uniquely identify
every tuple is also a primary key. In the above example, since
EmployeeID, InsuranceNumber and PanNumber are candidate keys,
any one of them can be chosen as a Primary Key. Here EmployeeID is
chosen as the primary key.
 Alternate Key – Alternate Keys are the candidate keys, which are not
chosen as a Primary key. From the above example, the alternate keys
are PanNumber and Insurance Number.
 Unique Key – The unique key is similar to the primary key, but allows
one NULL value in the column. Here the Insurance Number and the Pan
Number can be considered as unique keys.
 Foreign Key – An attribute that can only take the values present as
the values of some other attribute, is the foreign key to the attribute to
which it refers. in the above example, the Employee_ID from the
Employee_Information Table is referred to the Employee_ID from the
Employee_Salary Table.
 Composite Key – A composite key is a combination of two or more
columns that identify each tuple uniquely. Here, the Employee_ID and
Month-Year_Of_Salary can be grouped together to uniquely identify
every tuple in the table.

Constraints in SQL
Introduction
SQL constraints are a collection of rules used on tables in relational
databases to limit the types of data that may be added, changed, or
removed from those tables. By doing this, the information recorded in the
table is guaranteed to be reliable and accurate. After the constraint is set up,
any database operation that doesn't adhere to the restrictions set forth by
the constraint is terminated. We will discuss SQL constraints in this post,
including what they are, the many types that are frequently used, how to
apply them, and how to remove them. But first, let's quickly go through the
main benefits of constraints.
Why Do We Apply SQL Constraints to Tables?
The following is a list of the main reasons why SQL Constraints help us while
creating and managing databases:
 Ensure that bad data is not added to important tables.
 Enforce business logic at the database level.
 Maintain relationship integrity between any number of tables.
 Boost the overall performance of the database.
 Important database rules are documented.
 Maintain uniqueness
Are you sure you're getting this? Is this statement true or false?
Constraints are used to specify restrictions on the data in order to assure the
quality of the data recorded in tables.
Press true if you believe the statement is correct, or false otherwise.
TRUE
FALSE
NOT NULL Constraint
A column may by default contain NULL values. Therefore, a NOT NULL
constraint is utilized in order to solve this problem when necessary. This
constraint states that there can never be a blank cell value for any
row in this column. Typically, this condition is applied to columns that store
data that is extremely necessary to locate and retrieve from a table. The
NOT NULL constraint can be set up either when the table is first created or at
a later time using a MODIFY statement. Below, we can see the syntax for
declaring a NOT NULL Constraint on the Customer_ID column during the
creation of the table, named Customer:
TEXT/X-SQL
1CREATE TABLE Customer (
2 Customer_Id int NOT NULL
3);
The int keyword stands for integer – which means that the fields of this
column only accept integer values. In case we had created the table without
specifying the NOT NULL constraint and would like to add it at a later time,
we can do this by using the ALTER and MODIFY keywords, like so:
TEXT/X-SQL
1ALTER TABLE Customer
2MODIFY Customer_Id int NOT NULL;
UNIQUE Constraint
The UNIQUE constraint states that no cell value in a column may be used
more than once across the whole table. To put it another way, there can be
no duplicate rows in this column of the table. A guarantee for
uniqueness for a column or set of columns is provided by the UNIQUE and
PRIMARY KEY constraints. Let us now create the same table as above, only
this time let’s add another condition that the Customer_Id has to be unique,
apart from not being null:
TEXT/X-SQL
1CREATE TABLE Customer (
2 Customer_Id int NOT NULL UNIQUE
3);
If we’d like to ALTER an already created table, we’d use the ADD keyword this
time instead of the MODIFY one. Let’s take a look:
TEXT/X-SQL
1ALTER TABLE Customer
2ADD Unique(Customer_Id);
CHECK Constraint
All the records in a particular column must adhere to a specified
criterion, and this is where the CHECK constraint comes in. This constraint
is typically used to enforce business logic on values in a column, preventing
the entry of inaccurate data. The CHECK constraint may be specified either
when the table is created or may be added later using an ALTER statement.
Imagine we add a column in our Costumer table which holds information
about the customers’ age. Moreover, we’d like to make sure that all
customers are over 18 years old. Then, we’d write the following query:
TEXT/X-SQL
1CREATE TABLE Customer (
2 Customer_Id int NOT NULL UNIQUE,
3 Age int,
4 CHECK (Age>18)
5);
To create a CHECK constraint on the Age column after the table has been
created, we use the following syntax:
TEXT/X-SQL
1ALTER TABLE Customer (
2ADD CHECK (Age>18)
3);
DEFAULT Constraint
When a record's designated column is left empty, the DEFAULT constraint is
used to establish a default value that must be entered. If no alternative
value is provided, the default value will be appended to all new
records. The DEFAULT constraint can be set either when the table is created
or at a later time via an ALTER statement. In the following example, we
create a column City and whenever a city regarding a specific customer is
not specified, we add the default value, which in our case would be Unknown
City.
TEXT/X-SQL
1CREATE TABLE Customer (
2 Customer_Id int NOT NULL UNIQUE,
3 Age int,
4 City varchar(255) DEFAULT ‘Unknown City’,
5 CHECK (Age>18)
6);
In case the table is already created, use the following query to create a
DEFAULT constraint on the City column:
TEXT/X-SQL
1ALTER TABLE Customer (
2ALTER City SET DEFAULT ‘Unknown City’;
3);
PRIMARY KEY Constraint
PRIMARY KEYS serve as distinct identifiers for each row in a
table. They can be values found in a table's single column or a combination
of the table's several columns. The PRIMARY KEY column needs to
be UNIQUE and cannot be NULL. The primary key in the table's value is a
unique identifier for a specific row in the parent table that links the row to
additional information present in the child table, where the same distinct
identity also exists as a FOREIGN KEY. The PRIMARY KEY constraint can be set
either when the table is created or at a later time using an alter statement.
The following query creates a PRIMARY KEY on the Customer_Id column in
the Customer table.
TEXT/X-SQL
1CREATE TABLE Customer (
2 Customer_Id int NOT NULL UNIQUE,
3 Age int,
4 City varchar(255) DEFAULT ‘Unknown City’,
5 CHECK (Age>18)
6);
If we’d like to add a PRIMARY KEY after the creation of the table, we’d have
to run the following ALTER statement:
TEXT/X-SQL
1ALTER TABLE Customer (
2ADD PRIMARY KEY (Customer_Id);
3);
FOREIGN KEY Constraint
A foreign key is a field in a table that uniquely identifies each row of
another table. A column (or set of columns) in one table that is the
FOREIGN KEY relates to the PRIMARY KEY of another table. The table with
the FOREIGN KEY is referred to as the child table, and the table with
the PRIMARY KEY is referred to as the parent table. The FOREIGN KEY
constraint may be specified either at the time the table is created or may be
added later via an alter statement. Imagine we have a Customer table
created with the constraints explained in the examples above, and another
table called Orders, which keeps track of every order that has been made.
These tables can be seen below:

The Customer_Id is the PRIMARY KEY in the Customer Table. However,


the Customer_Id is a FOREIGN KEY in the Orders Table. In order to create the
Orders table, we run the following SQL query:
TEXT/X-SQL
1CREATE TABLE Orders (
2 Order_Id int NOT NULL UNIQUE,
3 PRIMARY KEY (Order_Id),
4 FOREIGN KEY (Customer_Id) REFERENCES Customer(Customer_Id)
5);
In order to create a FOREIGN KEY in an already created table, use the
following syntax:
TEXT/X-SQL
1ALTER TABLE Customer (
2ADD FOREIGN KEY (Customer_Id) REFERENCES Customer(Customer_Id);
3);
Are you sure you're getting this? Click the correct answer from the
options.

You might also like