Professional Documents
Culture Documents
DBMS (Unit II)
DBMS (Unit II)
DBMS (Unit II)
o ER model stands for an Entity-Relationship model. This model is used to define the
data elements and relationship for a specified system.
o In ER modelling, the database structure is portrayed as a diagram called an entity-
relationship diagram.
For example, Suppose we design a school database. In this database, the student will be an
entity with attributes like address, name, id, age, etc. The address can be another entity with
attributes like city, street name, pin code, etc and there will be a relationship between them.
Components of ER Diagram
1. Attribute
The attribute is used to describe the property of an entity. Ellipse is used to represent an
attribute.
Types of Attributes:
For example, id, age, contact number, name, etc. can be attributes of a student entity.
1. Key Attribute
The key attribute is used to represent the main characteristics of an entity. It represents a
primary key. The key attribute is represented by an ellipse with the text underlined.
Key attributes are those attributes which can identify an entity uniquely in an entity set.
Example-
2. Simple Attribute:
An attribute that cannot be further subdivided into components is a simple attribute.
Simple attributes are those attributes which cannot be divided further.
Here, all the attributes are simple attributes as they cannot be divided further.
3. Single-valued Attribute:
The attribute which takes up only a single value for each entity instance is a single-valued
attribute.
Example: The age of a student.
Single valued attributes are those attributes which can take only one value for a given entity
from an entity set.
Example-
Here, all the attributes are single valued attributes as they can take only one specific value for
each entity.
4. Composite Attribute
Composite attributes are those attributes which are composed of many other simple attributes.
Example-
Here, the attributes “Name” and “Address” are composite attributes as they are composed of
many other simple attributes.
The composite attribute is represented by an ellipse, and those ellipses are connected with an
ellipse.
5. Multivalued Attribute
An attribute can have more than one value. These attributes are known as a multivalued
attribute. The double oval is used to represent multivalued attribute.
For example, a student can have more than one phone number
Example-
Here, the attributes “Mob_no” and “Email_id” are multi valued attributes as they can take
more than one values for a given entity.
6. Derived Attribute
An attribute that can be derived from other attribute is known as a derived attribute. It can be
represented by a dashed ellipse.
For example, A person's age can be derived from another attribute like Date of birth.
Entity:
An entity may be any object, class, person or place. In the ER diagram, an entity can be
represented as rectangles.
a. Weak Entity
An entity that depends on another entity called a weak entity. The weak entity doesn't contain
any key attribute of its own. The weak entity is represented by a double rectangle.
A relationship is used to describe the relation between entities. Diamond or rhombus is used to
represent the relationship.
a. One-to-One Relationship
When only one instance of an entity is associated with the relationship, then it is known as one
to one relationship.
• Country - capital city: Each country has exactly one capital city. Each capital city is
the capital of exactly one country.
• Person - their fingerprints. Each person has a unique set of fingerprints. Each set of
fingerprints identifies exactly one person.
When a single instance of an entity is associated with a single instance of another entity then it
is called one to one relationship. For example, a person has only one passport and a passport is
given to one person.
b. One-to-many relationship
When only one instance of the entity on the left, and more than one instance of an entity on the
right associates with the relationship then this is known as a one-to-many relationship.
When a single instance of an entity is associated with more than one instances of another entity
then it is called one to many relationship. For example – a customer can place many orders but
a order cannot be placed by many customers.
c. Many-to-one relationship
When more than one instance of the entity on the left, and only one instance of an entity on the
right associates with the relationship then it is known as a many-to-one relationship.
When more than one instances of an entity is associated with a single instance of another entity
then it is called many to one relationship. For example – many students can study in a single
college but a student cannot study in many colleges at the same time.
d. Many-to-many relationship
When more than one instance of the entity on the left, and more than one instance of an entity
on the right associates with the relationship then it is known as a many-to-many relationship.
For example, Employee can assign by many projects and project can have many employees.
When the entity types ‘Customer’ and ‘Product’ are combined, each customer can purchase
several products, and a product can be purchased by multiple customers.
When more than one instances of an entity is associated with more than one instances of another
entity then it is called many to many relationship. For example, a can be assigned to many
projects and a project can be assigned to many students.
Connectivity of a Relationship –
It means how many instances of one entity type are linked with how many entity
of another entity set. Different types of connectivity of a relationship are –
Type – 1
(B) many-to-one relationship – If this relationship is many-to-one, i.e. many
customers can share one account then this is represented as follows.
Type – 2
(C) one-to-many relationship – If the relationship is one-to-many, i.e. one
customer may have any number of accounts, but one account belongs to only one
customer then this cardinality is represented as –
Type – 3
(D) many-to-many relationship – If relationship is many-to-many, i.e. one
customer may have any number of accounts and one acco unt can be shared by
any number of customers, then this is represented as follows.
Type – 4
1. Hospital ER Model
This is an ER model of a Hospital. The entities are represented in rectangular boxes and are
Patient, Tests and Doctor.
Each of these entities have their respective attributes which are −
• Patients - ID(primary key), name, age, visit_date
• Tests- Name(primary key), date, result
• Doctor- ID(primary key), name, specialization
The relationships between different entities are represented by a diamond shaped box.
2. Company ER Model
The entities in this ER model are Employee, Department and Project. These entities have the
following attributes −
• Employee - ENO(Primary Key) , Name, Salary
• Department - DNO(Primary key), Name, Locations
• Project - PNO(Primary key), Name
The relationships in this ER model are represented as Works for and Controls.
o A mapping constraint is a data constraint that expresses the number of entities to which
another entity can be related via a relationship set.
o For binary relationship set R on an entity set A and B, there are four possible mapping
cardinalities. These are as follows:
1. One to one (1:1)
2. One to many (1:M)
3. Many to one (M:1)
4. Many to many (M:M)
One-to-one
In one-to-one mapping, an entity in E1 is associated with at most one entity in E2, and an entity
in E2 is associated with at most one entity in E1.
One-to-many
In one-to-many mapping, an entity in E1 is associated with any number of entities in E2, and
an entity in E2 is associated with at most one entity in E1.
Many-to-one
In many-to-one mapping, an entity in E1 is associated with at most one entity in E2, and an
entity in E2 is associated with any number of entities in E1.
Many-to-many
In many-to-many mapping, an entity in E1 is associated with any number of entities in E2, and
an entity in E2 is associated with any number of entities in E1.
Keys
For example, ID is used as a key in the Student table because it is unique for each student. In
the PERSON table, passport_number, license_number, SSN are keys since they are unique for
each person.
Types of keys:
1. Primary Key
2. Candidate Key
3. Super Key
4. Foreign Key
5. Alternate Key
6. Composite Key
1. 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.
2. Candidate key
o A candidate key is an attribute or set of attributes that can uniquely identify a tuple
(row).
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.
3. Super Key
Super key is an attribute set that can uniquely identify a tuple (row). A super key is a superset
of a candidate key.
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.
DEPARTMENT
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.
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.
Generalization
For example, Faculty and Student entities can be generalized and create a higher level entity
Person.
Specialization
o Specialization is a top-down approach, and it is opposite to Generalization. In
specialization, one higher level entity can be broken down into lower level entities.
o The superclass is defined first, the subclass and its related attributes are defined next,
and relationship set are then added.
Aggregation
In aggregation, the relation between two entities is treated as a single entity. In aggregation,
relationship with its corresponding entities is aggregated into a higher level entity.
Example:
The above entity relationship diagram consists of, the Employee, a project, and a manager. The
above ER diagram also has two relationship boxes - they are "Builds" and "Manages". The
manager manages the employee and the project. This is called aggregation. In the above figure,
the Employee and the Project are connected to the "builds" operation. This builds operation is
connected to the "manages" operation that represents the aggregation function.
The "manages" operation is then connected to the new entity called as Manager entity.
Now if we compare the two cases we discussed above, in the first case we can say that the
student can have only one student id, however in the second case when we chose student id as
an entity it implied that a student can have more than one student id.
Let’s take an example to understand it better: A person takes a loan from a bank, here we have
two entities person and bank and their relationship is loan. This is fine until there is a need to
disburse a joint loan, in such case a new relationship needs to be created to define the
relationship between the two individuals who have taken joint loan. In this scenario, it is better
to choose loan as an entity set rather than a relationship set.
The n-ary relationships can make ER design complex, however the good news is that we can
convert and represent any n-ary relationship using multiple binary relationships.
This may sound confusing so let’s take an example to understand how we can convert an n-ary
relationship to multiple binary relationships. Now let’s say we have to describe a relationship
between four family members: father, mother, son and daughter. This can easily be represented
in forms of multiple binary relationships, father-mother relationship as “spouse”, son and
daughter relationship as “siblings” and father and mother relationship with their child as
“child”.
4. Placing Relationship Attributes
The cardinality ratio in DBMS can help us determine in which scenarios we need to place
relationship attributes. It is recommended to represent the attributes of one to one or one to
many relationship sets with any participating entity sets rather than a relationship set.
Let’s take an example: Here we have an entity set Employee with the attributes Name, Age,
Emp_Id and Salary. When we convert this ER diagram to table, the entity set becomes table so
we have a table named “Employee” as shown in the following diagram. The attributes of the
entity set becomes the attributes of the table.
Now we will see how to convert Strong entity set with composite attributes ER to table.
The entity set will be the table and the simple attributes of the composite attributes will
become the attributes of the table while the composite attribute itself will be ignored
during conversion.
Let’s take an example. As you can see we have a composite attribute Name and this
composite attribute has two simple attributes First_N and Last_N. While converting
this ER to table we have not used the composite attribute itself in the table instead we
have used the simple attributes of this composite attribute as table’s attributes.
Entity set with multi-valued attributes will require two tables in the relational model.
We will understand this conversion with the help of a diagram. Let’s take the same
example that we have seen above, here we have added a new multi-valued
attribute Dept. An employee can work in multiple department so we have
this Dept attribute marked as multi-valued. Whenever we have a multi-valued attribute,
there needs to be more than one table to represent the ER diagram. As you can see we
have created two tables to represent this ER.
In the following example, we have two entity sets Employee and Department. These entity sets
are associated to each other using the Works relationship set. To convert this relationship
set Works to the table, we take the primary attributes of each entity set, these
are Emp_Id and Dept_Id and all the attributes of the relationship set and form a table.
Table Name: Employee
Example
The database can be represented using the notations, and these notations can be reduced to a
collection of tables.
In the database, every entity set or relationship set can be represented in tabular form.
There are some points for converting the ER diagram to the table:
o Entity type becomes a table.
In the given ER diagram, LECTURE, STUDENT, SUBJECT and COURSE forms individual
tables.
In the student table, a hobby is a multivalued attribute. So it is not possible to represent multiple
values in a single column of STUDENT table. Hence we create a table STUD_HOBBY with
column name STUDENT_ID and HOBBY. Using both the column, we create a composite key.
In the given ER diagram, student address is a composite attribute. It contains CITY, PIN,
DOOR#, STREET, and STATE. In the STUDENT table, these attributes can merge as an
individual column.
In the STUDENT table, Age is the derived attribute. It can be calculated at any point of time
by calculating the difference between current date and Date of Birth.
Using these rules, you can convert the ER diagram to tables and columns and assign the
mapping between the tables. Table structure for the given ER diagram is as below:
Figure: Table structure
SQL
Group functions operate on sets of rows to give one result per group
Syntax:
Select column, groupfunction(column)
From table
[Where condition]
Name Datatype Remark
EmpNo Number(10) Not Null
EmpName Varchar(10)
DeptNo Number(10)
Designation Varchar(10)
Salary Number(10)
Contact Number(10)
Example:
Find total salary paid to employees.
SQL> select sum(salary) from empl;
output
SUM(SALARY)
-------------
3775
3. SQL avg() Function
The AVG() function returns the average value of a numeric column.
Syntax:
SQL>select avg(column-name) from table_name;
Example:
Find average salary of the Employees
SQL> select avg(salary) from emp;
output
AVG(SALARY)
----------
7725
1. SQL Min() Function
The Min() function returns the smallest value of the selected column.
Syntax:
SQL>select min(column-name) from table_name;
Example:
Find minimum salary of the Employees
SQL> select min(salary) from emp;
output
MIN(SALARY)
----------
6000
The Max() function returns the largest value of the selected column.
Syntax:
SQL>select max(column-name) from table_name;
Example:
Find the max salary paid to a clerk
SQL> select max(salary) from empl where designation='clerk';
output
MAX(SALARY)
----------
800
Nested Queries
A nested query is a query that has another query embedded within it. The embedded query is
called a subquery.
A subquery appears within the WHERE clause of a query.
Syntax:
Select select-list from table
Where conditional-exp (select select-list from tablename);
The subquery (inner query) executes once before the main query. The result of the subquery is
used by the main query (outer query).
Example:
List the ename, job, sal of the employee who get minimum salary in the company.
SQL> select ename, job, sal from emp where sal=(select min(sal) from emp);
ENAME JOB SAL
------------------------- --------------- ----------
Smith clerk 800
VIEWS IN SQL
SQL View is a virtual table based on the result-set of an SQL statement. A view contains rows
and columns, just like a real table. The fields in a view are fields from one or more real tables in the
database.
A view is actually a composition of a table in the form of a predefined SQL query. A view can
contain all rows of a table or select rows from a table. A view can be created from one or many tables
which depends on the written SQL query to create a view.
Creating Views:
Database views are created using the CREATE VIEW statement. Views can be created from a single
table, multiple tables, or another view.
To create a view, a user must have the appropriate system privilege according to the specific
implementation.
FROM table_name
WHERE [condition];
You can include multiple tables in your SELECT statement in very similar way as you use them in
normal SQL SELECT query.
Example:
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
Now, following is the example to create a view from CUSTOMERS table. This view would be used
to have customer name and age from CUSTOMERS table:
FROM CUSTOMERS;
Now, you can query CUSTOMERS_VIEW in similar way as you query an actual table. Following is
the example:
+----------+-----+
| name | age |
+----------+-----+
| Ramesh | 32 |
| Khilan | 25 |
| kaushik | 23 |
| Chaitali | 25 |
| Hardik | 27 |
| Komal | 22 |
| Muffy | 24 |
Updating a View:
A view can be updated under certain conditions:
So if a view satisfies all the above-mentioned rules then you can update a view. Following is an
example to update the age of Ramesh:
SET AGE = 35
WHERE name='Ramesh';
This would ultimately update the base table CUSTOMERS and same would reflect in the view itself.
Now, try to query base table, and SELECT statement would produce the following result:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
This would delete a row from the base table CUSTOMERS and same would reflect in the view itself.
Now, try to query base table, and SELECT statement would produce the following result:
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
Dropping Views:
Drop the view if it is no longer needed. The syntax is very simple as given below: