Database System - Notes - Unit-2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 26

UNIT II

DATA MODELS

Data models in DBMS help to understand the design at the conceptual, physical, and
logical levels as it provides a clear picture of the data making it easier for developers
to create a physical database.
Data models are used to describe how the data is stored, accessed, and updated in a
DBMS. A set of symbols and text is used to represent them so that all the members of an
organization can understand how the data is organized. It provides a set of conceptual tools
that are vastly used to represent the description of data.

There are many types of data models that are used in the industry, some of them are -

Types of Data Model

Hierarchical Model

The hierarchical data model is one of the oldest data models, developed in
the 1950s by IBM. In this data model, the data is organized in a hierarchical tree-like
structure. This data model can be easily visualized because each record has one parent and
many children (possibly 0) as shown in the image given below.

Vehicle

Two Wheelers Four-wheelers

Bike Scooter Car Tractor Mini-Bus

Sedan SUVs

The above given image represents the data model of the Vehicle database, vehicle are
classified into two types Viz. two-wheelers and four-wheelers and then they are further
classified. The main drawback we can see here is we can only have one to many
relationships under this model, hence the hierarchical data model is very rarely used
nowadays.

Network Model

A network model is nothing but a generalization of the hierarchical data model as this
data model allows many to many relationships therefore in this model a record can also have
more than one parent.
The network model can be represented as a graph and hence it replaces the hierarchical
tree with a graph in which object types are the nodes and relationships are the edges. For
example
College

Department 1 Department 2 Department 3

Director

Here you can see all the three departments are linked with the director which was not
possible in the hierarchical data model. In the network model, there can be many possible
paths to reach a node from the root node (College is the root node in the above case),
therefore the data can be accessed efficiently when compared to the hierarchical data
model. But, on the other hand, the process of insertion and deletion of data is quite complex.

Entity-Relationship model (ER Model)

An Entity-Relationship model is a high-level data model that describes the structure


of the database in a pictorial form which is known as ER-diagram. In simple words, an
ER diagram are used to represent logical structure of the database easily. ER model
develops a conceptual view of the data hence it can be used as a blueprint to implement the
database in the future.
Developers can easily understand the system just by looking at ER diagram. Let's first have
a look at the components of an ER diagram.

 Entity - Anything that has an independent existence about which we collect the
data. They are represented as rectangles in the ER diagram. For example - Car,
house, employee.
 Entity Set - A set of the same type of entities is known as an entity set. For example
- Set of students studying in a college.
 Attributes - Properties that define entities are called attributes. They are
represented by an ellipse shape.
 Relationships - A relationship is used to describe the association between
entities. They are represented as diamond or rhombus shapes in the ER diagram.

Ename Eid DateOfJoin CompRegNo CName

Employee Works in Company

In the above-represented ER diagram, we have two entities that are Employee and
Company and the relationship among them. Also, in the above-represented ER diagram, we
can see that both employee and company have some attributes and the relationship is of
"works in" type, which means employee works in a company.

Relational Model

This is the most widely accepted data model. In this model, the database is represented
as a collection of relations in the form of rows and columns of a two-dimensional
table. Each row is known as a tuple (a tuple contains all the data for an individual record)
while each column represents an attribute. For example -

Stu. Id Name Branch


101 Ram CSE
102 Priya ECE
103 Krishna IT
104 Michael ME

The above table shows a relation "STUDENT" with attributes as Stu. Id, Name, and Branch
which consists of 4 records or tuples.

Object-Oriented Data model

As suggested by its name, the object-oriented data model is a combination of object-oriented


programming, and relational data model. In this data model, the data and their relationship
are represented in a single structure which is known as an object. Since data is stored as
objects we can easily store audio, video, images, etc in the database which was very
difficult and inconvenient to do in the relational model. As shown in the image below two
objects are connected with each other through links.

Employee (Object) Department (Object)

EName=”Ram” DeptId=”D101”

Eid=101 DeptName=”Software”

Gender=’M’ AddDept()

AddEmployee() UpdateDept()

UpdateEmployee()

Attributes/ Data Members

Member Functions

In the above image, we have two objects that are Employee and Department in which all the
data is contained in a single unit (object). They are linked with each other as they share a
common attribute �.�.i.e. Department_Id.

Object Relational Data Model


Again as suggested by its name, the object-relational data model is an integration of the
object oriented model and the relational model. Since it inherits properties from both of the
models it supports objects, classes, etc like object oriented model and tabular structures like
the relational model.

It provides data structures and operations used in the relational model and also provides
features of object oriented models like classes, inheritance, etc. The only drawback of this
data model is that it is complex and quite difficult to handle.

Float Data Model

The float data model consists of a single two-dimensional array of data elements. For
example, in the 2-d array we can have one column as username and the other as password.
One thing that can be noticed here is, there should not be duplicate entries in the table
(array).

The major drawbacks of this model are that it fails to store a huge amount of data secondly,
to access any data whole table needs to be searched which makes it inefficient.

Semi-Structured Data Model

The semi-structured data model is a generalized form of the relational model, which allows
representing data in a flexible way, hence we can not differentiate between data and
schema in this model because, in this model, some entities have a missing
attribute(s) and on the other hand, some entities might have some extra attribute(s)
which in turn makes it easy to update the schema of the database.
For example - We can say a data model to be semi-structured if in some attributes we are
storing both atomic values (values that can't be divided further, for example, Roll_No) as well
as a collection of values.

Advantages of Data Models

 Data models ensure that the data is represented accurately.


 The relationship between the data is well defined.
 Data redundancy can be minimized and missing data can be identified easily.
 Last but not the least, security of the data is not compromised.

Disadvantages of Data Models

 The biggest disadvantage of the data model is, one must know the characteristics of
physical data to build a data model.
 Sometimes in big databases, it is quite difficult to understand the data model also the
cost incurred is very high.

ER (Entity Relationship) Diagram in DBMS


o 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.
o It develops a conceptual design for the database. It also develops a very
simple and easy to design view of data.
o In ER modeling, 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.

Component of ER Diagram

1. Entity:

An entity may be any object, class, person or place. In the ER diagram, an entity
can be represented as rectangles.

Consider an organization as an example- manager, product, employee,


department etc. can be taken as an entity.
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.

2. Attribute

The attribute is used to describe the property of an entity. Eclipse is used to


represent an attribute.

For example, id, age, contact number, name, etc. can be attributes of a
student.

a. 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.
b. Composite Attribute - An attribute that composed of many other attributes
is known as a composite attribute. The composite attribute is represented by an
ellipse, and those ellipses are connected with an ellipse.

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

d. 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 changes over time and can be derived from
another attribute like Date of birth.

3. Relationship

A relationship is used to describe the relation between entities. Diamond or


rhombus is used to represent the relationship.
Types of relationship are as follows:

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.

For example, A female can marry to one male, and a male can marry to one
female.

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.

For example, Scientist can invent many inventions, but the invention is done by
the only specific scientist.

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.

For example, Student enrolls for only one course, but a course can have many
students.
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.

DBMS – ER Design Issues


Here are some of the issues that can occur while ER diagram design process:

1. Choosing Entity Set vs Attributes

Here we will discuss how choosing an entity set vs an attribute can change the whole ER
design semantics. To understand this lets take an example, let’s say we have an entity set
Student with attributes such as student-name and student-id. Now we can say that the student-
id itself can be an entity with the attributes like student-class and student-section.

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.

2. Choosing Entity Set vs. Relationship Sets

It is hard to decide that an object can be best represented by an entity set or relationship set.
To comprehend and decide the perfect choice between these two (entity vs relationship), the
user needs to understand whether the entity would need a new relationship if a requirement
arise in future, if this is the case then it is better to choose entity set rather than relationship
set.

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.

3. Choosing Binary vs n-ary Relationship Sets

In most cases, the relationships described in an ER diagrams are binary. The n-


ary relationships are those where entity sets are more than two, if the entity sets are only two,
their relationship can be termed as binary relationship.
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 lets take an example to understand how we can convert an n-ary
relationship to multiple binary relationships. Now lets 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.

For example, if an entity cannot be determined as a separate entity rather it is represented by


the combination of participating entity sets. In such case it is better to associate these entities
to many-to-many relationship sets.

AGGREGATE FUNCTIONS IN SQL

An aggregate function in SQL performs a calculation on multiple values and returns a single
value. SQL provides many aggregate functions that include avg, count, sum, min, max, etc.
An aggregate function ignores NULL values when it performs the calculation, except for the
count function. An aggregate function in SQL returns one value after calculating multiple
values of a column. We often use aggregate functions with the GROUP BY and HAVING
clauses of the SELECT statement.

Various types of SQL aggregate functions are:

 Count()

 Sum()

 Avg()

 Min()

 Max()

COUNT() Function - The COUNT() function returns the number of rows in a


database table.

Syntax: COUNT(*) or COUNT( [ALL|DISTINCT] expression )


Example: We will use the ‘products’ table from the sample database for our demonstration.

The following SQL statement fetches the number of products in the table.

This will produce the following result.

The below-given command will display those product ids where the unit price is greater than
4.

This will display the following result.

Let's look at how we can use GROUP BY and HAVING functions with the COUNT
function.

Consider the following dataset:


The SQL command given below will list the number of customers in each city.

This will produce the following results:

SUM() Function - The SUM() function returns the total sum of a numeric column.

Syntax: SUM() or SUM( [ALL|DISTINCT] expression )

Example: The following SQL statement finds the sum of the "unit price" fields in the
"products" table:
This will produce the following result. Let’s look at how we can use GROUP BY and
HAVING functions with the SUM function.

Consider the following dataset:

The SQL command below will list the number of customers in each city, having a sum of
points greater than 3000.

This will produce the following result:

AVG() Function - The AVG() function calculates the average of a set of values.

Syntax: AVG() or AVG( [ALL|DISTINCT] expression )

Example: The following SQL command calculates the average quantity in stock.
This will produce the following result.

MIN() Function - The MIN() aggregate function returns the lowest value (minimum)
in a set of non-NULL values.

Syntax: MIN() or MIN( [ALL|DISTINCT] expression )

Example:

The above code will give us the minimum quantity in stock in the products table.

MAX() Function - The MAX() aggregate function returns the highest value
(maximum) in a set of non-NULL values.

Syntax: AVG() or AVG( [ALL|DISTINCT] expression )

Example: The code depicted below will give us the maximum quantity in stock in the
products table.

This will produce the following result.


SQL Views

In SQL, views contain rows and columns similar to a table, however, views don't hold the
actual data.A view as a virtual table environment that's created from one or more tables so
that it's easier to work with data.

Example: SQL Views

Creating a View in SQL

We can create views in SQL by using the CREATE VIEW command. For example,
CREATE VIEW us_customers AS
SELECT customer_id, first_name
FROM Customers
WHERE Country = 'USA';
Here, a view named us_customers is created from the customers table.
Now to select the customers who lives in USA, we can simply run,
SELECT *
FROM us_customers;
Run Code
Updating a View

It's possible to change or update an existing view using the CREATE OR REPLACE
VIEW command. For example,
CREATE OR REPLACE VIEW us_customers AS
SELECT *
FROM Customers
WHERE Country = 'USA';
Run Code

Here, the us_customers view is updated to show all the fields.

Deleting a View

We can delete views using the DROP VIEW command. For example,
DROP VIEW us_customers;
Run Code

Here, the SQL command deletes the view named us_customers.

Note: If the view is not available, the above command throws an error.

Views for Complex Queries

Suppose A and B are two tables and we wan't to select data from both of the tables. For that,
we have to use SQL JOINS.
However using the JOIN each time could be a tedious task. For that, we can create a view to
fetch records easily.
Let's create a view,

CREATE VIEW order_details AS


SELECT Customers.customer_id, Customers.first_name, Orders.amount
FROM Customers
JOIN Orders
ON Customers.customer_id = Orders.customer_id;
Run Code

Now, to select the data, we can run

SELECT *
FROM order_details;
Run Code
Here, the SQL command selects data from the view order_details.

SQL Sub Query [ Nested Query ]


A Subquery is a query within another SQL query and embedded within the WHERE clause.

Important Rule:

o A subquery can be placed in a number of SQL clauses like WHERE clause, FROM
clause, HAVING clause.
o You can use Subquery with SELECT, UPDATE, INSERT, DELETE statements
along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
o A subquery is a query within another query. The outer query is known as the main
query, and the inner query is known as a subquery.
o Subqueries are on the right side of the comparison operator.
o A subquery is enclosed in parentheses.
o In the Subquery, ORDER BY command cannot be used. But GROUP BY command
can be used to perform the same function as ORDER BY command.

1. Subqueries with the Select Statement

SQL subqueries are most frequently used with the Select statement.

Syntax

1. SELECT column_name
2. FROM table_name
3. WHERE column_name expression operator
4. ( SELECT column_name from table_name WHERE ... );

Example

Consider the EMPLOYEE table have the following records:

ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00


3 David 27 Bangkok 2000.00

4 Alina 29 UK 6500.00

5 Kathrin 34 Bangalore 8500.00

6 Harry 42 China 4500.00

7 Jackson 25 Mizoram 10000.00

The subquery with a SELECT statement will be:

1. SELECT *
2. FROM EMPLOYEE
3. WHERE ID IN (SELECT ID
4. FROM EMPLOYEE
5. WHERE SALARY > 4500);

This would produce the following result:

ID NAME AGE ADDRESS SALARY

4 Alina 29 UK 6500.00

5 Kathrin 34 Bangalore 8500.00

7 Jackson 25 Mizoram 10000.00

2. Subqueries with the INSERT Statement

o SQL subquery can also be used with the Insert statement. In the insert statement, data
returned from the subquery is used to insert into another table.
o In the subquery, the selected data can be modified with any of the character, date
functions.

Syntax:

1. INSERT INTO table_name (column1, column2, column3....)


2. SELECT *
3. FROM table_name
4. WHERE VALUE OPERATOR

Example

Consider a table EMPLOYEE_BKP with similar as EMPLOYEE.

Now use the following syntax to copy the complete EMPLOYEE table into the
EMPLOYEE_BKP table.

1. INSERT INTO EMPLOYEE_BKP


2. SELECT * FROM EMPLOYEE
3. WHERE ID IN (SELECT ID
4. FROM EMPLOYEE);

3. Subqueries with the UPDATE Statement

The subquery of SQL can be used in conjunction with the Update statement. When a
subquery is used with the Update statement, then either single or multiple columns in a table
can be updated.

Syntax

1. UPDATE table
2. SET column_name = new_value
3. WHERE VALUE OPERATOR
4. (SELECT COLUMN_NAME
5. FROM TABLE_NAME
6. WHERE condition);

Example

Let's assume we have an EMPLOYEE_BKP table available which is backup of EMPLOYEE


table. The given example updates the SALARY by .25 times in the EMPLOYEE table for all
employee whose AGE is greater than or equal to 29.

1. UPDATE EMPLOYEE
2. SET SALARY = SALARY * 0.25
3. WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
4. WHERE AGE >= 29);

This would impact three rows, and finally, the EMPLOYEE table would have the following
records.
ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

4 Alina 29 UK 1625.00

5 Kathrin 34 Bangalore 2125.00

6 Harry 42 China 1125.00

7 Jackson 25 Mizoram 10000.00

4. Subqueries with the DELETE Statement

The subquery of SQL can be used in conjunction with the Delete statement just like any other
statements mentioned above.

Syntax

1. DELETE FROM TABLE_NAME


2. WHERE VALUE OPERATOR
3. (SELECT COLUMN_NAME
4. FROM TABLE_NAME
5. WHERE condition);

Example

Let's assume we have an EMPLOYEE_BKP table available which is backup of EMPLOYEE


table. The given example deletes the records from the EMPLOYEE table for all EMPLOYEE
whose AGE is greater than or equal to 29.

1. DELETE FROM EMPLOYEE


2. WHERE AGE IN (SELECT AGE FROM EMPLOYEE_BKP
3. WHERE AGE >= 29 );

This would impact three rows, and finally, the EMPLOYEE table would have the following
records.
ID NAME AGE ADDRESS SALARY

1 John 20 US 2000.00

2 Stephan 26 Dubai 1500.00

3 David 27 Bangkok 2000.00

7 Jackson 25 Mizoram 10000.00

Converting the E-R diagram into relational Model

Covert the following E-R diagram into relational Model

Fname Mname Laname

SSN dob name salary Dep# Dname DLocation

EMPLOYEE N works 1 DEPARTMENT


1 for 1
1 1

manage control
dependent M N
of N
works PROJECT
N fo

DEPENDENT hours Pro# Pname Plocation

Nam Sex Dob Relation

The above E-R diagram consists of

(i) Three strong entities (EMPLOYEE,DEPARTMENT and PROJECT)

(ii) One Weak entity (DEPENDENT)


(iii) Five relationship sets between the entities

(iv) One composite attribute

(v) One descriptive attribute

(vi) Each strong entity set has a primary key(underlined) (vii) Weak entity set
has only secondary key

into Relational Model


Pro# Pname Plocation
STEPS to Convert ER
diagram into relational Model
Step 1. Convert all Strong entity sets into relations

(i) Exclude multivalued now, to be considered later


(ii) Don’t divide Composite Attribute

After the step1, we have the following relational schemas


Employee(relation 1)
SSN dob fname mname lname salary

Department (relatio 2)
Dep# Dname Dlocation

Project (relation 3)

Step 2: Mapping of weak entity type

(i) Create a separate relation & include all simple attribute

(ii) Add Primary key of the owner entity set into the relation and make it as the
foreign key as
Employee(relation 1)

