0% found this document useful (0 votes)
16 views26 pages

Unit-3

Uploaded by

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

Unit-3

Uploaded by

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

UNIT-III

Entity Relationship Model: Introduction, Representation of entities, attributes, entity set,


relationship, relationship set, constraints, sub classes, super class, inheritance,
Generalization/specialization, Aggregation.
SQL: Creating tables with relationships, implementation of key and integrity constraints,
nested queries, sub queries, grouping, aggregation, ordering, implementation of different
types of joins, views(updatable and non-updatable), relational set operations.

ER model stands for an Entity-Relationship model. It is a high-level data model. This model is
used to define the data elements and relationship for a specified system. It develops a
conceptual design for the database.
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.

Graphical Notations to develop ER Diagram:


Entity:
An Entity may be an object with a physical existence – a particular person, car, house, or
employee.
In the ER diagram, an entity can be represented as rectangles.

Entity Set:

An Entity is an object of Entity Type and a set of all entities is called as an entity set.
e.g.; E1 is an entity having Entity Type Student and set of all students is called Entity Set.
Attribute(s):

Attributes are the properties that define the entity type. For example, Roll_No, Name, DOB,
Age, Address, Mobile_No are the attributes that define entity type (E1, E2, E3) Student. In ER
diagram, the attribute is represented by an oval.

1. Key Attribute:
The attribute which uniquely identifies each entity in the entity set is called key attribute.
For example, Roll_No will be unique for each student. In ER diagram, key attribute is
represented by an oval with underlying lines.

2. Composite Attribute:
An attribute composed of many other attribute is called as composite attribute. For example,
Address attribute of student Entity type consists of Street, City, State, and Country. In ER
diagram, composite attribute is represented by an oval comprising of ovals.
3. Multivalued Attribute:
An attribute consisting more than one value for a given entity. For example, Phone_No (can
be more than one for a given student). In ER diagram, a multivalued attribute is represented
by a double oval.

4. Derived Attribute –
An attribute that can be derived from other attributes of the entity type is known as a
derived attribute. e.g.; Age (can be derived from DOB). In ER diagram, the derived attribute
is represented by a dashed oval.

The complete entity type Student with its attributes can be represented as:
Relationship Type and Relationship Set:

Relationship Type:

A relationship type represents the association between entity types. For example, ‘Enrolled
in’ is a relationship type that exists between entity type Student and Course. In ER diagram,
the relationship type is represented by a diamond and connecting the entities with lines.

Relationship Set:
A set of relationships of the same type is known as a relationship set. The following
relationship set depicts S1 as enrolled in C2, S2 is enrolled in C1, and S3 is enrolled in C3.

Degree of a relationship set:

1. Unary Relationship –
When there is only ONE entity set participating in a
relation, the relationship is called a unary relationship. For
example, one person is married to only one person.

2. Binary Relationship –
When there are TWO entities set participating in a relationship, the relationship is called a
binary relationship. For example, a Student is enrolled in a Course.

3. n-ary Relationship –
When there are n entities set participating in a relation, the relationship is called an an n-ary
relationship.
Constraints
Constraints are used for modeling limitations on the relations between entities.
Various types of constraints on the Entity Relationship (ER) model −

● Mapping cardinality or cardinality ratio.

● Key Constraints

● Participation constraints

Mapping Cardinality

It is expressed as the number of entities to which another entity can be associated via a
relationship set.
For binary relationship set there are entity set A and B then the mapping cardinality can be
one of the following −
● One-to-one
● One-to-many
● Many-to-one
● Many-to-many
One-to-one relationship
One entity of A is associated with one entity of B.
We express cardinality constraints by drawing either a directed line (→), signifying “one,”
or an undirected line (—), signifying “many,” between the relationship set and the entity
set.

One-to-one relationship between an instructor and a student :


• A student is associated with at most one instructor via the relationship advisor
• A student is associated with at most one department via stud_dept

One-to-many relationship
An entity set A is associated with any number of entities in B with a possibility of zero and
entity in B is associated with at most one entity in A

one-to-many relationship between an instructor and a student


• an instructor is associated with several (including 0) students via advisor
• a student is associated with at most one instructor via advisor,
Many-to-one relationship
An entity set A is associated with at most one entity in B and an entity set in B can be
associated with any number of entities in A with a possibility of zero.

In a many-to-one relationship between an instructor and a student,


• an instructor is associated with at most one student via advisor,
• and a student is associated with several (including 0) instructors via advisor

Many-to-many relationship
Many entities of A are associated with many entities of B.
An entity in A is associated with many entities of B and an entity in B is associated with many
entities of A.
An instructor is associated with several (possibly 0) students via advisor
▪ A student is associated with several (possibly 0) instructors via advisor

Types of keys:(Key Constraints)


1. Primary key

● It is a key which uniquely identifies a Tuple.

● 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.


2. Candidate key

● A candidate key is an attribute or set of attributes that can uniquely identify a

tuple.

● 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. 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.

4. Foreign key

● Foreign keys are the column of the table used to point to the primary key of

another table.

● 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.

● We add the primary key of the DEPARTMENT table, Department_Id, as a new

