Jntuk R20 DBMS Unit - 3
Jntuk R20 DBMS Unit - 3
Jntuk R20 DBMS Unit - 3
Unit – III
Entity Relationship Model: Introduction, Representation of entities, attributes, entity set,
relationship, relationship set, constraints, sub classes, super class, inheritance, specialization,
generalization using ER Diagrams.
SQL: Creating tables with relationship, implementation of key and integrity constraints, nested
queries, sub queries, grouping, aggregation, ordering, implementation of different types of joins,
view(updatable and non- updatable), relational set operations.
INTRODUCTION:
Entity: An entity can be a real-world object, either animate or inanimate, that can be easily
identifiable. An entity is, something which is described in the database by storing its data.
Entity set: An entity set is a collection of similar entities. The Employees entity set with attributes ssn,
name, and lot is shown in the following figure.
Attribute: An attribute describes a property of an entity. Attribute will have a name and a value for
each entity.
Domain: A domain defines a set of permitted values for an attribute.
Entity Relationship Model (ERM) :
It is a theoretical and conceptual way of showing data relationships.
It is a database modeling technique that generates an abstract diagram or visual representation
of a system's data that can be helpful in designing a relational database.
It allows us, to describe the data involved in a real-world, in terms of objects and their
relationships and is widely used to develop an initial database design.
REPRESENTATION OF ENTITIES:
1. ENTITIES:
Entities are represented by using rectangular boxes. These are named with the entity name
that they represent.
2. ATTRIBUTES:
Attributes are the properties of entities. Attributes are represented by means of ellipses. Every
ellipse represents one attribute and is directly connected to its entity.
Types of attributes:
Simple attribute − Simple attributes are atomic values, which cannot be divided further. For
example, student's phone number is an atomic value of 10 digits.
Composite attribute − Composite attributes are made of more than one simple attribute. For
example, student'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,
average_salary in a department should not be saved directly in the database, instead it can be
derived. For another example, age can be derived from data_of_birth.
Multi-valued attribute − Multi-value attributes may contain more than one values. For
example, a person can have more than one phone number, email_address, etc.
If the attributes are composite, they are further divided in a tree like structure.
Every node is then connected to its attribute. That is, composite attributes are represented by
DBMS | UNIT 3
3 RELATIONSHIP:
Types of relationships:
Unary Relationship:
Binary Relationship:
A relationship among 2 entity sets. Example: A professor teaches a course and a course is
taught by a professor.
Ternary Relationship: A relationship among 3 entity sets. Example: A professor teaches a course in so
and so semester.
DBMS | UNIT 3
R E3
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 is categorized into 4. They are:
1. One-to-One relationship
2. One-to-Many relationship
3. Many-to-One relationship
4. Many-to-Many relationship
1. One-to-One relationship:
When only one instance of an EntitySet are associated with the relationship, then the relationship
is one-to-one relationship.
Each entity in A is associated with at most one entity in B and each entity in B is associated with
at most one entity in A.
Each professor teaches one course and each course is taught by one professor.
2. One-to-many relationship:
When more than one instance of an entity is associated with a relationship, then the relationship
is one-to-many relationship.
DBMS | UNIT 3
Each entity in A is associated with zero or more entities in B and each entity in B is associated
with at most one entity in A.
Each professor teaches 0 (or) more courses and each course is taught by at most one professor.
3. Many-to-one relationship:
When more than one instance of entity is associated with the relationship, then the relationship
is many-to-one relationship.
Each entity in A is associated with at most one entity in B and each entity in B is associated
with 0 (or) more entities in A.
Each professor teaches at most one course and each course is taught by 0 (or) more professors.
4. Many-to-Many relationship:
If more than one instance of an entity on the left and more than one instance of an entity on the
right can be associated with the relationship, then it depicts many-to-many relationship.
Each entity in A is associated with 0 (or) more entities in B and each entity in B is associated
with 0 (or) more entities in A.
DBMS | UNIT 3
Each professor teaches 0 (or) more courses and each course is taught by 0 (or) more professors.
4. RELATIONSHIP SET:
A set of relationships of similar type is called a relationship set. Like entities, a relationship
too can have attributes. These attributes are called descriptive attributes.
PARTICIPATION CONSTRAINTS:
Total Participation
If Each entity in the entity set is involved in the relationship then the participation of the
entity set is said to be total. Total participation is represented by double lines.
Partial participation
If, Not all entities of the entity set are involved in the relationship then such a
participation is said to be partial. Partial participation is represented by single lines.
Example: Participation Constraints can be explained easily with some examples. They are as follows.
Strong Entity set: If each entity in the entity set is distinguishable or it has a key then such an entity set
is known as strong entity set.
Weak Entity set: If each entity in the entity set is not distinguishable or it doesn't has a key then such
an entity set is known as strong entity set.
If entity set is weak then the relationship is also known as weak relationship, since the dependent
relation is no longer needed when the owner left.
Ex: policy dependent details are not needed when the owner (employee) of that policy left or fired from
the company or expired. The detailed ER Diagram is as follows.
The cardinality of the owner entity set is with weak relationship is 1 : m. Weak entity set is
uniquely identifiable by partial key and key of the owner entity set.
Dependent entity set is key to the relation because the all the tuples of weak entity set are
associated with the owner entity set tuples.
EER Model
EER is a high-level data model that incorporates the extensions to the original ER model.
Aggregation
These concepts are used when the comes in EER schema and the resulting schema diagrams called
as EER Diagrams.
It is used to represent a collection of objects that is union of objects of different of different entity
types.
DBMS | UNIT 3
The relationship between sub class and super class is denoted with symbol.
Super Class
Super class is an entity type that has a relationship with one or more subtypes.
An entity cannot exist in database merely by being member of any super class.
For example: Shape super class is having sub groups as Square, Circle, Triangle.
Sub Class
Sub class is a group of entities with unique attributes.
Sub class inherits properties and attributes from its super class.
For example: Square, Circle, Triangle are the sub class of Shape super class.
Generalization is the process of generalizing the entities which contain the properties of all the
generalized entities.
It is a bottom approach, in which two lower level entities combine to form a higher level entity.
It minimizes the difference between the entities by identifying the common features.
DBMS | UNIT 3
For example:
In the above example, Tiger, Lion, Elephant can all be generalized as Animals.
Specialization
Specialization is a process that defines, a group entities which is divided into sub groups based on
their characteristic.
It is a top down approach, in which one higher entity can be broken down into two lower level
entity.
It maximizes the difference between the members of an entity by identifying the unique
characteristic or attributes of each member.
It defines one or more sub class for the super class and also forms the superclass/subclass
relationship.
In the above Specialization example, Employee can be specialized as Developer or Tester, based
on what role they play in an Organization.
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.
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.
DBMS | UNIT 3
INHERITANCE
Inheritance enables us to share attributes between objects such that a subclass inherits attributes
from its parent class.
Simply, it allows low level entities(sub classes) to share the attributes from the high level
entities(Super class).
Properties of Is A:
Inheritance:
All attributes of the super type apply to the subtype.
The subtype inherits all attributes of its super type.
The key of the super type is also the key of the subtype.
DBMS | UNIT 3
Transitivity:
This property creates a hierarchy of IsA relationships.
SQL
CREATING TABLES WITH RELATIONSHIPS:
Entity Set:
Each attribute of the entity set becomes an attribute of the table.
Here, we must know the domain of each attribute and the primary key of an entity set.
Note:: Descriptive attributes:: Which can be used to describe about the relationship.
address CHAR(20) ,
since DATE,
PRIMARY KEY (ssn, did, address),
FOREIGN KEY (ssn) REFERENCES Employees,
FOREIGN KEY (address) REFERENCES Locations,
FOREIGN KEY (did) REFERENCES Departments );
Another Example:
When a column is defined as NOTNULL, then that column becomes a mandatory column.
It implies that a value must be entered into the column if the record is to be accepted for
storage in the table.
Syntax: CREATE TABLE Table_Name(
attribute_name data_type(size) NOT NULL , ….);
Example:
SQL> CREATE Table emp2(
eno number(5) not null,
ename varchar2(10));
Table created.
DBMS | UNIT 3
2. UNIQUE:
The purpose of a unique key is to ensure that information in the column(s) is unique.
i.e. a value entered in column(s) defined in the unique constraint must not be repeated across
the column(s).
A table may have many unique keys.
Syntax: CREATE TABLE Table_Name(
column_name data_type(size) UNIQUE, ….);
Example:
SQL> CREATE Table emp3(
eno NUMBER(5) UNIQUE,
ename VARCHAR2(10));
Table created.
SQL> desc emp3;
ENO NUMBER(5)
ENAME VARCHAR2(10)
SQL> insert into emp3 values(&eno,'&ename');
Enter value for eno: 1
Enter value for ename:
sss
old 1: insert into emp3
values(&eno,'&ename')
new 1: insert into emp3 values(1,'sss')
1 row created.
SQL> /
Enter value for eno: 1
Enter value for ename:
sas
old 1: insert into emp3
values(&eno,'&ename')
DBMS | UNIT 3
3. CHECK:
4. PRIMARY KEY:
5. FOREIGN KEY:
The table that defines the primary key and is referenced by the foreign key is called the
master table.
Syntax: CREATE TABLE Table_Name (
col_name data_type(size)
FOREIGN KEY(col_name) REFERENCES table_name);
Example:
SQL> CREATE TABLE subject (
scode NUMBER (3) PRIMARY KEY,
subname CHAR(10),fcode NUMBER(3),
FOREIGN KEY(fcode) REFERENCE faculty );
SUB QUERIES:
A Subquery or Inner query or a Nested query is a query within another SQL query and
embedded within the WHERE clause.
Subquery is used to return data that will be used in the main query as a condition to further
restrict the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along
with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.
Example:
Consider the CUSTOMERS table having the following records −
Example:
Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table.
Now to copy the complete CUSTOMERS table into the CUSTOMERS_BKP table, we can use
the following syntax.
Example:
This would impact two rows and finally CUSTOMERS table would have the following records.
The subquery can be used in conjunction with the DELETE statement like with any other
statements mentioned above.
Syntax:
Example:
Assuming, we have a CUSTOMERS_BKP table available which is a backup of the
CUSTOMERS table.
The following example deletes the records from the CUSTOMERS table for all the customers
whose AGE is greater than or equal to 27.
DBMS | UNIT 3
This would impact two rows and finally the CUSTOMERS table would have the following records.
GROUPING
The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange
identical data into groups.
This GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the
ORDER BY clause.
Syntax:
The basic syntax of a GROUP BY clause is shown in the following code block.
The GROUP BY clause must follow the conditions in the WHERE clause and must precede
the ORDER BY clause if one is used.
Using WHERE clause, rows can be pre executed before dividing them into groups.
Column aliases can't be used in the Group by clause.
By Default, rows are sorted by ascending order of columns included in the Group By list.
Examples:
Display the average salary of the departments from Emp table.
Display the minimum and maximum salaries of employees working as clerks in each department.
Syntax:
SELECT column1, column2 FROM table1, table2 WHERE [
conditions ] GROUP BY column1, column2 HAVING [ conditions ];
Sequence of steps:
Syntax:
MIN Function:
SQL> select min(Salary) from
Employees;
OUTPUT:
MIN(SALARY)
29860
MAX Function:
SQL> select max(Salary) from
Employees;
OUTPUT:
MAX(SALARY)
65800
SUM Function:
SQL> select sum(Salary) from
Employees;
OUTPUT:
SUM(SALARY)
212574
DBMS | UNIT 3
AVG Function:
SQL> select avg(Salary) from
Employees;
OUTPUT:
AVG(SALARY)
42514.8
COUNT Function:
SQL> select count(IdNum) from
Employees;
OUTPUT:
COUNT(IDNUM)
5
COUNT(*) Function:
SQL> select count(*) from
Employees;
OUTPUT:
COUNT(*)
5
IMPLEMENTATION OF JOINS
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them.
Types of SQL JOINS:
(INNER) JOIN: Returns records that have matching values in both tables
LEFT (OUTER) JOIN: Return all records from the left table, and the matched records from the
right table
RIGHT (OUTER) JOIN: Return all records from the right table, and the matched records
from the left table
FULL (OUTER) JOIN: Return all records when there is a match in either left or right table
DBMS | UNIT 3
1. INNER JOIN:
The INNER JOIN keyword selects records that have matching values in both tables
Syntax:
select column_name(s) from table1 inner join table2
on table1.column_name = table2.column_name;
2. LEFT JOIN:
The LEFT JOIN keyword returns all records from the left table (table1), and the matched
records from the right table (table2). The result is NULL from the right side, if there is no
match.
Syntax:
select column_name(s)from table1left join table2
on table1.column_name = table2.column_name;
3. RIGHT JOIN:
The RIGHT JOIN keyword returns all records from the right table (table2), and the matched
records from the left table (table1). The result is NULL from the left side, when there is no
match.
Syntax:
select column_name(s)from table1right join table2
on table1.column_name table2.column_name;
4. FULL JOIN:
The FULL OUTER JOIN keyword return all records when there is a match in either left
(table1) or right (table2) table records.
Syntax:
select column_name(s) from table1full outer join table2
on table1.column_name = table2.column_name;
A self JOIN is a regular join, but the table is joined with itself.
Syntax:
select column_name(s) from table1 t1, table1 t2 where condition;
EXAMPLES:
Consider the following two tables.
Table 1 − CUSTOMERS Table is as follows.
DBMS | UNIT 3
Inner Join:
SQL> SELECT id, name, amount, date FROM
customers INNER JOIN orders
ON customers.id = orders.customer_id;
This would produce the following result −
Right Join:
Full Join:
Self Join:
SQL> SELECT a.id, b.name, a.salary FROM customers a,
customers b WHERE a.salary<b.salary
This would produce the following result −
DBMS | UNIT 3
ID NAME SALARY
2 Ramesh 1500.00
2 Kaushik 1500.00
1 Chaitail 2000.00
2 Chaitail 1500.00
3 Chaitail 2000.00
6 Chaitail 4500.00
1 Hardik 2000.00
2 Hardik 1500.00
3 Hardik 2000.00
4 Hardik 6500.00
6 Hardik 4500.00
1 Komal 2000.00
2 Komal 1500.00
3 Komal 2000.00
1 Muffy 2000.00
2 Muffy 1500.00
3 Muffy 2000.00
4 Muffy 6500.00
5 Muffy 8500.00
6 Muffy 4500.00
VIEWS:
A view is nothing more than a SQL statement that is stored in the database with an associated
name.
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.
Views, which are a type of virtual tables allow users to do the following −
Structure data in a way that users or classes of users find natural or intuitive.
Restrict access to the data in such a way that a user can see and (sometimes) modify exactly
what they need and no more.
DBMS | UNIT 3
Summarize data from various tables which can be used to generate reports.
Types of Views
There are 2 types of Views..
i)Updatable and
ii)Read-only -views
Unlike base tables, VIEWs are either updatable or read-only, but not both.
INSERT, UPDATE, and DELETE operations are allowed on updatable VIEWs and base tables,
subject to any other constraints.
INSERT, UPDATE, and DELETE are not allowed on read-only VIEWs, but we can change
their base tables,as we want them to be.
An updatable VIEW is one that can have each of its rows associated with exactly one row in an
underlying base table.
When the VIEW is changed, the changes pass unambiguously through the VIEW to that
underlying base table.
Updatable VIEWs in Standard SQL are defined only for queries that meet these criteria:
a. Built on only one table
b. No GROUP BY clause
c. No HAVING clause
d. No aggregate functions
e. No calculated columns
f. No UNION, INTERSECT, or EXCEPT
g. No SELECT DISTINCT clause
In short, we are absolutely sure that each row in the VIEW maps back to one and only one row in
the base table.
Some updating is handled by the CASCADE option in the referential integrity constraints on
the base tables, not by the VIEW declaration.
The major advantage of View definition is that it is based on syntax and not semantics.
dictionary.
DBMS | UNIT 3
A view contains no data. All the data it shows comes from the base tables.
A view can provide an additional level of table security by restricting access to a set of rows
or columns of a table.
A view hides implementation complexity.
A view lets we change the data we can access, applying operators, aggregation functions,
filters etc. on the base table.
A view isolates applications from changes in definitions of base tables. Suppose a view uses
two columns of a base table, it makes no difference to the view if other columns are added,
modified or removed from the base table.
To know about the views in your own schema, look up user_views.
The underlying SQL definition of the view can be read via select text from user_views for the
view.
Oracle does not enforce constraints on views. Instead, views are subject to the constraints of their
base tables.
Creating Views
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2 table_name WHERE [condition];
we can include multiple tables in your SELECT statement in a similar way as we use them in a normal
SQL SELECT query.
Example:
Consider the CUSTOMERS table having the following records −
Following is an example to create a view from the CUSTOMERS table. This view would be used
to have customer name and age from the CUSTOMERS table.
DBMS | UNIT 3
Now, we can query CUSTOMERS_VIEW in a similar way as w e query an actual table. Following
is an example for the same.
Example:
The WITH CHECK OPTION in this case should deny the entry of any NULL values in the
view's AGE column, because the view is defined by data that does not have a NULL value in the AGE
column.
Updating a View
A view can be updated under certain conditions which are given below –
The SELECT clause may not contain the keyword DISTINCT.
This would ultimately update the base table CUSTOMERS and the same would reflect in the view
itself. Now, try to query the base table and the SELECT statement would produce the following result.
Rows of data can be deleted from a view. The same rules that apply to the UPDATE and
INSERT commands apply to the DELETE command.
This would ultimately delete a row from the base table CUSTOMERS and the same would reflect in
the view itself.
Now, try to query the base table and the SELECT statement would produce the following result.
DBMS | UNIT 3
Dropping Views
Obviously, where we have a view, we need a way to drop the view if it is no longer needed.
Syntax:
DROP VIEW view_name;
Example:
SQL> DROP VIEW CUSTOMERS_VIEW;
SET OPERATIONS
These operators are used to combine information of similar datatype from one or more than one
table.
Datatype of the corresponding columns in all the select statement should be same.
Different types of set commands are
UNION
UNION ALL
INTERSECT
MINUS
Set operators are combine 2 or more queries into one result .
The result of each SELECT statement can be treated as a set and SQL set operators can be
applied on those sets to arrive at a final result.
SQL statements containing set operators are referred to as compound queries, and each
SELECT statements in a command query in referred to as a compound query.
Set operations are often called vertical joins, as a result combines data from 2 or more SELECT
based on columns instead of rows.
Syntax:
<compound query>
{ UNION | UNION ALL | MINUS | INTERSECT }
<compound query>
UNION: Combines the result of 2 select statements into one result set, and then estimates any
duplicate rows from that result set.
UNION ALL: Combines the result of 2 SELECT statements into one result set including the duplicates.
DBMS | UNIT 3
INTERSECT: Returns only the rows that are returned by each of two SELECT statements.
MINUS: Takes the result set of each SELECT statement, and removes those rows that are also
recommended by a second SELECT statement.
Point Of Concentration:
The queries are all executed independently but their output is merged.
Only final queries ends with a semicolon(;).
The result set of both the queries must have same number of columns.
The datatype of each column in the second result set must match the datatype of the
corresponding column in the first result set.
The 2 SELECT statements may not contain an ORDER BY clause. The final result of the
entire set operations can be ordered.
The columns used for ordering must be defined through the column number.
Examples:
Display the employees who work in departments 10 and 30with out duplicates.
SQL> SELECT empno, ename from emp where
deptno=10 UNION
SELECT empno, ename from emp where deptno=30;
Display the employees whose row number is less than 7 but not less than 6.
SQL> SELECT rownum , ename from emp where
rownum<7 MINUS
SELECT rownum , ename from emp where rownum<6;
RELATIONAL OPERATIONS
Codd originally defined eight relational operators.
1. SELECT originally called RESTRICT
2. PROJECT
3. JOIN
DBMS | UNIT 3
4. PRODUCT
5. UNION
6. INTERSECT
7. DIFFERENCE
8. DIVIDE
The most important of these are (1), (2), (3) and (8), which, together with some other aggregate
functions, are powerful enough to answer a wide range of queries.
The eight operators will be described as general procedures - i.e. not in the syntax of SQL or any
other relational language.
SELECT:
RESTRICTS the rows chosen from a table to those entries with specified attribute values.
SELECT item FROM stock_level WHERE quantity > 100
constructs a new, logical table - an unnamed relation - with one column per row (i.e. item) containing
all rows from stock_level that satisfy the WHERE clause.
PROJECT:
JOIN:
Associates entries from two tables on the basis of matching column values.
JOIN stock_item WITH stock_level OVER item
It is not necessary for there to be a one-to-one relationship between entries in two tables to be
joined - entries which do not match anything will be eliminated from the result, and entries from one
table which match several entries in the other will be duplicated the required number of times.
PRODUCT:
Builds a relation from two specified relations consisting of all possible combinations of
rows, one from each of the two relations.
For example, consider two relations, A and B, consisting of rows:
Ex:: A:: {a,b,c} B::{ d,e } Then A PRODUCT B :: {a d, a e, b d , b e , c d , c e.}
UNION:
Builds a relation consisting of all rows appearing in either or both of the two relations. For
example, consider two relations, A and B, consisting of rows:
DBMS | UNIT 3
INTERSECT:
Builds a relation consisting of all rows appearing in both of the two relations. For example, consider two
relations, A and B, consisting of rows:
A: a B: a =>A INTERSECT B:a
b e
c
DIFFERENCE: Builds a relation consisting of all rows appearing in the first and not in the second of
the two relations. For example, consider two relations, A and B, consisting of rows:
A: a B: a=> A - B: b and B - A: e
b e c
c
DIVIDE: Takes two relations, one binary and one unary, and builds a relation consisting of all
values of one column of the binary relation that match, in the other column, all values in the unary
relation.
A: a x B: x =>A divide B: a
a y y
a z
b x
c y
For example, suppose table A contains a list of suppliers and commodities, table B a list
of all commodities bought by a company. Dividing A by B produces a table listing suppliers
who sell all commodities.