Jntuk R20 DBMS Unit - 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

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.

Fig: Student and Employee


entities
DBMS | UNIT 3

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

 Single-value attribute − Single-value attributes contain single value. For example −


Social_Security_Number.

 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.

ER Representation for 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 (rectangle).

 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

ellipses that are connected with an ellipse.

 Multi valued attributes are depicted by double ellipse.

 Derived attributes are depicted by dashed ellipse.

3 RELATIONSHIP:

 Relationships are represented by diamond-shaped box.


 Name of the relationship is written inside the diamond-box.
 All the entities (rectangles) participating in a relationship, are connected to it by a line.
DBMS | UNIT 3

Types of relationships:

 Degree of Relationship is the number of participating entities in a relationship.


 Based on degree the relationships are categorized as
 Unary = degree 1
 Binary = degree 2
 Ternary = degree 3
 n-ary = degree

Unary Relationship:

 A relationship with one entity set.


 It is like a relationship among 2 entities of same entity set.
 Example: A professor (in-charge) reports to another professor (Head Of the Dept).

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

n-array Relationship: A relationship among n entity sets.


E1
E2

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.

1. Each Professor teaches at least one


course. min=1 (Total Participation)
max=many (No key)

2. Each Professor teaches at most one


course. min=0 (Partial Participation)
max=many (Key)
DBMS | UNIT 3

3. Each Professor teaches Exactly one course.


min=1 (Total Participation)
max=1 (Key)

4. Each Professor teaches course.


min=0 (Partial Participation)
max=many (no Key)

Note: Partial Participation is the default participation.

STRONG AND WEAK ENTITY SETS:

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.

 Here, eno is key so it is represented by solid underline. dname is partial key.


 It can't distinguish the tuples in the Dependent entity set. So dname is represented by dashed
underline.
 Weak entity set is always in total participation with the relation.
DBMS | UNIT 3

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

 It is a diagrammatic technique for displaying the following concepts

 Sub Class and Super Class

 Specialization and Generalization

 Aggregation

 These concepts are used when the comes in EER schema and the resulting schema diagrams called
as EER Diagrams.

Features of EER Model

 EER creates more accurate design to database schemas.

 It reflects the data properties and constraints more precisely.

 It includes all modeling concepts of the ER model.

 Diagrammatic technique helps for displaying the EER schema.

 It includes the concept of specialization and generalization.

 It is used to represent a collection of objects that is union of objects of different of different entity
types.
DBMS | UNIT 3

SUB CLASS AND SUPER CLASS


 Sub class and Super class relationship leads the concept of Inheritance.

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

SPECIALIZATION AND GENERALIZATION


Generalization

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

 Generalization is the reverse process of Specialization.

 It defines a general entity type from a set of specialized entity type.

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

SQL> CREATE TABLE Employees (


ssn CHAR(11),
name CHAR(30) ,
sal INTEGER,
PRIMARY KEY (ssn) );

Relationship sets without constraints:

 To represent a relationship, we must be able to identify each participating entity.


 Also consider the descriptive attributes of the relationship.
 Thus, the attributes of the relation include:
 The primary key attributes of each participating entity set,can be taken as foreign key.
 The set of descriptive attributes of the relationship.

Note:: Descriptive attributes:: Which can be used to describe about the relationship.

SQL> CREATE TABLE Works_In (


ssn CHAR(11),
did INTEGER,
DBMS | UNIT 3

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:

SQL> CREATE TABLE Reports_To ( in_charge_ssn CHAR (11),


hod_ssn CHAR (11) ,
PRIMARY KEY (in_charge_ssn,hod_ssn),
FOREIGN KEY (in_charge_ssn) REFERENCES
Professor(ssn), FOREIGN KEY (hod_ssn) REFERENCES
Professor(ssn) );

IMPLEMENTATION OF KEY AND INTEGRITY CONSTRAINTS


1. NOT NULL:

 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

SQL> desc emp2;

Name Null? Type

ENO NOT NUMBER(5)


NULL
ENAME VARCHAR2(10)

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;

Name Null? Type

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

new 1: insert into emp3 values(1,'sas')


insert into emp3 values(1,'sas')
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C003006) violated

3. CHECK:

 Specifies a condition that each row in the table must satisfy.


 To satisfy the constraint, each row in the table must make the condition either TRUE or
unknown (due to a null).
Syntax: CREATE TABLE Table_Name(
column_name data_type(size) CHECK(logical expression), ….);
Example:
SQL> CREATE TABLE student (
sno NUMBER (3),
name CHAR(10),
class CHAR(5),
CHECK(class IN(‘CSE’,’IT’,’ECE’));

4. PRIMARY KEY:

 A field which is used to identify a record uniquely.


 A column or combination of columns can be created as primary key, which can be used as a
reference from other tables.
 A table contains primary key is known as Master Table.
 It must uniquely identify each record in a table.
 It must contain unique values.
 It cannot be a null field.
 It should contain a minimum no. of fields necessary to be called unique.

Syntax: CREATE TABLE Table_Name(column_name data_type(size) PRIMARY KEY, ….);


Example:
SQL> CREATE TABLE faculty (
fcode NUMBER(3) PRIMARY KEY,
fname CHAR(10));

5. FOREIGN KEY:

 It is a table level constraint. We cannot add this at column level.


 To reference any primary key column from other table this constraint can be used.
 The table in which the foreign key is defined is called a detail table.
DBMS | UNIT 3

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

There are a few rules that subqueries must follow ::


 Subqueries must be enclosed within parentheses.
 An ORDER BY command cannot be used in a subquery, although the main query can use an
ORDER BY. 
 The GROUP BY command can be used to perform the same function as the ORDER BY in a
subquery.
 Subqueries that return more than one row can only be used with multiple value operators such
as the IN operator.

Subqueries with the SELECT Statement:

 Subqueries are most frequently used with the SELECT statement.


Syntax

SELECT column_name(s) FROM table1 [, table2 ]

WHERE column_name OPERATOR

(SELECT column_name [, column_name ]

FROM table1 [, table2 ] [WHERE]);


DBMS | UNIT 3

Example:
Consider the CUSTOMERS table having the following records −

ID NAME AGE ADDRESS SALARY


1 Ramesh 35 Ahmadabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00

SQL> SELECT * FROM CUSTOMERS


WHERE ID IN
(SELECT ID FROM CUSTOMERS WHERE SALARY > 4500) ;

This would produce the following result.

ID NAME AGE ADDRESS SALARY


4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
7 Muffy 24 Indore 10000.00

Subqueries with the INSERT Statement:

 Subqueries also can be used with INSERT statements.


 The INSERT statement uses the data returned from the subquery to insert into another table.
 The selected data in the subquery can be modified with any of the character, date or number
functions.
Syntax:

INSERT INTO table_name [ (column(s) ]


SELECT [ *|column1 [, column2 ] FROM table1 [, table2 ]
[ WHERE VALUE OPERATOR];

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.

SQL> INSERT INTO CUSTOMERS_BKP


SELECT * FROM CUSTOMERS
WHERE ID IN
(SELECT ID FROM CUSTOMERS) ;
DBMS | UNIT 3

Subqueries with the UPDATE Statement:

 The subquery can be used in conjunction with the UPDATE statement.


 Either single or multiple columns in a table can be updated when using a subquery with the
UPDATE statement.
Syntax:

UPDATE table SET column_name = new_value


[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME FROM TABLE_NAME [WHERE)] )

Example:

 Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS


table.
 The following example updates SALARY by 0.25 times in the CUSTOMERS table for all the
customers whose AGE is greater than or equal to 27.

SQL> UPDATE CUSTOMERS SET SALARY = SALARY * 0.25


WHERE AGE IN
(SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 27 );

This would impact two rows and finally CUSTOMERS table would have the following records.

ID NAME AGE ADDRESS SALARY


1 Ramesh 35 Ahmadabad 125.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 2125.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00

Subqueries with the DELETE Statement:

 The subquery can be used in conjunction with the DELETE statement like with any other
statements mentioned above.

Syntax:

DELETE FROM TABLE_NAME


[ WHERE OPERATOR [ VALUE ]
(SELECT COLUMN_NAME FROM TABLE_NAME[WHERE) ] );

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

SQL> DELETE FROM CUSTOMERS WHERE AGE IN


(SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 27 );

This would impact two rows and finally the CUSTOMERS table would have the following records.

ID NAME AGE ADDRESS SALARY


2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00

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.

SELECT column1, column2 FROM table_name WHERE [ conditions ]


GROUP BY column1, column2 ORDER BY column1, column2;

Guidelines to use Group By Clause

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

SQL> select deptno,AVG(sal) from emp group by deptno;

Display the minimum and maximum salaries of employees working as clerks in each department.

SQL> select deptno,min(sal),max(sal) from emp where job='CLERK' Group by deptno;

Excluding Groups of Results:


 While using Group By clause, there is a provision to exclude some group results using HAVING
clause.
 HAVING clause is used to specify which groups can be specified. It is used to filter the data
which is associated with the group functions.
DBMS | UNIT 3

Syntax:
SELECT column1, column2 FROM table1, table2 WHERE [
conditions ] GROUP BY column1, column2 HAVING [ conditions ];

Sequence of steps:

 First rows are grouped.


 Group functions are applied to that identifies groups.
 Groups that match with the criteria in having clause are displayed.

Note::
 Existence of Group by clause does not guarantee the existence of HAVING clause but the
existence of HAVING clause demands the existence of Group By clause.
Example:
Display the Departments having the min salary of clerks is > 1000

SQL> select deptno, min(sal) from emp where


job='CLERK' group by deptno HAVING
min(sal)> 1000;
Display the sum of the salaries of the departments.

SQL> select deptno, sum(sal) from emp group by deptno;

AGGREGATION: Aggregation Functions or Group Functions::

 These function return a single row based on group of rows.


 These can appear in SELECT list and HAVING clauses only.
 These operate on sets of rows to give one result per group.
 The set may be whole table or table split into group.

Guidelines to use Aggregate Functions:

 Distinct makes the functions to consider only non duplicate value.


 All makes the function to consider every value including
duplicates.

Syntax:

GroupFunctionName (Distinct/ All columns)

 The data types for arguments may be char,varchar, number or Date.


 All group functions except count(*) ignore NULL values.
DBMS | UNIT 3

The list of Aggregate Functions are:

MIN returns the smallest value in a given column


MAX returns the largest value in a given column
SUM returns the sum of the numeric values in a given column
AVG returns the average value of a given column
COUNT returns the total number of values in a given column
COUNT(*) returns the number of rows in a table

Consider the following table:

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

ORDERING: (ORDER BY CLAUSE)


 The SQL ORDER BY clause is used to sort the data in ascending or descending order, based
on one or more columns. Some databases sort the query results in an ascending order by
default.
Syntax:

select column-list from table_name[where condition]


[order by column1, column2,..columnn][asc|desc];
Example:
Consider the following table:
ID NAME AGE ADDRESS SALARY
1 Ramesh 35 Ahmadabad 2000
2 Khilan 25 Delhi 1500
3 Kowshik 23 Kota 2000
4 Chaitali 25 Mumbai 6500
5 Hardhik 27 Bhopal 8500
6 Komal 22 MP 4500
7 Muffy 24 Indore 10000
DBMS | UNIT 3

SQL > select * from customers order by name, salary;


OUTPUT:
ID NAME AGE ADDRESS SALARY
4 Chaitali 25 Mumbai 6500
5 Hardhik 27 Bhopal 8500
3 Kowshik 23 Kota 2000
2 Khilan 25 Delhi 1500
6 Komal 22 MP 4500
7 Muffy 24 Indore 10000
1 Ramesh 35 Ahmadabad 2000

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:

There are 4 different 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;

5. SQL SELF JOIN:

 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

ID NAME AGE ADDRESS SALARY


1 Ramesh 31 Ahmadabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
5 Hardik 27 Mumbai 6500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
Table 2 − ORDERS Table is as follows.
OID DATE CUSTOMER_ID AMOUNT
102 2009-10-08 00:00:00 3 3000
100 2009-10-08 00:00:00 3 1500
101 2009-11-20 00:00:00 2 1560
103 2008-05-20 00:00:00 4 2060

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 −

ID NAME AMOUNT DATE


3 Kaushik 3000 2009-10-08-00:00:00
3 Kaushik 1500 2009-10-08 00:00:00
2 Khilan 1560 2009-11-20 00:00:00
4 Chaitali 2060 2008-05-20 00:00:00
Left Join:
SQL> SELECT id, name, amount, date FROM
customers LEFT JOIN orders
ON customers.id = orders.customer_id;
This would produce the following result −

ID NAME AMOUNT DATE


1 Ramesh NULL NULL
2 Khilan 1560 2009-11-20 00:00:00
3 Kaushik 3000 2009-10-08-00:00:00
3 Kaushik 1500 2009-10-08 00:00:00
4 Chaitali 2060 2008-05-20 00:00:00
5 Hardik NULL NULL
6 Komal NULL NULL
7 Muffy NULL NULL
DBMS | UNIT 3

Right Join:

SQL> SELECT id, name, amount, date FROM


customers RIGHT JOIN orders
ON customers.id = orders.customer_id;

This would produce the following result −

ID NAME AMOUNT DATE


3 Kaushik 3000 2009-10-08-00:00:00
3 Kaushik 1500 2009-10-08 00:00:00
2 Khilan 1560 2009-11-20 00:00:00
4 Chaitali 2060 2008-05-20 00:00:00

Full Join:

SQL> SELECT id, name, amount, date FROM


customers FULL JOIN orders
ON customers.id = orders.customer_id;
This would produce the following result −

ID NAME AMOUNT DATE


1 Ramesh NULL NULL
2 Khilan 1560 2009-11-20 00:00:00
3 Kaushik 3000 2009-10-08-00:00:00
3 Kaushik 1500 2009-10-08 00:00:00
4 Chaitali 2060 2008-05-20 00:00:00
5 Hardik NULL NULL
6 Komal NULL NULL
7 Muffy NULL NULL
3 Kaushik 3000 2009-10-08 00:00:00
3 Kaushik 1500 2009-10-08 00:00:00
2 Khilan 1560 2009-11-20 00:00:00
4 Chaitali 2060 2008-05-20 00:00:00

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.

Examples of Updatable and Non-updatable View.


CREATE VIEW view_1 AS
SELECT * FROM Table1 WHERE x IN (1,2);
-- updatable, has a key!
-------------------------------------------------------
CREATE VIEW view_2 AS
SELECT * FROM Table1 WHERE x = 1 UNION ALL
SELECT * FROM Table1 WHERE x = 2;
-- not updatable!
More about Views:
 A view takes up no storage space other than for the definition of the view in the data

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

 Database views are created using the CREATE VIEW statement.


 Views can be created from a single table, multiple tables or another view.
 To create a view, a user must have the appropriate system privilege according to the specific
implementation.

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 −

ID NAME AGE ADDRESS SALARY


1 Ramesh 32 Ahmadabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00

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

SQL > CREATE VIEW CUSTOMERS_VIEW AS


SELECT name, age FROM CUSTOMERS;

Now, we can query CUSTOMERS_VIEW in a similar way as w e query an actual table. Following
is an example for the same.

SQL > SELECT * FROM CUSTOMERS_VIEW;

This would produce the following result.


NAME AGE
Ramesh 32
Khilan 25
Kaushik 23
Chaitali 25
Hardik 27
Komal 22
Muffy 24
With Check Option:

 “ WITH CHECK OPTION” is a CREATE VIEW statement option.


 The purpose of the WITH CHECK OPTION is to ensure that all UPDATE and INSERTs
satisfy the condition(s) in the view definition.
 If they do not satisfy the condition(s), the UPDATE or INSERT returns an error.

Example:

SQL> CREATE VIEW CUSTOMERS_VIEW


AS SELECT name, age FROM
CUSTOMERS
WHERE age IS NOT NULL WITH CHECK OPTION;

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.

 The SELECT clause may not contain summary functions.


 The SELECT clause may not contain set functions.
 The SELECT clause may not contain set operators..
 The SELECT clause may not contain an ORDER BY clause.
 The FROM clause may not contain multiple tables.
 The WHERE clause may not contain subqueries.
DBMS | UNIT 3

 The query may not contain GROUP BY or HAVING.


 Calculated columns may not be updated.
 All NOT NULL columns from the base table must be included in the view in order for the
INSERT query to function.
So, if a view satisfies all the above-mentioned rules then we can update that view. The following
code blockhas an example to update the age of Ramesh.

SQL > UPDATE CUSTOMERS_VIEW SET AGE = 35 WHERE name = 'Ramesh';

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.

ID NAME AGE ADDRESS SALARY


1 Ramesh 35 Ahmadabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00

Inserting Rows into a View

 Rows of data can be inserted into a view.


 The same rules that apply to the UPDATE command also apply to the INSERT command.
 Here, we cannot insert rows in the CUSTOMERS_VIEW because we have not included all
the NOT NULL columns in this view, otherwise we can insert rows in a view in a similar way as
we insert them in a table.

Deleting Rows from a View

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

Following is an example to delete a record having AGE = 22.

SQL > DELETE FROM CUSTOMERS_VIEW WHERE age = 22;

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

ID NAME AGE ADDRESS SALARY


1 Ramesh 35 Ahmadabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
7 Muffy 24 Indore 10000.00

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(;).

Rules And Restrictions:

 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 who work in departments 10 and 30.


SQL> SELECT empo,ename from emp where
deptno=10 UNION ALL
SELECT empno, ename from emp where deptno=30 ;
Display the employees who work in both the departments with deptno 10 and 30.
SQL> SELECT empno, ename from emp where
deptno=10 INTERSECT
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:

 Selects rows made up of a sub-set of columns from a table.


PROJECT stock_item OVER item AND description produces a new logical table where each row
contains only two columns - item and description.
The new table will only contain distinct rows from stock_item; i.e. any duplicate rows so
formed will be eliminated.

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

Eg:: A:: {a,b,c} B::{ d,e } Then A UNION B :: {a,b,c,d,e}

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.

You might also like