SSN dob fname mname lname salary

Dependent (relation 4)

SSN Name Sex dob relation

Step 3: Mapping 1:1 relationship types

(i) Identify total participation from sets R and S (Say S)

(ii) Add primary key of R into S as a foreign keyIn the ER diagram,the


entity Department has the total participation in the relationship and Primary key of
Employee into Department relation as
Employee
SSN dob fname mname
lname salary
Department
SSN Dep# Dname Dlocation

into Relational Model

Step 4: Mapping 1:N and N:1 relationship types


Add primary key from “1” side to “N” side as foreign key
Here there are two relation of these types (between
Employee and Department and Department and Project)
Employee

SSN dob fname mname lname salary Dep #

Department

Dep # Dname Dlocation

Project

Dep # Pro# Pname Plocation

Step 5: Mapping of M:N relationship type


Create a separate relation that contain the primary keys of both the entity sets and add
descriptive attribute in it if it has.
Works - for (Relation 5)

Dep # SSN hours

Employee

SSN dob fname mname lname salary Dep #

Project

Dep # Pro# Pname Plocation

The Final Relational model Schema is

Employee

SSN dob fname mname lname salary Dep #

Dependent

SSN Name Sex dob relation

Department

Dep # Dname Dlocation

Project

Dep # Pro# Pname Plocation

Works - for

Dep # SSN hours

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