What is a Key in Database relation
What is a Key in Database relation
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;
12345678
1 Shyam Delhi
9
22336579
2 Rakesh Kolkata
6
17546896
3 Suraj Delhi
5
12345678
1 Shyam Delhi
9
22336579
2 Rakesh Kolkata
6
17546896
3 Suraj Delhi
5
1 001 C001
2 056 C005
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).
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
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
Hi !
Welcome to the new edition of Business Analytics Review !
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.
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.
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.
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: