0% found this document useful (0 votes)
15 views

UNIT-iii

The document provides an overview of the Entity Relationship (ER) model, which is used for conceptual database design based on real-world entities and their relationships. It covers key concepts such as entities, attributes, keys, relationships, and the enhanced ER model that includes subclasses, specialization, generalization, and aggregation. Additionally, it explains various types of relationships, including one-to-one, one-to-many, and many-to-many, as well as the distinction between strong and weak entities.

Uploaded by

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

UNIT-iii

The document provides an overview of the Entity Relationship (ER) model, which is used for conceptual database design based on real-world entities and their relationships. It covers key concepts such as entities, attributes, keys, relationships, and the enhanced ER model that includes subclasses, specialization, generalization, and aggregation. Additionally, it explains various types of relationships, including one-to-one, one-to-many, and many-to-many, as well as the distinction between strong and weak entities.

Uploaded by

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

UNIT-III

Entity Relationship Model


The ER model defines the conceptual view of a database. It works around real-world entities
and the associations among them. At view level, the ER model is considered a good option
for designing databases.

Entity
An entity can be a real-world object, either animate or inanimate, that can be easily
identifiable. For example, in a school database, students, teachers, classes, and courses
offered can be considered as entities. All these entities have some attributes or properties
that give them their identity.

An entity set is a collection of similar types of entities. An entity set may contain entities
with attribute sharing similar values. For example, a Students set may contain all the
students of a school; likewise a Teachers set may contain all the teachers of a school from all
faculties. Entity sets need not be disjoint.

Attributes
Entities are represented by means of their properties, called attributes. All attributes have
values. For example, a student entity may have name, class, and age as attributes.

There exists a domain or range of values that can be assigned to attributes. For example, a
student's name cannot be a numeric value. It has to be alphabetic. A student's age cannot be
negative, etc.

Types of Attributes
 Simple attribute − Simple attributes are atomic values, which cannot be divided
further. For example, a 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, a 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-value attribute − Multi-value attributes may contain more than one values.
For example, a person can have more than one phone number, email_address, etc.

Entity-Set and Keys


Key is an attribute or collection of attributes that uniquely identifies an entity among entity
set.

For example, the roll_number of a student makes him/her identifiable among students.

 Super Key − A set of attributes (one or more) that collectively identifies an entity in
an entity set.
 Candidate Key − A minimal super key is called a candidate key. An entity set may
have more than one candidate key.
 Primary Key − A primary key is one of the candidate keys chosen by the database
designer to uniquely identify the entity set.

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

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.

Degree of Relationship
The number of participating entities in a relationship defines the degree of the relationship.

 Binary = degree 2
 Ternary = degree 3
 n-ary = deg
Notations:
Mapping Cardinalities
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.

 One-to-one − One entity from entity set A can be associated with at most one entity
of entity set B and vice versa.

 One-to-many − One entity from entity set A can be associated with more than one
entities of entity set B however an entity from entity set B, can be associated with at
most one entity.

 Many-to-one − More than one entities from entity set A can be associated with at
most one entity of entity set B, however an entity from entity set B can be associated
with more than one entity from entity set A.
 Many-to-many − One entity from A can be associated with more than one entity
from B and vice versa.

Enhanced (Extended) ER Diagrams

EER is a high-level data model that incorporates the extensions to the original ER
model. Enhanced ERD are high level models that represent the requirements and
complexities of complex database.
In addition to ER model concepts EE-R includes −

 Subclasses and Super classes.


 Specialization and Generalization.
 Category or union type.
 Aggregation.
These concepts are used to create EE-R diagrams.

Subclasses and Super class


Super class is an entity that can be divided into further subtype.
For example − consider Shape super class.
Super class shape has sub groups: Triangle, Square and Circle.
Sub classes are the group of entities with some unique attributes.Sub class inherits
the properties and attributes from super class.

Specialization and Generalization