attribute in the EMPLOYEE table.


● In the EMPLOYEE table, Department_Id is the foreign key, and both the tables are

related.

5. 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.

Entity Relationship Participation in Database (Participation constraints)

In a Relationship, Participation constraint specifies the existence of an entity when it is


related to another entity in a relationship type. It is also called minimum cardinality
constraint.

There are two types of Participation constraint −

Total Participation
Each entity in the entity set is involved in at least one relationship in a relationship set
i.e. the number of relationship in every entity is involved is greater than 0.

Consider two entities Employee and Department related via Works_For relationship.
Now, every Employee works in at least one department therefore an Employee entity
exist if it has at least one Works_For relationship with Department entity. Thus the
participation of Employee in Works_For is total relationship.Total Participation is
represented by double line in ER diagram.

Partial Participation
Each entity in entity set may or may not occur in at least one relationship in a
relationship set.

For example: Consider two entities Employee and Department and they are related to
each other via Manages relationship. An Employee must manage a Department, he or she
could be the head of the department. But not every Employee in the company manages
the department. So, participation of employee in the Manages relationship type is partial
i.e. only a particular set of Employees will manage the Department but not all.

Subclasses, Superclasses, and Inheritance:

Enhanced Entity Relationship Model contains all the features of the Entity Relationship
model. In addition to all that, it also contains features of Subclasses, Superclasses and
Inheritance.
Subclasses
A subclass is a class derived from the superclass. It inherits the properties of the superclass
and also contains attributes of its own.

Car, Truck and Motorcycle are all subclasses of the superclass Vehicle. They all inherit
common attributes from vehicle such as speed, colour etc. while they have different
attributes also i.e Number of wheels in Car is 4 while in Motorcycle is 2.

Superclasses
A superclass is the class from which many subclasses can be created. The subclasses inherit
the characteristics of a superclass. The superclass is also known as the parent class or base
class.

Inheritance
Inheritance is basically the process of basing a class on another class i.e to build a class on a
existing class. The new class contains all the features and functionalities of the old class in
addition to its own.

Additional Features of ER Diagram


Generalization and Specialization
Generalization and specialization are the Enhanced Entity Relationship diagram (EER-
diagram)
1. Generalization :
It works on the principle of bottom up approach. In Generalization lower level functions are
combined to form higher level function which is called as entities. This process is repeated
further to make advanced level entities.
In the Generalization process properties are drawn from particular entities and thus we can
create generalized entity. We can summarize the Generalization process as it combines
subclasses to form superclass.
Example of Generalization –
Consider two entities Student and Patient. These two entities will have some characteristics
of their own. For example Student entity will have Roll_No, Name and Mob_No while
patient will have PId, Name and Mob_No characteristics. Now in this example Name and
Mob_No of both Student and Patient can be combined as a Person to form one higher level
entity and this process is called as Generalization Process.

2. Specialization :

We can say that Specialization is opposite of Generalization. In Specialization things are


broken down into smaller things to simplify it further. We can also say that in Specialization a
particular entity gets divided into sub entities and it’s done on the basis of it’s characteristics.
Also in Specialization Inheritance takes place.

Example of Specialization –

Consider an entity Account. This will have some attributes consider them Acc_No and
Balance. Account entity may have some other attributes like Current_Acc and Savings_Acc.
Now Current_Acc may have Acc_No, Balance and Transactions while Savings_Acc may have
Acc_No, Balance and Interest_Rate henceforth we can say that specialized entities inherits
characteristics of higher level entity.
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.
For example: Center entity offers the Course entity act as a single entity in the relationship
which is in a relationship with another entity visitor. In the real world, if a visitor visits a
coaching center then he will never enquiry about the Course only or just about the Center
instead he will ask the enquiry about both.

Weak Entity Sets:

The entity sets which do not have sufficient attributes to form a primary key are known
as weak entity sets and the entity sets which have a primary key are known as strong entity
sets.

As the weak entities do not have any primary key, they cannot be identified on their own, so
they depend on some other entity (known as owner entity). The weak entities have
total participation constraint (existence dependency) n its identifying relationship with
owner identity. Weak entity types have partial keys. Partial Keys are set of attributes with
the help of which the tuples of the weak entities can be distinguished and identified.
Example:

In the below ER Diagram, ‘Payment’ is the weak entity. ‘Loan Payment’ is the identifying
relationship and ‘Payment Number’ is the partial key. Primary Key of the Loan along with
the partial key would be used to identify the records.

Hospital Management System


SQL: Creating tables with relationships, implementation of key and integrity constraints, nested
queries, sub queries, grouping, aggregation, ordering, implementation of different types of joins,
views(updatable and non-updatable), relational set operations

Consider two tables student and faculty.The relation between these two tables is faculty teaches
students.
Table 1(Faculty) creation
Create table Faculty(fid number(3),fname varchar2(10),subject varchar2(10) primary key(fid));
Table2(student)creation
Create table Student(sid number(10),sname varchar2(10),subject varchar2(10) primary
key(sid) );
Relationship table
Create table Teaches(fid number(3),sid number(10),subject varchar2(5), foreign key(fid)
references faculty(fid),foreign key(sid) references student(sid),Primary key(fid,sid));

