0% found this document useful (0 votes)
18 views39 pages

Unit 2 Part 2

Uploaded by

paarthchotani85
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)
18 views39 pages

Unit 2 Part 2

Uploaded by

paarthchotani85
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/ 39

CHAPTER 4

INTRODUCTION TO ER AND
RELATIONAL MODEL

❖ Entity Relationship (ER) Diagram


❖ Integrity Constraints
❖ Mapping of ER Model to Relational Model
❖ Querying Using SQL Commands
❖ Aggregate Functions
INTRODUCTION TO ER AND RELATIONAL MODEL

The Entity-Relationship model defines the conceptual view of a database. ER model works on
the real-world entities. The ER model is best for designing databases and is very simple and easy
to design logical view of data. In ER Model, we disintegrate data into entities, attributes and
setup relationships between entities and this can be represented visually using the ER diagram.
ER Diagram is a visual representation of data that describes how data is related to each other.

Importance of ER Model
• ER Model is plain and simple for designing the structure.
• It saves time.
• Without ER diagrams you cannot make a database structure & write production code.
• It displays the clear picture of the database structure.

Relationship model represents data in the form of relations or tables. Relationship model is the
primary data model, which is used widely used around the world for data storage and
processing. This model is very simple to implement and very easy to process data with storage
efficiency. It consists of:
• Tables: In relationship model, relations are represent in the form of Tables. A table has
rows and columns, where rows represent records and columns represent the attributes.
Employee table is representing the relationship model.
• Tuple: A single row of a table, which contains a single record for that relation is called a
tuple. e.g.; Employee relation given above has 3 tuples.
• Relation Schema : A relation schema describes the relation name (table name),
attributes, and their names. Relational Schema of Employee relation can be represented
as:Emp_id,Emp_name,city,Contact_no. Dept.
• Relation Key: Each row has one or more attributes, known as relation key, which can
identify the row in the relation (table) uniquely.
• Attribute Domain: The possible values an attribute can take in a relation is called its
domain. For Example, domain of contact_no is 10 digits
• NULL Values: Values of some attribute for some tuples may be unknown, missing or
undefined which are represented by NULL.
Employee Table
Emp_id Emp_name City Contact _No. Dept.
101 A Delhi 1234567891 IT
102 B Bombay Null Marketing
103 C Goa 9985641235 Developer

4.1 Entity Relationship (ER) Diagram

It is a graphical representation of an information system. ER diagram shows the relationship


between objects, places, people, events etc. within that system. It is a data modeling technique
which helps in defining the business process. It used for solving the design problems. Following
are the symbols used in ER Diagram:-

Notations Representation Description


Rectangle It represents the Entity.

Ellipse It represents the Attribute.

Diamond It represents the Relationship.

Line It represents the link between attribute


and entity set to relationship set.
Double Rectangle It represents the weak entity.

Composite Attribute It represents composite attribute which


can be divided into subparts.
For eg. Name can be divided into First
Name and Last Name
Multi valued Attribute It represents multi valued attribute
which can have many values for a
particular entity. For eg. Mobile
Number.
Derived Attribute It represents the derived attribute which
can be derived from the value of related
attribute.
Key Attribute It represents key attribute of an entity
which have a unique value in a table.
For eg. Employee → EmpId (Employee
Id is Unique).

Entity
An entity is any singular, identifiable and separate object. Entity either be living or non living
objects but can be easily identifiable. For example, in employee database, employee, managers
and departments can be considered as entities. All the entities have some attributes or properties
that give them their identity. An entity set is a collection of similar types of entities. An entity set
may contain entities with attribute sharing similar values.

Types of Entity

Strong Entity: The strong entity has a primary key. Weak entities are dependent on strong entity.
Its existence is not dependent on any other entity. Strong Entity is represented by a single
rectangle.

Weak Entity: The weak entities in DBMS do not have a primary key and are dependent on the
parent entity. It mainly depends on other entities. Weak Entity is represented by double
rectangle.
S_name
S_roll no Loan_name Loan_date
S_course

Student Borrows Loan

Strong Entity Weak Entity

Fig No. 1 Types of Entity

Attributes
Attributes are the properties of the entities. All attributes have values. For example, an employee
entity may have Empid, emp_name, department and date of hiring as attributes. There exists a
domain or range of values that can be assigned to attributes. For example, a employee name
cannot be a numeric value. It has to be alphabetic.

Types of Attributes
Simple Attribute: Simple attributes are atomic values, which cannot be divided further. For
example, marital status of an employee.

Composite Attribute : Composite attributes are combination of more than one simple attribute.
For example, a employee's complete name may have first_name and last_name.

Derived attribute: Derived attributes are the attributes that do not exist in the physical database,
but their values are derived from other attributes present in the database. For example, age of
employee should not be saved directly in the database, instead it can be derived from
data_of_birth.

Key Attribute : Single-value attributes contain single value. For example – empid.
Null Attribute: It does not have a value and can be left blank, it’s optional can be filled or cannot
be. For example: employee middle name.

Stored Attribute: Attribute that cannot be derived from other attributes are called as stored
attributes. For example: DOB of an employee

Simple Attribute

Derived Attribute
Marital Status
Key Attribute
Age
DOB
Emp_id
Employee
Stored Attribute

Emp_Name Composite Attribute

Emp_F_Name Emp_M_Name Emp_L_Name

NULL Attribute

Fig No. 2 Types of Attribute

Keys
Key is an attribute or collection of attributes that uniquely identifies an entity among entity set.
For example, the empid of a employee makes him/her identifiable among employees.

Types of Keys

Primary Key: It is the first key which identifies a single instance of an entity uniquely. An entity
can contain multiple keys. In the emp table, emp_id can be primary key since it is unique for
each employee and we can even select License_Number and Passport_Number as primary key
since they are also unique. For each entity, selection of the primary key is based on requirement
and developers.

Candidate Key: A minimal super key is called a candidate key. An entity set may have more than
one candidate key. The remaining attributes except for primary key are considered as a candidate
key. The candidate keys are as strong as the primary key. In the emp table, emp_id is best suited
for the primary key and remaining attributes like Passport_Number, and License_Number, etc.
are considered as a candidate key.

Super Key: Super key is a set of an attribute which can uniquely identify a tuple. Super key is a
superset of a candidate key. In the emp table, for (emp_id, emp_name) the name of two
employees can be the same, but their emp_id can't be the same. Hence, this combination can also
be a key. The super key would be emp_id, (emp_id, emp_name), etc.

Foreign Key: Foreign keys are the column of the table which is used as primary key for one table
but acts as a candidate key of another table. In a organization, each employee works in a specific
department, and employee and department are two different entities. So we can't store the
information of the department in the employee table. Therefore we link these two tables through
the primary key of one table. We add the primary key of the dept table, dept_id as a new attribute
in the emp table. Now in the emp table, dept_id is the foreign key, and both the tables are related.

Fig No. 3 Types of Keys


Relationship
The association among entities is called a relationship. For example, an employee works_at a
department, a student enrolls in a course. Here, Works_at and Enrolls are called relationships.

Degree of Relationship
The number of participating entities in a relationship defines the degree of the relationship.
Binary = degree 2
Ternary = degree 3
n-ary = degree n

Cardinality
Cardinality defines the number of entities in one entity set, which can be associated with the
number of entities of other set via relationship set.

Cardinality

One to Many to Many to


One to One
Many One Many
Fig No. 4 Types of Cardinality

One-to-One: In One - to - One Relationship, one entity is related with only one other entity. One
row in a table is linked with only one row in another table and vice versa. For example: A
Country can have only one Capital City.
Country Capital

1 1
Country Have Capital

One to one mapping

Fig No. 5 One to One Cardinality

One-to-Many: In One - to - Many Relationship, one entity is related to many other entities. One
row in a table A is linked to many rows in a table B, but one row in a table B is linked to only
one row in table A. For example: One Department has many Employees.

Department Employee

1 N
Department Have Employee

One to Many mapping

Fig No. 6 One to Many Cardinality

Many-to-One: In Many - to - One Relationship, many entities can be related with only one other
entity. For example: No. of Employee works for Department. Multiple rows in Employee table is
related with only one row in Department table.
Employee Department

N 1
Employee N Have Department

Many to One mapping

Fig No. 6 Many to One Cardinality

Many-to-Many: In Many - to - Many Relationship, many entities are related with the multiple
other entities. This relationship is a type of cardinality which refers the relation between two
entities. For example: Various Books in a Library are issued by many Students.

Book Student

N N
Book N Read By Students

Many to Many mapping

Fig No. 7 Many to Many Cardinality

E-R Diagram Example: Library Management System

Entity Names Attribute Names


Book Id, Title, Isbn, Pages
User Id, Name, Username, Password, Email
Periodical Id, Title Year, Volume, Isbn
Publisher Id, Name
Author Id, Name
Paper Id, Name
Tag Id, Value
Source:https://www.researchgate.net/figure/Entity-relationship-diagram-ERD-for-a-simple-
library-management-system-Entities-are_fig2_258388421

4.2 Integrity Constraints

Integrity constraints are a set of rules. It is used to maintain the quality of information. Integrity
constraints ensure that the data integrity is not affected while insertion, updating, and other
processes have to be performed on the database. These are used to limit the type of data that can
go into a table. An integrity constraint ensures the accuracy, reliability and consistency of the
data in the database. Thus, integrity constraint is used to guard against accidental damage to the
database.
Data integrity is handled in a relational database through the concept of referential integrity.
Constraints can be categorized in two ways:
• The constraints can be specified immediately after the column definition in command.
This is called column-level definition. The column level constraints are applied only to
one column.
• The constraints can be specified after all the columns are defined. This is called table-
level definition. The table level constraints are applied to the whole table.
Integrity
Constraints

Referential
Domain Entity integrity
Integrity Key Constraints
Constraints Constraints
Constraints

Fig No. 8 Integrity Constraints

Domain Constraints
Domain constraints can be defined as the definition of a valid set of values for an attribute. The
data type of domain includes string, character, integer, time, date, currency, etc. The value of the
attribute must be available in the corresponding domain.
Example:

Entity Integrity Constraints


The entity integrity constraint states that primary key value can't be null. This is because the
primary key value is used to identify individual rows in relation and if the primary key has a null
value, then we can't identify those rows. A table can contain a null value other than the primary
key field.
Example:
Referential Integrity Constraints
A referential integrity constraint is specified between two tables. In the Referential integrity
constraints, if a foreign key in Table 1 refers to the Primary Key of Table 2, then every value of
the Foreign Key in Table 1 must be null or be available in Table 2.
Example:
Key Constraints
Keys are the entity set that is used to identify an entity within its entity set uniquely. An entity set
can have multiple keys, but out of which one key will be the primary key. A primary key can
contain a unique and null value in the relational table.
Example:

4.3 Mapping of ER Model to Relational Model

ER Model gives a good overview of entity-relationship diagram, which is easier to understand.


ER diagrams can be mapped to relational schema. There are numerous methods available to
convert ER Diagrams into Relational Schema. ER diagrams mainly consist of:-
• Entity and its attributes
• Relationship, which is association among entities.

Mapping Entity
An entity is a real-world object with some attributes.

Following steps are included to mapping the entity in the ER diagram


• Create table for each entity.
• Entity's attributes should become fields of tables with their respective data types.
• Declare primary key.
Contact_No.
Emp_Name
Address

Emp_Id
Employee Dept

4.4 Querying Using SQL Commands

SQL commands are instructions. It is used to communicate with the database. It is also used to
perform specific tasks, functions, and queries of data. SQL can perform various tasks like create
a table, add data to tables, drop the table, modify the table, set permission for users

Types of SQL Commands

Types of SQL
Command

DDL DML TCL

CREATE SELECT COMMIT

ALTER INSERT ROLLBACK

DROP DELETE

UPDATE

Fig No. 8 Types of SQL Commands


DDL (Data Definition Language): DDL or Data Definition Language actually consists of the
SQL commands that can be used to define the database structure. It is used to create and modify
the structure of database objects in database.DDL changes the structure of the table like creating
a table, deleting a table, altering a table, etc. All the command of DDL are auto-committed that
means it permanently save all the changes in the database. Examples of DDL commands:
• Create: It is used to create a new table in the database.
Syntax:

1. CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);

• Drop: It is used to delete both the structure and record stored in the table.
Syntax:

2. DROP TABLE_NAME ;

• Alter: It is used to alter the structure of the database. This change could be either to
modify the characteristics of an existing attribute or probably to add a new attribute.
Syntax:

3. ALTER TABLE table_name ADD column_name COLUMN-definition;


4. ALTER TABLE MODIFY(COLUMN DEFINITION....);

DML(Data Manipulation Language) : DML commands are used to modify the database. It is
responsible for all form of changes in the database. Examples of DML:
• Select: This command is used to fetch the data from the database. It is used to select the
attribute based on the condition described by WHERE clause.
Syntax:
1. SELECT expressions
2. FROM TABLES
3. WHERE conditions;
• Insert: The INSERT statement is a SQL query. It is used to insert data into the row of a
table.
Syntax:

1. INSERT INTO TABLE_NAME


2. (col1, col2, col3,.... col N)
3. VALUES (value1, value2, value3, .... valueN);

• Update: This command is used to update or modify the value of a column in the table.
Syntax:

1. UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHER


E CONDITION]

• Delete: It is used to remove one or more row from a table.


Syntax:

DELETE FROM table_name [WHERE condition];

TCL(Transaction Control Language): TCL commands deals with the transaction within the
database. TCL commands can only use with DML commands like INSERT, DELETE and
UPDATE only. These operations are automatically committed in the database that's why they
cannot be used while creating tables or dropping them. Here are some commands that come
under TCL:
Commit: Commit command is used to save all the transactions to the database.
Syntax:

1. COMMIT;
Rollback: Rollback command is used to undo transactions that have not already been saved to
the database.
Syntax:

1. ROLLBACK;

Create Table
Insert Row in a Table
Retrive Data From Table Using Select Command
Remove Data from Table Using Delete Command

Updating Contents in Existing Table


Modify The Structure of Table With Alter Command
4.5 Aggregate Functions

Aggregate Functions are all about performing calculations on multiple rows of a single column
of a table and returning a single value. In database management an aggregate function is a
function where the values of multiple rows are grouped together as input on certain criteria to
form a single value of more significant meaning. Aggregate function are used because Top levels
managers are usually interested in knowing whole figures and not necessary the individual
details.

Various Aggregate Functions


• COUNT()
• SUM()
• AVERAGE()
• MIN()
• MAX()
Now let us understand each Aggregate function with a example:
EMP_ID Name Salary
101 RAM null
102 RAMESH 5000
103 GARIMA 6000
104 KARISHMA 5000
105 PANKAJ 4000
106 DEV 7000

COUNT Function
The COUNT function returns the total number of values in the specified field. It works on both
numeric and non-numeric data types.
Count(*): Returns total number of records .i.e 6.
Count(salary): Return number of Non Null values over the column salary. i.e 5.
Count(Distinct Salary): Return number of distinct Non Null values over the column salary .i.e 4

SUM Function
Suppose we want a report that gives total amount of payments made so far. We can use the
MySQL SUM function which returns the sum of all the values in the specified column. SUM
works on numeric fields only. Null values are excluded from the result returned.
sum(salary): Sum all Non Null values of Column salary i.e., 27000
sum(Distinct salary): Sum of all distinct Non-Null values i.e., 22000

AVG Function
MySQL AVG function returns the average of the values in a specified column. Just like the
SUM function, it works only on numeric data types.
Avg(salary) = Sum(salary) / count(salary) = 27000/5=5400
Avg(Distinct salary) = sum(Distinct salary) / Count(Distinct Salary) = 22000/4=5500

MIN Function
The MIN function returns the smallest value in the specified table field.
Min(salary): Minimum value in the salary column except NULL i.e., 4000.

MAX Function
Just as the name suggests, the MAX function is the opposite of the MIN function. It returns the
largest value from the specified table field.
Max(salary): Maximum value in the salary i.e., 7000
SUMMARY

• The Entity-Relationship model defines the conceptual view of a database. ER model


works on the real-world entities.
• Relationship model represents data in the form of relations or tables. Relationship model
is the primary data model, which is used widely used around the world for data storage
and processing.
• ER diagram shows the relationship between objects, places, people, events etc. within
that system. It is a data modeling technique which helps in defining the business process.
• An entity is any singular, identifiable and separate object. Entity either be living or non
living objects but can be easily identifiable.
• Attributes are the properties of the entities. All attributes have values.
• Key is an attribute or collection of attributes that uniquely identifies an entity among
entity set.
• The association among entities is called a relationship. For example, an
employee works_at a department, a student enrolls in a course.
• Cardinality defines the number of entities in one entity set, which can be associated with
the number of entities of other set via relationship set.
• An integrity constraint ensures the accuracy, reliability and consistency of the data in the
database. Thus, integrity constraint is used to guard against accidental damage to the
database.
• SQL can perform various tasks like create a table, add data to tables, drop the table,
modify the table, set permission for users
• In database management an aggregate function is a function where the values of multiple
rows are grouped together as input on certain criteria to form a single value of more
significant meaning.
• Aggregate function are used because Top levels managers are usually interested in
knowing whole figures and not necessary the individual details.
REVIEW QUESTIONS

Q1 What is ER diagram? Discuss its importance.


Q2 Explain various symbols used to design ER diagram.
Q3 What is an entity? Explain its types.
Q4 What is an attribute? Discuss its various types.
Q5 Discuss different types of keys present in database.
Q6 What is cardinality? Explain its types along with suitable examples.
Q7 Discuss various integrity constraints.
Q8 Differentiate between entity and referential integrity constraint.
Q9 Define SQL.
Q10 Explain different types of SQL commands along with syntax and example.
Q11 Create table customer with fields: CID, Lname,Fname,city,Pin,State and perform the
following:-
• Insert 5 rows each using all the three methods(All Fields, Selected Fields and User
interactive)
• Display the contents of Customer Table
• Display CID and Fname of customers
• Display Fname,Lname and state of all the Customers
• Display all records from the customer table where state is Delhi
• Select records of customer from Delhi having name Rajiv.
• Display records of customer from state delhi or Karnataka
• Display details of Customer with CID=98
• Display details of Customer except the customer with CID=98
• Retrieve all rows where CID is between 98 and 100(both numbers included)
• Display those rows where stste name begins with ‘D’
• Retrieve all rows where first name contains the word’RAJ’
• Retrieve all rows where name field contains the word’RA ESH’
• Retrieve all rows where city is Delhi, Karnataka or Banglore
• Delete all those rows of customers who stay in Banglore
• Delete those customers who do not have Pin Code.
• Rename column city to address
• Delete the customers who do not belong to Banglore.

You might also like