Generalization is a process of generalizing an entity which contains generalized
attributes or properties of generalized entities.
It is a Bottom up process i.e. consider we have 3 sub entities Car, Truck and
Motorcycle. Now these three entities can be generalized into one super class
named as Vehicle.
Specialization is a process of identifying subsets of an entity that share some
different characteristic. It is a top down approach in which one entity is broken down
into low level entity.
In above example Vehicle entity can be a Car, Truck or Motorcycle.

Vehicle is the company’s primary entity, also known as the superclass.


Color, Type, Engine capacity, and so on are all attributes of the
superclass. Vehicle is further subdivided into subclasses such as Scooter,
Car, and Truck. Each subclass inherits all of the attributes of the
superclass. Apart from inherited attributes, a subclass can have its own
attributes as well.

Generalization

The process of extracting the common attributes or properties of entities


(subclasses) to sum up and form a superclass is known as Generalization.
It is a reverse Specialisation method which means it follows the bottom-up
approach. It is an approach to high-level database management systems
that focuses on core values and principles.

The Scooter, Car, and Truck are the primary entities in the Enhanced ER
diagram. They can include attributes such as registration fees, license
tenure, fitness data, and so on, and serve as subclasses for both Private
and Commercial vehicle superclasses. The attributes belong to the
subclasses Scooter, Car, and Truck, and they are included in the
respective superclass because they are common. This process of taking
the common attributes and reaching the primary root is known
as Generalization.

Category or Union
Relationship of one super or sub class with more than one super class.

Owner is the subset of two super class: Vehicle and House.

Aggregation
Represents relationship between a whole object and its component.
Consider a ternary relationship Works_On between Employee, Branch and
Manager. Now the best way to model this situation is to use aggregation, So, the
relationship-set, Works_On is a higher level entity-set. Such an entity-set is treated
in the same manner as any other entity-set. We can create a binary relationship,
Manager, between Works_On and Manager to represent who manages what tasks.
In this case, two entities, Teachers and Students are aggregated to form a
new entity. In simple terms, the relationship between Teachers and
Students is considered a single entity.
 Contain all the basic modeling concepts of an ER Diagram
 Adds additional concepts:
o Specialization/generalization
o Subclass/super class
o Categories
o Attribute inheritance
 Extended ER diagrams use some object-oriented concepts such as inheritance.
 EER is used to model concepts more accurately than the ER diagram.

Sub classes and Super classes

 In some cases, and entity type has numerous sub-groupings of its entities that are
meaningful, and need to be explicitly represented, because of their importance.

 For example, members of entity Employee can be grouped further into Secretary,
Engineer, Manager, Technician, Salaried_Employee.

 The set listed is a subset of the entities that belong to the Employee entity, which means
that every entity that belongs to one of the sub sets is also an Employee.

 Each of these sub-groupings is called a subclass, and the Employee entity is called the
super-class.

 An entity cannot only be a member of a subclass; it must also be a member of the super-
class.
 An entity can be included as a member of a number of sub classes, for example, a
Secretary may also be a salaried employee, however not every member of the super class
must be a member of a sub class.
Type Inheritance
 The type of an entity is defined by the attributes it possesses, and the relationship types it
participates in.

 Because an entity in a subclass represents the same entity from the super class, it should
possess all the values for its attributes, as well as the attributes as a member of the super
class.

 This means that an entity that is a member of a subclass inherits all the attributes of the
entity as a member of the super class; as well, an entity inherits all the relationships in
which the super class participates.

Employee Wor Department


k

Secretary Engineer Technician

Specialization

 The process of defining a set of subclasses of a super class.


 Specialization is the top-down refinement into (super) classes and subclasses
 The set of sub classes is based on some distinguishing characteristic of the super class.
 For example, the set of sub classes for Employee, Secretary, Engineer, Technician,
differentiates among employee based on job type.
 There may be several specializations of an entity type based on different distinguishing
characteristics.
 Another example is the specialization, Salaried_Employee and Hourly_Employee, which
distinguish employees based on their method of pay.

Notation for Specialization


 To represent a specialization, the subclasses that define a specialization are attached by
lines to a circle that represents the specialization, and is connected to the super class.
 The subset symbol (half-circle) is shown on each line connecting a subclass to a super
class, indicates the direction of the super class/subclass relationship.
 Attributes that only apply to the sub class are attached to the rectangle representing the
subclass. They are called specific attributes.
 A sub class can also participate in specific relationship types. See Example.

Employee Wor Department


k

Secretary Engineer Technician

Belongs Professional
To
Organization

Reasons for Specialization


 Certain attributes may apply to some but not all entities of a super class. A subclass is
defined in order to group the entities to which the attributes apply.
 The second reason for using subclasses is that some relationship types may be
participated in only by entities that are members of the subclass.
Summary of Specialization
Allows for:

 Defining set of subclasses of entity type


 Create additional specific attributes for each sub class
 Create additional specific relationship types between each sub class and other entity types
or other subclasses.

Generalization

 The reverse of specialization is generalization.


 Several classes with common features are generalized into a super class.
 For example, the entity types Car and Truck share common attributes License_PlateNo,
VehicleID and Price, therefore they can be generalized into the super class Vehicle.

Constraints on Specialization and Generalization


 Several specializations can be defined on an entity type.
 Entities may belong to subclasses in each of the specializations.
 The specialization may also consist of a single subclass, such as the manager
specialization, in this case we don’t use the circle notation.
Types of Specializations

Predicate-defined or Condition-defined specialization


 Occurs in cases where we can determine exactly the entities of each sub class by placing a
condition of the value of an attribute in the super class.
 An example is where the Employee entity has an attribute, Job Type. We can specify the
condition of membership in the Secretary subclass by the condition, JobType=”Secretary”
Another Example:

 The condition is called the defining predicate of the sub class.


 The condition is a constraint specifying exactly those entities of the Employee entity type
whose attribute value for Job Type is Secretary belong to the subclass.
 Predicate defined subclasses are displayed by writing the predicate condition next to the
line that connects the subclass to the specialization circle.

Attribute-defined specialization
 If all subclasses in a specialization have their membership condition on the same attribute
of the super class, the specialization is called an attribute-defined specialization, and the
attribute is called the defining attribute.
 Attribute-defined specializations are displayed by placing the defining attribute name next
to the arc from the circle to the super class.
User-defined specialization
 When we do not have a condition for determining membership in a subclass the subclass
is called user-defined.
 Membership to a subclass is determined by the database users when they add an entity to
the subclass.
Disjointness/Overlap Constraint
 Specifies that the subclass of the specialization must be disjoint, which means that an
entity can be a member of, at most, one subclass of the specialization.
 The d in the specialization circle stands for disjoint.
 If the subclasses are not constrained to be disjoint, they overlap.
 Overlap means that an entity can be a member of more than one subclass of the
specialization.
 Overlap constraint is shown by placing an o in the specialization circle.
Completeness Constraint
 The completeness constraint may be either total or partial.
 A total specialization constraint specifies that every entity in the superclass must be a
member of at least one subclass of the specialization.
 Total specialization is shown by using a double line to connect the super class to the
circle.
 A single line is used to display a partial specialization, meaning that an entity does not
have to belong to any of the subclasses.

Disjointness vs. Completeness


 Disjoint constraints and completeness constraints are independent. The following
possible constraints on specializations are possible:
Disjoint, total

Department

Academic Administrative

Disjoint, partial

Employee

Secretary Analyst Engineer

Overlapping, total

Part

Manufactured Puchased
Overlapping, partial

Movie

Children Comedy Drama

Weak Entities
A weak entity is a type of entity which doesn’t have its key attribute. It can
be identified uniquely by considering the primary key of another entity. For
that, weak entity sets need to have participation.

The relation between one strong and one weak entity is represented by a
double diamond. This relationship is also known as identifying relationship.

In above ER Diagram examples, “Trans No” is a discriminator within a


group of transactions in an ATM.
Let’s learn more about a weak entity by comparing it with a Strong Entity

Strong Entity Set Weak Entity Set

Strong entity set always has a It does not have enough attributes
primary key. to build a primary key.

It is represented by a rectangle It is represented by a double


symbol. rectangle symbol.

It contains a Primary key It contains a Partial Key which is


represented by the underline represented by a dashed underline
symbol. symbol.

The member of a strong entity set The member of a weak entity set
is called as dominant entity set. called as a subordinate entity set.

In a weak entity set, it is a


Primary Key is one of its attributes
combination of primary key and
which helps to identify its member.
partial key of the strong entity set.

The relationship between one


In the ER diagram the relationship
strong and a weak entity set shown
between two strong entity set
by using the double diamond
shown by using a diamond symbol.
symbol.

The connecting line of the strong The line connecting the weak entity
entity set with the relationship is set for identifying relationship is
single. double.
Relationship
A relationship is used to describe the relation between entities. Diamond
or rhombus is used to represent the relationship.

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.

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.

One-to-One Association With Mandatory Relationship

One-to-One Association With Optional Relationship

One-to-Many Association With Mandatory Relationship


Many-to-Many Association With Mandatory Relationship

Many-to-Many Association With Optional Relationship

Participation Constraints
 Total Participation − Each entity is involved in the relationship. Total
participation is represented by double lines.
 Partial participation − Not all entities are involved in the relationship. Partial
participation is represented by single lines.

Degree of a relationship set


The number of participating entities in a relationship describes the degree of the relationship.
The three most common relationships in E-R models are:

1. Unary (degree1)
2. Binary (degree2)
3. Ternary (degree3)

1. Unary relationship: This is also called recursive relationships. It is a


relationship between the instances of one entity type. For example, one
person is married to only one person.
2. Binary relationship: It is a relationship between the instances of two entity
types. For example, the Teacher teaches the subject.

3. Ternary relationship: It is a relationship amongst instances of three


entity types. In fig, the relationships "may have" provide the association
of three entities, i.e., TEACHER, STUDENT, and SUBJECT. All three entities
are many-to-many participants. There may be one or many participants in
a ternary relationship.

In general, "n" entities can be related by the same relationship and is


known as n-ary relationship.
Construct an ER diagram for the Banking system

Draw an ER model of the Banking database application considering the following


constraints −
 A bank has many entities.
 Each customer has multiple accounts.
 Multiple customers belong to a single branch.
 Single customer can borrow multiple loans.
 A branch has multiple employees.
Step 1 − Identify the entity sets
The entity set has multiple instances in a given business scenario.
As per the given constraints the entity sets are as follows −
 Customer
 Account
 Account
 Loan
 Loan
Step 2 − Identify the attributes for the given entities
 Customer − the relevant attributes are customerName, CustomerID, address.
 Account − The relevant attributes are AccountNo, balance.
 Branch − The relevant attributes are branchID, branchName, address.
 Loan − The relevant attributes are loanNo, paymentMode, dateOfLoan, and
amount.
 Employee − The relevant attributes are empID, empName, dateOfJoin,
experience, qualification.
Step 3 − Identify the Key attributes
 CustomerID is the key attribute for a customer.
 AccountNo is the key attribute for Account entities.
 BranchID is the key attribute for branch entities.
 LoanNo is the key attribute for a loan entity.
 EmpID is the key attribute for an Employee entity.
Step 4 − Identify the relationship between entity sets
 One customer is enrolled by multiple accounts and one account for multiple
customers. Hence, the relationship is many to many.
How to Create an Entity Relationship Diagram
(ERD)

In a university, a Student enrolls in Courses. A student must be assigned to at least one or


more Courses. Each course is taught by a single Professor. To maintain instruction quality, a
Professor can deliver only one course

Step 1) Entity Identification


We have three entities

 Student
 Course
 Professor
Step 2) Relationship Identification
We have the following two relationships

 The student is assigned a course


 Professor delivers a course

Step 3) Cardinality Identification


For them problem statement we know that,

 A student can be assigned multiple courses


 A Professor can deliver only one course

Step 4) Identify Attributes


You need to study the files, forms, reports, data currently maintained by the
organization to identify attributes. You can also conduct interviews with
various stakeholders to identify entities. Initially, it’s important to identify the
attributes without mapping them to a particular entity.

Once, you have a list of Attributes, you need to map them to the identified
entities. Ensure an attribute is to be paired with exactly one entity. If you
think an attribute should belong to more than one entity, use a modifier to
make it unique.

Once the mapping is done, identify the primary Keys. If a unique key is not
readily available, create one.

Entity Primary Key Attribute

Student Student_ID StudentName

Professor Employee_ID ProfessorName

Course Course_ID CourseName

For Course Entity, attributes could be Duration, Credits, Assignments, etc.


For the sake of ease we have considered just one attribute.

Step 5) Create the ERD Diagram


A more modern representation of Entity Relationship Diagram Example

Sql subqueries:

Subquery or Inner query or a Nested query is a query within another SQL query and
embedded within the WHERE clause.

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


 A subquery can have only one column in the SELECT clause, unless multiple
columns are in the main query for the subquery to compare its selected columns.
 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.
 The SELECT list cannot include any references to values that evaluate to a BLOB,
ARRAY, CLOB, or NCLOB.
 A subquery cannot be immediately enclosed in a set function.
 The BETWEEN operator cannot be used with a subquery. However, the BETWEEN
operator can be used within the subquery.

Subqueries with the SELECT Statement


Subqueries are most frequently used with the SELECT statement. The basic syntax is as
follows −

SELECT column_name [, column_name ]


FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE])

Example
Consider the CUSTOMERS table having the following records −

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 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 |
+----+----------+-----+-----------+----------+

Now, let us check the following subquery with a SELECT statement.

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.

The basic syntax is as follows.

INSERT INTO table_name [ (column1 [, column2 ]) ]


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, you can use the
following syntax.

SQL> INSERT INTO CUSTOMERS_BKP


SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS) ;

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.

The basic syntax is as follows.

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

The basic syntax is as follows.

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.

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 |
+----+----------+-----+---------+----------+

GROUP BY clause:
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

Example
Consider the CUSTOMERS table is having the following records −

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 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 |
+----+----------+-----+-----------+----------+
If you want to know the total amount of the salary on each customer, then the GROUP BY
query would be as follows.

SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS


GROUP BY NAME;

This would produce the following result −

+----------+-------------+
| NAME | SUM(SALARY) |
+----------+-------------+
| Chaitali | 6500.00 |
| Hardik | 8500.00 |
| kaushik | 2000.00 |
| Khilan | 1500.00 |
| Komal | 4500.00 |
| Muffy | 10000.00 |
| Ramesh | 2000.00 |
+----------+-------------+
Now, let us look at a table where the CUSTOMERS table has the following records with
duplicate names −

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Ramesh | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | kaushik | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Now again, if you want to know the total amount of salary on each customer, then the
GROUP BY query would be as follows −

SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS


GROUP BY NAME;

This would produce the following result −

+---------+-------------+
| NAME | SUM(SALARY) |
+---------+-------------+
| Hardik | 8500.00 |
| kaushik | 8500.00 |
| Komal | 4500.00 |
| Muffy | 10000.00 |
| Ramesh | 3500.00 |
+---------+-------------+

 The GROUP BY clause groups records into summary rows.


 GROUP BY returns one records for each group.
 GROUP BY typically also involves aggregates: COUNT, MAX, SUM, AVG, etc.
 GROUP BY can group by one or more columns.

Aggregation:

Aggregate functions perform a calculation on a set of values and return a single value. Except for
COUNT,aggregate functions ignore null values. Aggregatefunctions are frequently used with the GROUP BY
clause of the SELECT statement.

• 1.AVG :- returns the average value

syntax:- Select avg(sal) from emp;

• 2.MIN :- return the minimum value of expr.

syntax :-select min(sal) from emp;

• 3.COUNT :- returns the no. of rows where expr. Is not null

syntax:-select count(acct_no) from acct_mstr;

• 4.COUNT(*) :- Returns the no. of rows in a table including duplicates and


those with null.

syntax:- select count(*)”no of records” from acct_mstr;

• 5.MAX:- Returns the minimum value of expr.

syntax:-select max(curbal) from acct_mstr;

• 6.SUM:-Returns the sum of the value of ‘n’

syntax:-select sum(curbal) from acct_ms

ordering

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
The basic syntax of the ORDER BY clause is as follows −

SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure whatever column
you are using to sort that column should be in the column-list.

Example
Consider the CUSTOMERS table having the following records −

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 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 |
+----+----------+-----+-----------+----------+
The following code block has an example, which would sort the result in an ascending order
by the NAME and the SALARY −

SQL> SELECT * FROM CUSTOMERS


ORDER BY NAME, SALARY;

This would produce the following result −

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+----------+-----+-----------+----------+
The following code block has an example, which would sort the result in the descending
order by NAME.

SQL> SELECT * FROM CUSTOMERS


ORDER BY NAME DESC;
This would produce the following result −

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
+----+----------+-----+-----------+----------+

Implementation of different types of joins


Join in SQL

SQL Join is used to fetch data from two or more tables, which is joined to appear as single set
of data. SQL Join is used for combining column from two or more tables by using values
common to both tables. JoinKeyword is used in SQL queries for joining two or more tables.
Minimum required condition for joining table, is(n-1) where n, is number of tables. A table
can also join to itself known as, Self Join.

Types of Join
The following are the types of JOIN that we can use in SQL.

 Inner
 Outer
 Left
 Right

Cross JOIN or Cartesian Product


This type of JOIN returns the cartesian product of rows from the tables in Join. It will return a
table which consists of records which combines each row from the first table with each row
of the second table.
Cross JOIN Syntax is,
SELECT column-name-list
from table-name1
CROSS JOIN
table-name2;

Example of Cross JOIN


The class table,

ID NAME

1 abhi

2 adam

4 alex

The class_info table,

ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

Cross JOIN query will be,


SELECT *
from class,
cross JOIN class_info;
The result table will look like,

ID NAME ID Address

1 abhi 1 DELHI
2 adam 1 DELHI

4 alex 1 DELHI

1 abhi 2 MUMBAI

2 adam 2 MUMBAI

4 alex 2 MUMBAI

1 abhi 3 CHENNAI

2 adam 3 CHENNAI

4 alex 3 CHENNAI

INNER Join or EQUI Join


This is a simple JOIN in which the result is based on matched data as per the equality
condition specified in the query.
Inner Join Syntax is,
SELECT column-name-list
from table-name1
INNER JOIN
table-name2
on table-name1.column-name = table-name2.column-name;

Example of Inner JOIN


The class table,
ID NAME

1 abhi

2 adam

3 alex

4 anu

The class_info table,

ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

Inner JOIN query will be,


SELECT * from class, class_info where class.id = class_info.id;
The result table will look like,

ID NAME ID Address

1 abhi 1 DELHI

2 adam 2 MUMBAI

3 alex 3 CHENNAI
Natural JOIN
Natural Join is a type of Inner join which is based on column having same name and same
datatype present in both the tables to be joined.
Natural Join Syntax is,
SELECT *
from table-name1
NATURAL JOIN
table-name2;

Example of Natural JOIN


The class table,

ID NAME

1 Abhi

2 Adam

3 Alex

4 Anu

The class_info table,

ID Address
1 DELHI

2 MUMBAI

3 CHENNAI

Natural join query will be,


SELECT * from class NATURAL JOIN class_info;
The result table will look like,

ID NAME Address

1 Abhi DELHI

2 Adam MUMBAI

3 Alex CHENNAI

In the above example, both the tables being joined have ID column(same name and same
datatype), hence the records for which value of ID matches in both the tables will be the
result of Natural Join of these two tables.

Outer JOIN
Outer Join is based on both matched and unmatched data. Outer Joins subdivide further into,

 Left Outer Join


 Right Outer Join
 Full Outer Join

Left Outer Join


The left outer join returns a result table with the matched data of two tables then remaining
rows of the lefttable and null for the right table's column.
Left Outer Join syntax is,
SELECT column-name-list
from table-name1
LEFT OUTER JOIN
table-name2
on table-name1.column-name = table-name2.column-name;
Left outer Join Syntax for Oracle is,
select column-name-list
from table-name1,
table-name2
on table-name1.column-name = table-name2.column-name(+);

Example of Left Outer Join


The class table,

ID NAME

1 Abhi

2 Adam

3 Alex

4 Anu

5 Ashish

The class_info table,

ID Address

1 DELHI

2 MUMBAI
3 CHENNAI

7 NOIDA

8 PANIPAT

Left Outer Join query will be,


SELECT * FROM class LEFT OUTER JOIN class_info ON (class.id=class_info.id);
The result table will look like,

ID NAME ID Address

1 abhi 1 DELHI

2 adam 2 MUMBAI

3 alex 3 CHENNAI

4 anu null null

5 ashish null null


Right Outer Join
The right outer join returns a result table with the matched data of two tables then remaining
rows of the right table and null for the left table's columns.
Right Outer Join Syntax is,
select column-name-list
from table-name1
RIGHT OUTER JOIN
table-name2
on table-name1.column-name = table-name2.column-name;
Right outer Join Syntax for Oracle is,
select column-name-list
from table-name1,
table-name2
on table-name1.column-name(+) = table-name2.column-name;
Example of Right Outer Join
The class table,

ID NAME

1 Abhi

2 Adam

3 Alex

4 Anu

5 Ashish

The class_info table,

ID Address

1 DELHI

2 MUMBAI

3 CHENNAI
7 NOIDA

8 PANIPAT

Right Outer Join query will be,


SELECT * FROM class RIGHT OUTER JOIN class_info on (class.id=class_info.id);
The result table will look like,

ID NAME ID Address

1 Abhi 1 DELHI

2 Adam 2 MUMBAI

3 Alex 3 CHENNAI

null Null 7 NOIDA

null Null 8 PANIPAT

Full Outer Join


The full outer join returns a result table with the matched data of two table then remaining
rows of both lefttable and then the right table.
Full Outer Join Syntax is,
select column-name-list
from table-name1
FULL OUTER JOIN
table-name2
on table-name1.column-name = table-name2.column-name;
Example of Full outer join is,
The class table,

ID NAME

1 Abhi

2 Adam

3 Alex

4 Anu

5 Ashish

The class_info table,

ID Address

1 DELHI

2 MUMBAI

3 CHENNAI

7 NOIDA

8 PANIPAT

Full Outer Join query will be like,


SELECT * FROM class FULL OUTER JOIN class_info on (class.id=class_info.id);
The result table will look like,

ID NAME ID Address
1 Abhi 1 DELHI

2 Adam 2 MUMBAI

3 Alex 3 CHENNAI

4 Anu Null Null

5 Ashish Null Null

Null Null 7 NOIDA

Null Null 8 PANIPAT

Self join

A self join is a regular join, but the table is joined with itself.

SELECT column_name(s)
FROM table1T1,table1T2
WHERE condition;

The SQL SELF JOIN is used to join a table to itself as if the table were two tables; temporarily renaming at least one
table in the SQL statement.
Example
CUSTOMERS Table is as follows.
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 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 |
+----+----------+-----+-----------+----------+
Now, let us join this table using SELF JOIN as follows −
SQL> SELECT a.ID, b.NAME, a.SALARY
FROM CUSTOMERS a, CUSTOMERS b
WHERE a.SALARY < b.SALARY;
This would produce the following result −
+----+----------+---------+
| ID | NAME | SALARY |
+----+----------+---------+
| 2 | Ramesh | 1500.00 |
| 2 | kaushik | 1500.00 |
| 1 | Chaitali | 2000.00 |
| 2 | Chaitali | 1500.00 |
| 3 | Chaitali | 2000.00 |
| 6 | Chaitali | 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 |
+----+----------+---------+
A self join is a join in which a table is joined with itself (which is also called
Unary relationships), especially when the table has a FOREIGN KEY which
references its own PRIMARY KEY. To join a table itself means that each row
of the table is combined with itself and with every other row of the table.
CREATE TABLE employee(emp_id varchar(5) NOT NULL,

emp_name varchar(20) NULL,

dt_of_join date NULL,

emp_supv varchar(5) NULL,

CONSTRAINT emp_id PRIMARY KEY(emp_id) ,

CONSTRAINT emp_supv FOREIGN KEY(emp_supv)

REFERENCES employee(emp_id));

The structure of the table

In the EMPLOYEE table displayed above, emp_id is the primary key.


emp_supv is the foreign key (this is the supervisor’s employee id).

If we want a list of employees and the names of their supervisors, we’ll have
to JOIN the EMPLOYEE table to itself to get this list.

Unary relationship to employee

How the employees are related to themselves:


 An employee may report to another employee (supervisor).

 An employee may supervise himself (i.e. zero) to many employees (subordinates).

We have the following data into the table EMPLOYEE.

The above data shows:

 Unnath Nayar's supervisor is Vijes Setthi

 Anant Kumar and Vinod Rathor can also report to Vijes Setthi.

 Rakesh Patel and Mukesh Singh are under supervison of Unnith Nayar.

Example
To get the list of employees and their supervisor the following SQL statement
has used:

SQL Code:
SELECT a.emp_id AS "Emp_ID",a.emp_name AS "Employee Name",

b.emp_id AS "Supervisor ID",b.emp_name AS "Supervisor Name"

FROM employee a, employee b

WHERE a.emp_supv = b.emp_id;

Output:
VIEWS

In SQL, a view is a virtual table based on the result-set of an SQL statement.

A view contains rows and columns, just like a real table. The fields in a view are fields from
one or more real tables in the database.

You can add SQL functions, WHERE, and JOIN statements to a view and present the data as
if the data were coming from one single table.

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.

The basic CREATE VIEW syntax is as follows −

CREATE VIEW view_name AS


SELECT column1, column2.....
FROM table_name
WHERE [condition];
You can include multiple tables in your SELECT statement in a similar way as you 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 | Ahmedabad | 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.

SQL > CREATE VIEW CUSTOMERS_VIEW AS


SELECT name, age
FROM CUSTOMERS;

Now, you can query CUSTOMERS_VIEW in a similar way as you 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 |
+----------+-----+

The WITH CHECK OPTION


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

The following code block has an example of creating same view CUSTOMERS_VIEW with
the WITH CHECK OPTION.

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.
 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 you can update that view. The
following code block has 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 | Ahmedabad | 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 you can insert rows in a view in a similar
way as you insert them in a table.

Deleting Rows into 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.

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 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 you have a view, you need a way to drop the view if it is no longer
needed. The syntax is very simple and is given below −

DROP VIEW view_name;


Following is an example to drop the CUSTOMERS_VIEW from the CUSTOMERS table.

DROP VIEW CUSTOMERS_VIEW;

Updatable and Insertable Views

Some views are updatable and references to them can be used to specify tables to be updated
in data change statements. That is, you can use them in statements such
as UPDATE, DELETE, or INSERT to update the contents of the underlying table.

For a view to be updatable, there must be a one-to-one relationship between the rows in the
view and the rows in the underlying table. There are also certain other constructs that make a
view nonupdatable. To be more specific, a view is not updatable if it contains any of the
following:

 Aggregate functions (SUM(), MIN(), MAX(), COUNT(), and so forth)


 DISTINCT
 GROUP BY
 HAVING
 UNION or UNION ALL
 Subquery in the select list
 Certain joins
 Reference to nonupdatable view in the FROM clause
 Subquery in the WHERE clause that refers to a table in the FROM clause
 Refers only to literal values (in this case, there is no underlying table to update)

 Multiple references to any column of a base table

You might also like