● SQL stands for Structured Query Language. It is used for storing and managing
data in relational database management system (RDMS).
● It is a standard language for Relational Database System. It enables a user to
create, read, update and delete relational databases and tables.
● All the RDBMS like MySQL, Informix, Oracle, MS Access and SQL Server use
SQL as their standard database language.
● SQL allows users to query the database in a number of ways, using English-like
statements.

Schema contains valuable information such as:


● The title of each table
● The fields that each table contains
● The relations between tables (e.g. linking an employee’s overtime pay to their identity
via their ID
Table Name: Users
Attributes: ID, Full Name, Email, Date of Birth, Department
Nested queries

1. Create three tables with the following schema

Sailors(sid:integer, sname:string, rating:integer, age:real)

Boats(bid:integer, bname:string, color:string)

Reserves(sid:integer, bid:integer, day:date)

Impose the appropriate integrity constraints.

Example:

SELECT sname FROM sailors WHERE s.sid = (SELECT DISTINCT r.sid from reserves
r WHERE s.sid=r.sid);

This nested query displays the names of sailors who have reserved at least one boat.

Sub queries/Correlated nested queries


Example: - Find the names of sailors who have not reserved boat number 103.

SELECT S.SNAME FROM SAILORS S WHERE NOT EXISTS (SELECT * FROM


RESERVES R WHERE R.BID = 103 AND R.SID = S.SID);

Aggregate Operators: that take a collection of values as input and return a single value.

SQL offers five built-in aggregate functions.

❖ MIN (A) : returns minimum of column values

❖ MAX (A) : returns maximum of column values

❖ AVG ([ distinct] A) : returns average of unique column values

❖ SUM ([ distinct] A) : returns total of unique column values

❖ COUNT ([ distinct] A) : returns number of unique column values

The input to SUM and AVG must be a collection of numbers but the other operators can operate
on

collection of non -numeric data types like strings.

For example,

select sum(rating) from sailors; displays total rating of all the sailors.

select count(sid) from sailors; displays no. of sailors.


select count (*) from sailors; displays no. of records in sailors.

All the functions except COUNT (*) ignore null values in their input collection. For SQL null
value means

unknown or inapplicable.

group by & having Clauses:

The select statement syntax including optional group by and having clauses is as under:

select [distinct ] select-list from from-list

[where qualification ]

[group by group-list ]

[having group-qualification];

The result of the GROUP BY clause is a grouped table i.e., a set of groups of rows derived
from the

table by conceptually rearranging it into the minimum number of groups such that within any
one group

all rows have the same value for the combination of columns identified by GROUP BY clause.

Example

select sum(sal) from emp group by job;

Using this statement, we get the total salary for each designation of the employees. There is a
restriction
on the select clause while using group by. Select item in the select clause must be single valued
per

group as for the other aggregate functions. Therefore, a statement like

select empno, sum(sal) from emp group by job;

select * from emp group by job; are invalid.

But we can give

select job from emp group by job;

and

select job, avg(sal) from emp group by job; are valid.

HAVING: clause works very much like a where clause except that its logic is related only to
the result

of group functions i.e., having clause is used to eliminate groups whereas where clause is used
to

eliminate rows from the whole table.

Example

select deptno, avg(sal) from emp group by deptno having max(sal) > 1500;

Displays average salaries depart wise for departments which have average salary greater than
1500.

Order by
The ORDER BY keyword is used to sort the result-set in ascending or descending order.

The ORDER BY keyword sorts the records in ascending order by default. To sort the records
in descending order, use the DESC keyword.

SELECT column1, column2, ...

FROM table_name

ORDER BY column1, column2, ... ASC|DESC;

1.Displays all the sailors according to rating (Topper First), if rating is same then sort according
to age (Older First).

2. Displays all the sailors according to rating (Topper First), if rating is same then sort according
to age (Younger First).

SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.

Different Types of SQL JOINs


the different types of the JOINs in SQL:

● (INNER) JOIN: Returns records that have matching values in both


tables
● LEFT (OUTER) JOIN: Returns all records from the left table, and the
matched records from the right table
● RIGHT (OUTER) JOIN: Returns all records from the right table, and
the matched records from the left table
● FULL (OUTER) JOIN: Returns all records when there is a match in
either left or right table
● eft or right table

Let's look at a selection from the "Orders" table:


OrderID CustomerID OrderDate

10308 2 1996-09-18

10309 37 1996-09-19

10310 77 1996-09-20

Then, look at a selection from the "Customers" table:

CustomerID CustomerName ContactName Country

1 Alfreds Futterkiste Maria Anders Germany

2 Ana Trujillo Emparedados y helados Ana Trujillo Mexico

3 Antonio Moreno Taquería Antonio Moreno Mexico

Notice that the "CustomerID" column in the "Orders" table refers to the "CustomerID" in the
"Customers" table. The relationship between the two tables above is the "CustomerID" column.

Then, we can create the following SQL statement (that contains an INNER JOIN), that selects
records that have matching values in both tables:
Example
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy