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

DBMS Unit 2

The document discusses the 12 rules for relational database management systems (RDBMS) proposed by E.F. Codd. It summarizes the rules as follows: 1) All data is represented in tables with rows and columns. 2) Data can be uniquely accessed by its primary key. 3) Null values are supported to represent missing or unknown data. 4) The database structure is also represented as a table that users can query. 5) The database supports a common query language like SQL for data manipulation and definition.

Uploaded by

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

DBMS Unit 2

The document discusses the 12 rules for relational database management systems (RDBMS) proposed by E.F. Codd. It summarizes the rules as follows: 1) All data is represented in tables with rows and columns. 2) Data can be uniquely accessed by its primary key. 3) Null values are supported to represent missing or unknown data. 4) The database structure is also represented as a table that users can query. 5) The database supports a common query language like SQL for data manipulation and definition.

Uploaded by

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

Database Management Systems (DBMS)

# KCS 501

Unit-2
Relational Database
Management System

Computer Science & Engineering


Ajay Kumar Garg Engineering College, Ghaziabad
[email protected]
9557131833
Looping
 Outline
• EF Codd Rule for Relational Model
• Structure of Relational Databases
• Integrity Constraint
• Relational Algebra
• Fundamental Operators and Syntax
 Selection
 Projection
 Cross Product OR Cartesian Product
 Joins
 Set Operators
 Division
 Rename
 Aggregate Functions
• Open Source and Commercial DBMS
Section - 1
Relational Database Management System (RDBMS)
• A relational database management system(RDBMS)is a database management
system (DBMS)that is based on the relational model as introduced by E.F. Codd.
• A short definition of an RDBMS may be a DBMS in which data is stored in the form
of tables and the relationship among the data is also stored in the form of tables.
• The rules mainly define what is required for a DBMS for it to be considered
relational, i.e. an RDBMS.
• E.F. Codd, the famous mathematician has introduced 12 rules (1-12)for the
relational model for databases commonly known as Codd's rules.
• The rules mainly define what is required for a DBMS for it to be
considered relational, i.e., an RDBMS.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 4
Rule 1:- INFORMATION RULE
• All information in the database is to be represented in one and only one way.
• All information in a RDB is represented as values in the form of rows and columns
of tables.
• All information including table names, column names and column data types
should be available in same table within the database.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 5
Rule 2: GUARANTEED ACCESS RULE
• Each unique piece of data should be accessible by: table name+ primary key(row)
+attribute(column).
• All data are uniquely identified and accessible via this identity.
• Most RDBMS do not make the definition of the primary key mandatory and are
deficient to that extent
RollNo Name Branch Semester CGPA Backlog
Primary Key
101 Raju CE 3 8 1

102 Mitesh CI 3 7 1

103 Mayur CE 3 6 2

104 Nilesh EE 3 9 4

105 Hitesh CI 3 7 2

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 6
Rule 3: Systematic Treatment of Null Values
• Null values(different from the empty character string or a string of blank
characters and distinct from zero or any other number) are supported in fully
relational DBMS for representing missing information and inapplicable
information in a systematic way, independent of data type.
• NULLs may mean: Missing data, Not applicable
• Should be handled consistently - Not Zero or Blank
• Primary keys — Not NULL
• Expressions on NULL should give NULL.
• Separate handling of missing and/or non applicable data.
• This is distinct to zero or empty strings

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 7
Rule 3- Systematic Treatment of Null Values

RollNo Name Branch Semester CGPA Backlog

101 Raju CE 3 8 1

102 Mitesh IT 3 7 1

103 Mayur NULL 3 6 2

104 Nilesh CSE 3 9 NULL

105 Hitesh ME 3 7 2 Null Value

Null Value

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 8
Rule 4: DATABASE DESCRIPTION RULE
• The data base description is represented at the logical level in the same way as-
ordinary data, so that authorized users can apply the same relational language to
its interrogation as they apply to the regular data.
• The authorized users can access the database structure by using common
language i.e. SQL.
• It represents the entire logical structure of the descriptive database that must be
stored online and is known as a database dictionary.
• It authorizes users to access the database and implement a similar query
language to access the database.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 9
Rule 5: COMPREHENSIVE DATA SUBLANGUAGE
• A relational system may support several languages and various modes of terminal
use .
• However, there must be at least one language whose statements are expressible,
per some well-defined syntax, as character strings and that is comprehensive in
supporting all the following items :
• Data Definition (Create, Alter, Drop,Truncate)
• Data Manipulation (Insert,Delete, Update)
• Integrity Constraints (primary key, foreign key, null values)
• Authorization (GRANT , REVOKE)
• Transaction boundaries ( commit, rollback etc)

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 10
Rule 6: VIEW UPDATING RULE
• View = ”Virtual table”, temporarily derived from base tables.
• Example: If a view is formed as join of 3 tables, changes to view should be
reflected in base tables.
• Not updatable: View does not have NOT-NULL attribute of base table.
• It allow the update of simple theoretically updatable views, but disallow attempts
to update complex views.
• Different views created for various purposes should be automatically updatable by
the system.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 11
Rule 7: HIGH-LEVEL INSERT , UPDATE AND DELETE
• This rule states that insert, update, and delete operations should be supported for
any retrievable set rather than just for a single row in a single table.
• It also perform the operation on multiple row simultaneously .
• There must be delete, updating and insertion at the each level of operation. Set
operation like union, all union , insertion and minus should also supported.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 12
Rule 8: PHYSICAL DATA INDEPENDENCE
• Any modification in the physical location of a table should not enforce
modification at application level.
• The ability to change the physical schema without changing the logical schema is
called physical data independence.
• This is saying that users shouldn’t be concerned about how the data is stored or
how it’s accessed. In fact, users of the data need only be able to get the basic
definition of the data they need.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 13
Rule 9: LOGICAL DATA INDEPENDENCE
• Any modification in logical or conceptual schema of a table should not enforce
modification at application level.
• The ability to change the logical (conceptual) schema without changing the
External schema (User View) is called logical data independence.
• For example, merging of two tables into one should not affect application
accessing it which is difficult to achieve.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 14
Rule 10: INTEGRITY INDEPENDENCE RULE
• Data integrity refers to maintaining assuring the accuracy and consistency of
data over its entire life cycle.
• Integrity constraints modified at database level should not enforce modification at
application level.
1. First insure that correct data type is used.
2. Check constraints: these allow column value to be checked agenized other
column before insertion is allowed.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 15
Rule 11: Distribution Independence
• Distribution independence implies that user should not have to be aware of
whether a database is distributed at different sites or not.
• Application program and adhoc request are not affected by the change in
distribution of physical data.
• Application program will work even if the programs and data are moved on
different site .

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 16
Rule 12: NON SUB-VERSION RULE
• There should be no way to modify to database structure other then through the
multiple row data base language(SQL).
• Low level access to data should not be able to bypass integrity rule to change
data.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 17
Section - 2
Structure of Relational Databases
Columns (5) Table (Relation): A database object that holds a
collection of data for a specific topic.
Student Table consist of rows and columns.
Attributes:
RollNo Name Branch Semester SPI
Title of column Column (Attribute): The vertical component of a
101 Raju CE 3 8
table. A column has a name and a particular data

Cardinality = No of tuples (7)


102 Mitesh CI 3 7 type; e.g. varchar, decimal, integer, datetime etc.
Rows or 103 Mayur CE 3 6
Tuples or Record (Tuple): The horizontal component of a
104 Nilesh EE 3 9
Records (7) table, consisting of a sequence of values, one for
105 Hitesh CI 3 7 each column of the table. It is also known as row.
106 Tarun ME 3 8
107 Suresh CE 3 9 A database consists of a collection of tables
(relations), each having a unique name.
Degree = No of columns (5)
Domain is a set of all possible unique values for a specific column.
Domain of Branch attribute is (CE, CI, ME, EE)

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 19
Section - 3
Integrity Constraints
• Integrity constraints are a set of rules. It is used to maintain the quality of
information.
• Integrity constraints in Database Management Systems (DBMS) are a set of rules
that are applied on the table columns or relationships to ensure that the overall
validity, integrity, and consistency (i.e. the quality) of the data present in the
database table is maintained
• Integrity constraints ensure that the data insertion, updating, and other processes
have to be performed in such a way that data integrity is not affected.
• Thus, integrity constraint is used to guard against accidental damage to the
database.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 21
Integrity Constraints Types
• There are 6 types of Integrity Constraints:
• Domain Constraint
• Entity Constraint
• Referential Integrity Constraint
• Key Constraint
• Check
• Not Null

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 22
Domain Constraints
• Domain constraints can be defined as the definition of a valid set of values for an
attribute.
• Domain integrity constraint contains a certain set of rules or conditions to restrict
the kind of attributes or values a column can hold in the database table.
• The data type of a domain can be string, integer, character, Date, etc..
RollNo Name Branch Semester AGE
101 Raju CE 3 18
102 Mitesh CI 3 17
103 Mayur CE 3 26 Not Allowed as AGE is
104 Nilesh EE 3 A number attribute

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 23
Entity Integrity Constraints
• Entity Integrity Constraint is used to ensure that the primary key cannot be null.
• A primary key is used to identify individual records in a table and if the primary
key has a null value, then we can't identify those records.
• There can be null values anywhere in the table except the primary key column.
RollNo Name Branch Semester AGE
101 Raju CE 3 18
102 Mitesh CI 3 17
103 Mayur CE 3 26
Nilesh EE 3 25

Not Allowed as Primary


Key can not be Null

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 24
Referential Integrity Constraints
• Referential Integrity Constraint ensures that there must always exist a valid
relationship between two relational database tables.
• This valid relationship between the two tables confirms that a foreign key exists in
a table.
• It should always reference a corresponding value or attribute in the other table or
be null.

Foreign Key

DeptID Dept_Name HOD RollNo Student_Name DeptID


1 Computer Doshi 101 Raj Patel 1
2 IT Vyash 102 Meet Shah 2

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 25
Key Constraints
• Keys are the set of entities that are used to identify an entity within its entity set
uniquely.
• There could be multiple keys in a single entity set, but out of these multiple keys,
only one key will be the primary key.
• A primary key can only contain unique and not null values in the relational
database table.
RollNo Name Branch Semester AGE
101 Raju CE 3 18
102 Mitesh CI 3 17
103 Mayur CE 3 26
102 Nilesh EE 3 25

Not Allowed as Primary


Key must be unique

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 26
Integrity Constraints
• Check
• This constraint defines a business rule on a column. All the rows in that column must
satisfy this rule.
• Limits the data values of variables to a specific set, range, or list of values.
• The constraint can be applied for a single column or a group of columns.
• E.g. value of SPI should be between 0 to 10.
• Not null
• This constraint ensures all rows in the table contain a definite value for the column which is
specified as not null. Which means a null value is not allowed.
• E.g. name column should have some value.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 27
Section - 4
Relational Algebra Operations
Operator Description
Selection Display particular rows/records/tuples from a relation
Projection Display particular columns from a relation
Cross Product Multiply each tuples of both relations
Combine data or records from two or more tables
1. Natural Join / Inner Join
Joins
2. Outer Join
1. Left Outer Join 2. Right Outer Join 3. Full Outer Join
Combine the results of two queries into a single result.
Set Operators
1. Union 2. Intersection 3. Minus / Set-difference
Division Divides one relation by another
Rename Rename a column or a table

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 29
Selection Operator
Section - 4.1
Selection Operator
• Symbol: σ (Sigma)
• Notation: σ condition (Relation)
• Operation: Selects tuples from a relation that satisfy a given condition.
• Operators: =, <>, <, >, <=, >=, Λ (AND), V (OR)
Example Display the detail of students belongs to “CE” Branch. Answer σBranch=‘CE’ (Student)
Student Output
RollNo Name Branch SPI RollNo Name Branch SPI
101 Raju CE 8 101 Raju CE 8
102 Mitesh ME 9 104 Meet CE 9
103 Nilesh CI 9
104 Meet CE 9

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 31
Selection Operator [σ condition (Relation)]

Example Display the detail of students belongs to “CE” Branch and having SPI more than 8.

Student
RollNo Name Branch SPI
101 Raju CE 8
102 Mitesh ME 9
103 Nilesh CI 9
104 Meet CE 9

Answer σBranch=‘CE’ Λ SPI>8 (Student)


Output
RollNo Name Branch SPI
104 Meet CE 9

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 32
Selection Operator [σ condition (Relation)]
Example Display the detail of students belongs to either “CI” or “ME” Branch.

Student
RollNo Name Branch SPI
101 Raju CE 8
102 Mitesh ME 9
103 Nilesh CI 9
104 Meet CE 9

Answer σBranch=‘CI’ V Branch=‘ME’ (Student)


Output
RollNo Name Branch SPI
102 Mitesh ME 9
103 Nilesh CI 9

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 33
Selection Operator [σ condition (Relation)]
Example Display the detail of students whose SPI between 7 and 9.

Student
RollNo Name Branch SPI
101 Raju CE 8
102 Mitesh ME 9
103 Nilesh CI 9
104 Meet CE 9

Answer σSPI>7 Λ SPI<9 (Student)


Output
RollNo Name Branch SPI
101 Raju CE 8

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 34
Exercise
• Write down the relational algebra for the student table. Student
• Display the detail of students whose RollNo is less than 104. RollNo Name Branch SPI
• Display the detail of students having SPI more than 8. 101 Raj CE 6
• Display the detail of students belongs to “CE” Branch having SPI
less than 8. 102 Meet ME 8
• Display the detail of students belongs to either “CE” or “ME” 103 Harsh EE 7
Branch.
• Display the detail of students whose SPI between 6 and 9. 104 Punit CE 9

Employee
 Write down the relational algebra for the employee table.
 Display the detail of all employee. EmpID Name Dept Salary
 Display the detail of employee whose Salary more than 10000. 101 Nilesh Sales 10000
 Display the detail of employee belongs to “HR” Dept having Salary more 102 Mayur HR 25000
than 20000.
103 Hardik HR 15000
 Display the detail of employee belongs to either “HR” or “Admin” Dept.
 Display the detail of employee whose Salary between 10000 and 25000 104 Ajay Admin 20000
and belongs to “HR” Dept.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 35
Projection Operator
Section - 4.2
Projection Operator
• Symbol: ∏ (Pi)
• Notation: ∏ attribute set (Relation)
• Operation: Selects specified attributes of a relation.
• It removes duplicate tuples (records) from the result.
Example Display RollNo, Name and Branch of all students. Answer ∏ RollNo, Name, Branch (Student)

Student Output
RollNo Name Branch SPI RollNo Name Branch
101 Raju CE 8 101 Raju CE
102 Mitesh ME 9 102 Mitesh ME
103 Nilesh CI 9 103 Nilesh CI
104 Meet CE 9 104 Meet CE

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 37
Exercise
• Write down the relational algebra for the student table. Student
RollNo Name Branch SPI
• Display RollNo, Name and SPI of all students.
101 Raj CE 6
• Display Name and SPI of all students.
102 Meet ME 8
• Display the Name of all students.
103 Harsh EE 7
• Display the Name of all branches.
104 Punit CE 9

Employee
 Write down the relational algebra for the employee table.
 Display EmpID with Name of all employee. EmpID Name Dept Salary
 Display Name and Salary of all employee. 101 Nilesh Sales 10000
 Display the Name of all employee. 102 Mayur HR 25000
 Display the Name of all departments. 103 Hardik HR 15000
104 Ajay Admin 20000

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 38
Combined Projection & Selection Operation
Example Display RollNo, Name & Branch of “ME” Branch students.

Student
RollNo Name Branch SPI
101 Raju CE 8
102 Mitesh ME 9
103 Nilesh CI 9
104 Meet CE 7

Step-1 σBranch=‘ME’ (Student) Answer ∏ RollNo, Name, Branch (σBranch=‘ME’ (Student))


Output-1 Output-2
RollNo Name Branch SPI RollNo Name Branch
102 Mitesh ME 9 102 Mitesh ME

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 39
Combined Projection & Selection Operation
Example Display Name, Branch and SPI of students whose SPI is more than 8.

Student
RollNo Name Branch SPI
101 Raju CE 8
102 Mitesh ME 9
103 Nilesh CI 9
104 Meet CE 7

Step-1 σSPI>8 (Student) Answer ∏ Name, Branch, SPI (σSPI>8 (Student))


Output-1 Output-2
RollNo Name Branch SPI Name Branch SPI
102 Mitesh ME 9 Mitesh ME 9
103 Nilesh CI 9 Nilesh CI 9

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 40
Combined Projection & Selection Operation
Example Display Name, Branch and SPI of students who belongs to “CE” Branch and SPI is more than
7.
Student
RollNo Name Branch SPI
101 Raju CE 8
102 Mitesh ME 9
103 Nilesh CI 9
104 Meet CE 7

Step-1 σBranch=‘CE’ Λ SPI>7 (Student) Answer ∏ Name, Branch, SPI (σBranch=‘CE’ Λ SPI>7 (Student))
Output-1 Output-2
RollNo Name Branch SPI Name Branch SPI
101 Raju CE 8 Raju CE 8

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 41
Combined Projection & Selection Operation
Example Display Name of students along with their Branch who belong to either “ME” Branch or “CI” Branch.

Student
RollNo Name Branch SPI
101 Raju CE 8
102 Mitesh ME 9
103 Nilesh CI 9
104 Meet CE 7

Step-1 σBranch=‘ME’ V Branch=‘CI’ (Student) Answer ∏ Name, Branch (σBranch=‘ME’ V Branch=‘CI’ (Student))
Output-1 Output-2
RollNo Name Branch SPI Name Branch
102 Mitesh ME 9 Mitesh ME
103 Nilesh CI 9 Nilesh CI

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 42
Exercise
• Write down the relational algebra for the student table. Student
• Display Rollno, Name and SPI of all students belongs to “CE” Branch. RollNo Name Branch SPI
• List the Name of students with their Branch whose SPI is more than 8 101 Raj CE 6
and belongs to “CE” Branch.
• List the Name of students along with their Branch and SPI who belongs 102 Meet ME 8
to either “CE” or “ME” Branch and having SPI more than 8. 103 Harsh EE 7
• Display the Name of students with their Branch name whose SPI
between 7 and 9. 104 Punit CE 9

 Write down the relational algebra for the employee table. Employee
 Display the Name of employee belong to “HR” Dept and having salary EmpID Name Dept Salary
more than 20000. 101 Nilesh Sales 10000
 Display the Name of all “Admin” and “HR” Dept’s employee.
102 Mayur HR 25000
 List the Name of employee with their Salary who belongs to “HR” or
“Admin” Dept having salary more than 15000. 103 Hardik HR 15000
 Display the Name of employee along with their Dept name whose 104 Ajay Admin 20000
salary between 15000 and 30000.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 43
Cartesian Product / Cross Product
Section - 4.3
Cartesian Product / Cross Product
• Symbol: X (Cross)
• Notation: Relation-1 (R1) X Relation-2 (R2) OR Algebra-1 X Algebra-2
• Operation: It will multiply each tuples of Relation-1 to each tuples of Relation-2.
• Attributes of Resultant Relation = Attributes of R1 + Attributes of R2
• Tuples of Resultant Relation = Tuples of R1 * Tuples of R2
Example Perform Cross Product between Student and Result. Answer (Student) X (Result)

Student Result Output


RNo Name Branch RNo SPI Student.RNo Name Branch Result.RNo SPI
101 Raju CE 101 8 101 Raju CE 101 8
102 Mitesh ME 102 9 101 Raju CE 102 9
102 Mitesh ME 101 8
If both relations have some attribute with the same name, it can be
102 Mitesh ME 102 9
distinguished by combing relation-name.attribute-name.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 45
Cartesian Product / Cross Product Example
Example Perform Cross Product between Student and Result. Consider only selected attributes
• Student – RNo, Name and
Student Branch
Result
• Result – RNo, SPI and BL
RNo Name Branch Sem RNo SPI BL Rank
101 Raju CE 3 101 8 1 2
102 Mitesh ME 5 103 9 0 1

Answer ∏ RNo, Name, Branch (Student) X ∏ RNo, SPI, BL (Result)


Output
Student.RNo Name Branch Result.RNo SPI BL
101 Raju CE 101 8 1
101 Raju CE 103 9 0
102 Mitesh ME 101 8 1
102 Mitesh ME 103 9 0

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 46
Cartesian Product / Cross Product Example
Example Perform Cross Product between Student and Result. Consider only selected tuples
• Student – Branch=‘CE’ and Sem=3
Student Result • Result – SPI>7 and BL<1
RNo Name Branch Sem RNo SPI BL Rank
101 Raju CE 3 101 8 1 2
102 Mitesh ME 5 103 9 0 1
103 Om CE 3 105 7 2 3
104 Dhara CE 5

Answer σBranch=‘CE’ Λ Sem=3 (Student) X σSPI>7 Λ BL<1 (Result)


Output
Student.RNo Name Branch Sem Result.RNo SPI BL Rank
101 Raju CE 3 103 9 0 1
103 OM CE 3 103 9 0 1

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 47
Natural Join / Inner Join
Section - 4.4
Natural Join / Inner Join
• Symbol:
• Notation: Relation-1 (R1) Relation-2 (R2) OR Algebra-1 Algebra-2
• Operation: Natural join will retrieve consistent data from multiple relations.
• It combines records from different relations that satisfy a given condition.

Steps performed in Natural Join


Steps Description
Step – 1 It performs Cartesian Product
Step – 2 Then it deletes inconsistent tuples
Step – 3 Then it removes an attribute from duplicate attributes

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 49
Natural Join / Inner Join Example
Example Perform Natural Join between Student and Result. Answer (Student) (Result)

Student Result Output


RNo Name Branch RNo SPI RNo Name Branch SPI
101 Raju CE 101 8 101 Raju CE 8
102 Mitesh ME 103 9
To perform a Natural Join there must be one common
Steps performed in Natural Join attribute (column) between two relations.

Step:1 Perform Cross Product Step:2 Removes inconsistent tuples


Student.RNo Name Branch Result.RNo SPI Student.RNo Name Branch Result.RNo SPI
101 Raju CE 101 8 101 Raju CE 101 8
101 Raju CE 103 9 Step:3 Removes an attribute from duplicate
102 Mitesh ME 101 8 RNo Name Branch SPI
102 Mitesh ME 103 9 101 Raju CE 8

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 50
Natural Join / Inner Join Example
Example Perform Natural Join between Branch and Faculty. Answer (Branch) (Faculty)

Branch Faculty Output


BID BName HOD FID FName BID BID Bname HOD FID FName
1 CE Shah 101 Raj 1 1 CE Shah 101 Raj
2 ME Patel 103 Meet 2 2 ME Patel 103 Meet

To perform a Natural Join there must be one common attribute (column)


between two relations.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 51
Write down relational algebra for the following tables/relations
• Relations
• Student (Rno, Sname, Address, City, Mobile)
• Department (Did, Dname)
• Academic (Rno, Did, SPI, CPI, Backlog)
• Guide (Rno, PName, Fid)
• Faculty (Fid, Fname, Subject, Did, Salary)
Example List the name of students with their department name and SPI of all student belong to “CE” department.

Answer ∏ Sname, Dname, SPI (σDname=‘CE’ (Student (Department Academic)))

Example Display the name of students with their project name whose guide is “A. J. Shah”.

Answer ∏ Sname, Pname (σFname=‘A.J.Shah’ (Student (Guide Faculty)))

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 52
Exercise: Write down relational algebra for the following tables/relations
• Relations
• Student (Rno, Sname, Address, City, Mobile)
• Department (Did, Dname)
• Academic (Rno, Did, SPI, CPI, Backlog)
• Guide (Rno, PName, Fid)
• Faculty (Fid, Fname, Subject, Did, Salary)
• List the name of students with their department name having backlog 0.
• List the name of faculties with their department name and salary having salary more than 25000 and
belongs to “CE” department.
• List the name of all faculties of “CE” and “ME” department whose salary is more than 50000.
• Display the students name with their project name of all “CE” department’s students whose guide is “Z.Z.
Patel”.
• Display the name of faculties with their department name who belongs to “CE” department and tough
“CPU” subject having salary more than 25000.
• List the name of students with their department name doing project “Hackathon” under guide “I. I. Shah”.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 53
Outer Join
Section - 4.5
Outer Join
• In natural join some records are missing, if we want that missing records than we
have to use outer join.
Three types of Outer Join
Sr. Outer Join Symbol
1 Left Outer Join
2 Right Outer Join
3 Full Outer Join

To perform a Outer Join there must be one common attribute (column)


between two relations.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 55
Left Outer Join
• Symbol:
• Notation: Relation-1 (R1) Relation-2 (R2) OR Algebra-1 Algebra-2
• Operation:
• Display all the tuples of the left relation even through there is no matching tuple in the right
relation.
• For such kind of tuples having no matching, the attributes of right relation will be padded
with NULL in resultant relation.
Example Perform Left Outer Join between Student and Result.
Answer (Student) (Result)
Student Result
RollNo Name Branch RollNo SPI Output
101 Raj CE 101 8 RollNo Name Branch SPI
102 Meet ME 103 9 101 Raj CE 8
Exercise What is the output of (Result) (Student). 102 Meet ME NULL

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 56
Left Outer Join Example
Example Perform Left Outer Join between Student and Result. (Display RollNo, Name and SPI)

Student Result
RollNo Name Branch RollNo SPI BL
101 Raj CE 101 8 1
102 Meet ME 103 9 0

Answer ∏ RollNo, Name, SPI ((Student) (Result))

Output
RollNo Name SPI
101 Raj 8
102 Meet NULL

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 57
Right Outer Join
• Symbol:
• Notation: Relation-1 (R1) Relation-2 (R2) OR Algebra-1 Algebra-2
• Operation:
• Display all the tuples of right relation even through there is no matching tuple in the left
relation.
• For such kind of tuples having no matching, the attributes of left relation will be padded
with NULL in resultant relation.
Perform Right Outer Join between Student and Result. Answer (Student) (Result)
Example
Student Result Output
RollNo Name Branch RollNo SPI RollNo Name Branch SPI
101 Raj CE 101 8 101 Raj CE 8

102 Meet ME 103 9 103 NULL NULL 9

Exercise What is the output of (Result) (Student).


Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 58
Right Outer Join Example
Example Perform Right Outer Join between Student and Result. (Display RollNo, Name and SPI)

Student Result
RollNo Name Branch RollNo SPI BL
101 Raj CE 101 8 1
102 Meet ME 103 9 0

Answer ∏ RollNo, Name, SPI ((Student) (Result))

Output
RollNo Name SPI
101 Raj 8
103 NULL 9

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 59
Full Outer Join
• Symbol:
• Notation: Relation-1 (R1) Relation-2 (R2) OR Algebra-1 Algebra-2
• Operation:
• Display all the tuples of both of the relations. It also pads null values whenever required.
(Left outer join + Right outer join)
• For such kind of tuples having no matching, it will be padded with NULL in resultant
relation.
Example Perform Full Outer Join between Student and Result. Answer (Student) (Result)
Student Result Output
RollNo Name Branch RollNo SPI RollNo Name Branch SPI
101 Raj CE 101 8 101 Raj CE 8
102 Meet ME 103 9 102 Meet ME NULL
103 NULL NULL 9
Exercise What is the output of (Result) (Student).

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 60
Full Outer Join Example
Example Perform Full Outer Join between Student and Result. (Display RollNo, Name and SPI)

Student Result
RollNo Name Branch RollNo SPI BL
101 Raj CE 101 8 1
102 Meet ME 103 9 0

Answer ∏ RollNo, Name, SPI ((Student) (Result))

Output
RollNo Name SPI
101 Raj 8
102 Meet NULL
103 NULL 9
Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 61
Set Operators
Section - 4.6
Set Operators
• Set operators combine the results of two or more queries into a single result.

Three types of Set Operators


Sr. Set Operator Symbol
1 Union U
2 Intersect / Intersection ∩
3 Minus / Set difference −

Conditions Set operators will take two or more queries as input, which must be union-compatible.

• Both queries should have same (equal) number of columns


• Corresponding attributes should have the same data type or domain

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 63
Conditions to perform Set Operators
Conditions-1 Both queries should have same (equal) number of columns.

Student Faculty Student Faculty


RNo Name Dept SPI FId Name Dept RNo Name Dept FId Name Dept
101 Raj CE 8 101 Patel CE 101 Raj CE 101 Patel CE
102 Meet ME 9 102 Shah ME 102 Meet ME 102 Shah ME
103 Jay CE 9 103 Dave ME 103 Jay CE 103 Dave ME

Conditions-2 Corresponding attributes should have the same data type.

Student Faculty Student Faculty


RNo Name Dept SPI FId Name Dept Sub RNo Name Dept SPI FId Name Dept Exp
101 Raj CE 8 101 Patel CE DS 101 Raj CE 8 101 Patel CE 5
102 Meet ME 9 102 Shah ME DBMS 102 Meet ME 9 102 Shah ME 3
103 Jay CE 9 103 Dave ME DF 103 Jay CE 9 103 Dave ME 4

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 64
Set Operators [Exercise]

Exercise Check whether following tables are compatible or not:

• A: (First_name(char), Last_name(char), Date_of_Birth(date))


• B: (FName(char), LName(char), PhoneNumber(number))
Χ (Not compatible) Both tables have 3 attributes but third attributes datatype is different.

• A: (First_name(char), Last_name(char), Date_of_Birth(date))


• B: (FName(char), LName(char), DOB(date))
 (Compatible) Both tables have 3 attributes and of same data type.

• Person (PersonID, Name, Address, Hobby)


• Professor (ProfessorID, Name, OfficeAddress, Salary)
• (Not compatible) Both tables have 4 attributes but forth attributes datatype is different.
∏ Name, Address (Person) & ∏ Name, OfficeAddress (Professor)
• (Compatible) Both tables have 2 attributes and of same data type.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 65
Union Operator
• Symbol: U
• Notation: Relation-1 (R1) U Relation-2 (R2) OR Algebra-1 U Algebra-2
• Operation:
• It displays all the tuples/records belonging to the first relation (left relation) or the second
relation (right relation) or both.
• It also eliminates duplicate tuples (tuples present in both relations appear once).
Example Answer
Perform Union between Customer and Employee. (Customer) U (Employee)
Output
Customer Employee
Name
Name Name
Manoj
Raju Meet
Meet
Suresh Suresh
Raju
Meet Manoj
Suresh
Exercise Is there any difference in the output if we swap the tables in Union operator. (Employee) U (Customer).
Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 66
Intersect/ Intersection Operator
• Symbol: ∩
• Notation: Relation-1 (R1) ∩ Relation-2 (R2) OR Algebra-1 ∩ Algebra-2
• Operation:
• It displays all the tuples/records belonging to both relations. OR
• It displays all the tuples/records which are common from both relations.
Example Perform Intersection between Customer and Employee. Answer (Customer) ∩ (Employee)
Customer Employee Output
Name Name Name
Raju Meet Meet
Suresh Suresh Suresh
Meet Manoj

Exercise Is there any difference in the output if we swap the tables in Intersection. (Employee) ∩ (Customer).
Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 67
Minus/ Set difference Operator
• Symbol: −
• Notation: Relation-1 (R1) − Relation-2 (R2) OR Algebra-1 − Algebra-2
• Operation:
• It displays all the tuples/records belonging to the first relation (left relation) but not in the
second relation (right relation).
Example Perform Set difference between Customer and Employee. Answer (Customer) − (Employee)
Customer Employee Output
Name Name Name
Raju Meet Raju
Suresh Suresh
Meet Manoj

Exercise Is there any difference in the output if we swap the tables in Set difference. (Employee) − (Customer).
Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 68
Union Operators Example

Example Display Name of person who are either employee or customer.


Customer Employee
ID Name Balance ID Name Dept Salary
1 Raju 10000 2 Suresh CE 8000
2 Suresh 20000 3 Manoj ME 9000

Answer ∏ Name (Customer) U ∏ Name (Employee)


Output
Name
Manoj
Raju
Suresh

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 69
Intersect/ Intersection Operators Example

Example Display Name of person who are employee as well as customer.


Customer Employee
ID Name Balance ID Name Dept Salary
1 Raju 10000 2 Suresh CE 8000
2 Suresh 20000 3 Manoj ME 9000

Answer ∏ Name (Customer) ∩ ∏ Name (Employee)


Output
Name
Suresh

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 70
Minus/ Set difference Operators Example

Example Display Name of person who are employee but not customer.
Customer Employee
ID Name Balance ID Name Dept Salary
1 Raju 10000 2 Suresh CE 8000
2 Suresh 20000 3 Manoj ME 9000

Answer ∏ Name (Employee) − ∏ Name (Customer)


Output
Name
Manoj

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 71
Minus/ Set difference Operators Example

Example Display Name of person who are customer but not employee.
Customer Employee
ID Name Balance ID Name Dept Salary
1 Raju 10000 2 Suresh CE 8000
2 Suresh 20000 3 Manoj ME 9000

Answer ∏ Name (Customer) − ∏ Name (Employee)


Output
Name
Raju

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 72
Set Operators [Exercise]
Exercise What is the output of following relational algebra for the below mentioned tables:

Customer Employee
ID Name Balance ID Name Dept Salary
1 Raju 10000 2 Suresh CE 8000
2 Suresh 20000 3 Manoj ME 9000

Algebra-1 ∏ ID, Name (Customer) U ∏ ID, Name (Employee)

Algebra-2 ∏ ID, Name, Balance (Customer) U ∏ ID, Name, Salary (Employee)

Algebra-3 ∏ ID, Name (Customer) ∩ ∏ ID, Name (Employee)

Algebra-4 ∏ ID, Name, Balance (Customer) ∩ ∏ ID, Name, Salary (Employee)

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 73
Set Operators [Exercise]
Exercise What is the output of following relational algebra for the below mentioned tables:

Customer Employee
ID Name Balance ID Name Dept Salary
1 Raju 10000 2 Suresh CE 8000
2 Suresh 20000 3 Manoj ME 9000

Algebra-1 ∏ ID, Name (Customer) − ∏ ID, Name (Employee)

Algebra-2 ∏ ID, Name, Balance (Customer) − ∏ ID, Name, Salary (Employee)

Algebra-3 ∏ ID, Name (Employee) − ∏ ID, Name (Customer)

Algebra-4 ∏ ID, Name, Balance (Employee) − ∏ ID, Name, Salary (Customer)

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 74
Division Operator
Section - 4.7
Division Operator
• Symbol: ÷ (Division)
• Notation: Relation1 (R1) ÷ Relation2 (R2) OR Algebra1 ÷ Algebra2
• Condition:
• Attributes of relation2/algebra2 must be a proper subset of attributes of relation1/algebra1.
• Operation:
• The output of the division operator will have attributes =
All attributes of relation1 – All attributes of relation2
• The output of the division operator will have tuples =
Tuples in relation1, which are associated with the all tuples of relation2.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 76
Division Operator Example
Example Perform Division operation between Student and Subject. Answer (Student) ÷ (Subject)

Student Subject Output


Name Subject Subject Name
Raj DBMS DBMS Rohit
Raj DS DS Suresh
Meet DS DF
Meet DF
Rohit DBMS
Rohit DS
Rohit DF
Suresh DBMS
Suresh DF
Suresh DS

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 77
Division Operator Example

A B1 B2 B3 B4
Sno PNo PNo PNo PNo PNo
S1 P1 P2 P2 P1 P2
S1 P2 P4 P2 P5
S1 P3 P4
S1 P4 Algebra (A) ÷ (B1) Algebra (A) ÷ (B2) Algebra (A) ÷ (B3) Algebra (A) ÷ (B4)
S2 P1
Output Output Output Output
S2 P2
SNo SNo SNo SNo
S3 P2
S1 S1 S1
S4 P2
S2 S4
S4 P4
S3
S5 P4
S4

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 78
Division Operator Example
Example List the name of students doing a project in all technologies.

Student Project
RNo Name Technology TID Technology
101 Raj .NET 1 .NET
101 Raj PHP 2 PHP
102 Meet .NET 3 Android
102 Meet PHP 4 iPhone
102 Meet iPhone
Answer ∏ Name, Technology (Student) ÷ ∏ Technology (Project)
102 Meet Android
103 Rohit Android Output

104 Suresh .NET Name


Meet
104 Suresh iPhone
104 Suresh Android

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 79
Rename Operator
Section - 4.8
Rename Operator
• Symbol: ρ (Rho)
• Notation: ρA (X1,X2….Xn) (Relation)
• Operation:
• The rename operation is used to rename the output relation.
• The result of rename operator are also relations with new name.
• The original relation name can not be changed when we perform rename operation on any
relation.
• How to use:
• ρ x (E)
Returns a relation E under a new name X.
• ρ A1, A2. …,An (E)
Returns a relation E with the attributes renamed to A1, A2, …., An.
• ρ x(A1, A2. …,An) (E)
Returns a relation E under a new name X with the attributes renamed to A1, A2, …., An.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 81
Rename Operator Example
Example Rename Example Rename attributes
table
Student Student
RNo Name CPI Rno Name CPI
101 Raj 8 101 Raj 8
102 Meet 9 102 Meet 9
103 Jay 7 103 Jay 7

Algebra ρPerson (Student) Algebra ρ(RollNo, StudentName, SPI) (Student)

Person Student
RNo Name CPI RollNo StudentName SPI
101 Raj 8 101 Raj 8
102 Meet 9 102 Meet 9
103 Jay 7 103 Jay 7

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 82
Rename Operator Example
Example Rename table and attributes both Example Rename particular attributes
Student Student
Rno Name CPI Rno Name CPI
101 Raj 8 101 Raj 8
102 Meet 9 102 Meet 9
103 Jay 7 103 Jay 7

Algebra ρPerson (RollNo, StudentName) (∏ RNo, Name (Student)) Algebra ρStudentName / Name (Student)

Person Student
RollNo StudentName Rno StudentName CPI
101 Raj 101 Raj 8
102 Meet 102 Meet 9
103 Jay 103 Jay 7

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 83
Rename Operator Example
Example Find out maximum CPI from student table. Step-1 ρA (Student) X ρB (Student)
Student Output-1
Rno Name CPI A.Rno A.Name A.CPI B.Rno B.Name B.CPI
101 Raj 8 101 Raj 8 101 Raj 8
102 Meet 9 101 Raj 8 102 Meet 9
103 Jay 7 101 Raj 8 103 Jay 7
102 Meet 9 101 Raj 8
Step-2 σA.CPI<B.CPI (ρA (Student) X ρB (Student))
102 Meet 9 102 Meet 9
Output-2 102 Meet 9 103 Jay 7
A.Rno A.Name A.CPI B.Rno B.Name B.CPI 103 Jay 7 101 Raj 8
101 Raj 8 102 Meet 9 103 Jay 7 102 Meet 9
103 Jay 7 101 Raj 8 103 Jay 7 103 Jay 7
103 Jay 7 102 Meet 9

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 84
Rename Operator Example
Example Find out maximum CPI from student table.
Student
Step-3 ∏ A.CPI (σA.CPI<B.CPI (ρA (Student) X ρB (Student)))
Rno Name CPI
101 Raj 8 Output-3
A.CPI
102 Meet 9
8
103 Jay 7
7
Step-2 σA.CPI<B.CPI (ρA (Student) X ρB (Student))

Output-2
A.Rno A.Name A.CPI B.Rno B.Name B.CPI
101 Raj 8 102 Meet 9
103 Jay 7 101 Raj 8
103 Jay 7 102 Meet 9

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 85
Rename Operator Example
Example Find out maximum CPI from student table.
Student
Step-3 ∏ A.CPI (σA.CPI<B.CPI (ρA (Student) X ρB (Student)))
Rno Name CPI
101 Raj 8 Output-3
A.CPI
102 Meet 9
8
103 Jay 7
7

Step-4 ∏ CPI (Student) − ∏ A.CPI (σA.CPI<B.CPI (ρA (Student) X ρB (Student)))

Student Output-3 Output


CPI A.CPI CPI
8 − 8 = 9
9 7
7
Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 86
Aggregate Functions
Section - 4.9
Aggregate Functions
• Symbol: g or G
• Notation: g function-name(column), function-name(column), …, function-name(column) (Relation)
• Operation:
• It takes a more than one value as input and returns a single value as output (result).
• Aggregate functions are:
• Sum (It returns the sum (addition) of the values of a column.)
• Max (It returns the maximum value for a column.)
• Min (It returns the minimum value for a column.)
• Avg (It returns the average of the values for a column.)
• Count (It returns total number of values in a given column.)

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 88
Aggregate Functions Example
Student
Example Find out sum of CPI of all students. Output
Rno Name Branch Semester CPI
sum
101 Ramesh CE 3 9 Answer g sum(CPI) (Student)
73
102 Mahesh EC 3 8
103 Suresh ME 4 7 Example Find out maximum & minimum CPI. Output
104 Amit EE 4 8 max min
Answer g max(CPI), min(CPI) (Student)
105 Anita CE 4 8 9 7

106 Reeta ME 3 7 Example Count the number of students. Output


107 Rohit EE 4 9 count
108 Chetan CE 3 8
Answer g count(Rno) (Student)
9
109 Rakesh CE 4 9
Example Find out average of CPI of all students. Output
avg
Answer g avg(CPI) (Student)
8.11

Dr. Anuj Kumar Singh #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 89
Relational Algebra [Exercise]
• Write down relational algebras for the following table:
• Employee (person-name, street, city)
• Works (person-name, company-name, salary)
• Company (company-name, city)
• Managers (person-name, manager-name)
• Find the names of all employees who work for “TCS”.
• Find the names and cities of residence of all employees who work for “Infosys”.
• Find the names, street and city of residence of all employees who work for “ITC” and earn more than
$10,000 per annum.
• Find the names of all employees in this database who live in the same city as the company for which
they work.
• Find the names of all employees working in “TCS” who earn more than 25000 and less than 40000.
• Find the name of employee whose manager is “Ajay Patel” and salary is more than 50000.
• Display the name of employee with street, city, company name, salary and manager name staying in
“Rajkot” and working in “Ahmedabad”.
• Find maximum, minimum and average salary of all employee.
• Find out the total number of employee.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 90
Questions asked in AKTU
1. Define Super key, Primary key, Candidate key and Alternate key.
2. Explain following Relational Algebra Operation with example.
I. Selection
II. Projection
III. Cross Product
IV. Joins (Inner Join, Outer Joins)
V. Rename
VI. Division
VII. Set operators
3. Explain different aggregate functions with example.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 91
Questions asked in AKTU [Relational Algebra]
4. Consider the following relational database, where the primary keys are
underlined. Give an expression in the relational algebra to express each of the
following queries
• employee (ssn, name, dno, salary, hobby, gender)
• department (dno, dname, budget, location, mgrssn)
• works_on (ssn, pno)
• project (pno, pname, budget, location, goal)
I. List all pairs of employee names and the project numbers they work on.
II. List out department number, department name and department budget.
III. List all projects that Raj Yadav works on by project name.
IV. List the names of employees who supervise themselves.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 92
Questions asked in AKTU [Relational Algebra]
5. Consider the following relational database, where the primary keys are
underlined. Give an expression in the relational algebra to express each of the
following queries
• course (course-id, title, dept_name, credits)
• instructor (id, name, dept_name, salary)
• section (course-id, sec-id, semester, year, building, room_no, time_slot_id)
• teaches (id, course-id, sec-id, semester, year)
I. Find the name of all instructors in the physics department.
II. Find all the courses taught in the fall 2009 semester but not in Spring semester.
III. Find the names of all instructors in the Comp. Sci. department together with the course
titles of all the courses that the instructors teach.
IV. Find the average salary in each department.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 93
Questions asked in AKTU [Relational Algebra]
6. Consider the following relations and write an relational algebra:
• EMP (empno, ename, jobtitle, managerno, hiredate, sal, commission, deptno)
• DEPT (deptno, dname, location)
I. Find the Employees working in the department number10, 20, 30 only.
II. Find Employees whose names start with letter A or letter a.
III. Find Employees along with their department name.
IV. Find the Employees who are working in Smith's department
V. Find the Employees who get salary more than Allen’s salary.
VI. Display employees who are getting maximum salary in each department.
VII. Find list of employees whose hire date is on or before 1-April-18.
7. Consider the relational database given below and give an expression in the relational
algebra:
• Employee (person-name, street, city) , Works (person-name, company-name, salary)
• Company (company-name, city) , Manages (person-name, manager-name)
I. Find the names of all employees in this database who live in the same city as the company for
which they work.
II. Find the names, street address, and cities of residence of all employees who work for HCL and
earn more than $10,000 per annum.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 94
Questions asked in AKTU [Relational Algebra]
8. The relational database schema is given below and write the relational algebra expressions
for the given queries.
• employee (person-name, street, city)
• works (person-name, company-name, salary)
• company (company-name, city)
• manages (person-name, manager-name)
I. Find the names of all employees who work for First Bank Corporation.
II. Find the names and cities of residence of all employees who work for First Bank
Corporation.
III. Find the names, street address, and cities of residence of all employees who work for
First Bank Corporation and earn more than $10,000 per annum.
IV. Find the names of all employees in this database who do not work for First Bank
Corporation.

Ms. Sonali Gahlot #KCS 501 (DBMS)  Unit 2 – Relational Query Languages 95
Database Management Systems (DBMS)
# KCS 501

Thank
You

Computer Science & Engineering


Ajay Kumar Garg Engineering College, Ghaziabad
[email protected]
9557131833
Topics to be covered
• View
• Stored Procedures
• Database Triggers
• Cursors

1
Advantages of PL/SQL
 Block structure:
• PL/SQL consist of block of code, which can be nested within each other.
• Each block forms a unit of a task or a logical module.
• PL/SQL blocks can be stored in the database and reused.
 Procedural language capability:
• PL/SQL consist of procedural constructs such as conditional statements (if, if
else, nested if, else if ladder) and loops (for, while, do while).
 Better performance:
• PL/SQL engine processes multiple SQL statements simultaneously as a single
block, thereby reducing network traffic.
 Error handling:
• PL/SQL handles errors or exceptions effectively during the execution of PL/SQL
program.
• Once an exception is caught, specific action can be taken depending upon the
type of the exception or it can be displayed to the user with message.

2
View
 In SQL, a VIEW is a virtual relation based on the result-set of a
SELECT 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.
 In some cases, we can modify a view and present the data as if the
data were coming from a single table.
 Syntax:-
CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition;

3
Example of view
 Consider the CUSTOMERS table having the following records:
ID NAME AGE CITY SALARY
1 Ramesh 32 Ahmedabad 20000
2 Karan 35 Rajkot 15000
3 Mayur 30 Surat 22000
4 Dipak 35 Rajkot 20000
5 Nilesh 38 Surat 29000
6 Kalpesh 37 Ahmedabad 26000

 We create a view that contain customer name and age from


CUSTOMERS table:

4
Example of view
 Syntax:- NAME AGE
Ramesh 32
CREATE VIEW CUSTOMERS_VIEW AS Karan 35
SELECT name, age Mayur 30
Dipak 35
FROM CUSTOMERS;
Nilesh 38
Kalpesh 37
 Now, you can query CUSTOMERS_VIEW in similar way as you
query an actual table. Following is the example:
SELECT * FROM CUSTOMERS_VIEW;

5
Stored procedure
 A stored procedure (proc) is a group of PL/SQL statements that
performs specific task.
 A procedure has two parts, header and body.
 The header consists of the name of the procedure and the
parameters passed to the procedure.
 The body consists of declaration section, execution section and
exception section.
 A procedure may or may not return any value. A procedure may
return more than one value.

6
Stored procedure (Syntax)
 CREATE [OR REPLACE] PROCEDURE procedure_name
[list of parameters]
AS
sql_statement

7
Stored procedure
 Create:-It will create a procedure.
 Replace :- It will re-create a procedure if it already exists.
 We can pass parameters to the procedures in three ways.
1. IN-parameters: - These types of parameters are used to send values to
stored procedures.
2. OUT-parameters: - These types of parameters are used to get values from
stored procedures. This is similar to a return type in functions but
procedure can return values for more than one parameters.
3. IN OUT-parameters: - This type of parameter allows us to pass values into
a procedure and get output values from the procedure.

8
Stored procedure
 AS indicates the beginning of the body of the procedure.
 sql_statement contains the SQL query. (select, insert, update or
delete)
 The syntax within the brackets [ ] indicates that they are optional.
 By using CREATE OR REPLACE together the procedure is created if
it does not exist and if it exists then it is replaced with the current
code.

9
How to execute a stored procedure?
 There are two ways to execute a procedure.
1. From the SQL prompt.
Syntax: EXECUTE [or EXEC] procedure_name (parameter);
2. Within another procedure: simply use the procedure name.
Syntax: procedure_name (parameter);

10
Advantages of stored procedure
 Security:- We can improve security by giving rights to selected
persons only.
 Faster Execution:- It is precompiled so compilation of procedure
is not required every time you call it.
 Sharing of code:- Once procedure is created and stored, it can be
used by more than one user.
 Productivity:- Code written in procedure is shared by all
programmers. This eliminates redundant coding by multiple
programmers so overall improvement in productivity.

11
Example of stored procedure
 CREATE [OR ALTER] PROCEDURE get_studentname_by_id
@id int
AS
SELECT studentname FROM student WHERE studentID = @id;

 Execute:- EXEC get_studentname_by_id 10

 Explanation:- Above procedure gives the name of student whose


id is 10.

12
Database triggers
 A trigger is a PL/SQL block structure which is triggered (executed)
automatically when DML statements like Insert, Delete, and
Update is executed on a table.
 In SQL Server we can create the following 3 types of triggers:
1. Data Definition Language (DDL) triggers
2. Data Manipulation Language (DML) triggers
3. Logon triggers

13
Data Definition Language (DDL) triggers
 In SQL Server we can create triggers on DDL statements (like
CREATE, ALTER and DROP) and certain system-defined Stored
Procedures that does DDL-like operations.

14
Data Manipulation Language (DML) triggers
 In SQL Server we can create triggers on DML statements (like
INSERT, UPDATE and DELETE) and Stored Procedures that do
DML-like operations. DML Triggers are of two types.
1. After trigger (using FOR/AFTER CLAUSE)
2. Instead of trigger (using INSTEAD OF CLAUSE)

15
Data Manipulation Language (DML) triggers
 DML Triggers are of two types.
1. After trigger (using FOR/AFTER CLAUSE) : After triggers are
executed after completing the execution of DML statements.
• Example: If you insert a record/row into a table then the
trigger related/associated with the insert event on this table
will executed only after inserting the record into that table.
• If the record/row insertion fails, SQL Server will not execute
the after trigger.

16
Data Manipulation Language (DML) triggers
 DML Triggers are of two types.
2. Instead of Trigger (using INSTEAD OF CLAUSE) : Instead of
trigger are executed before starts the execution of DML
statements.
• An instead of trigger allows us to skip an INSERT, DELETE, or
UPDATE statement to a table and execute other statements
defined in the trigger instead. The actual insert, delete, or
update operation does not occur at all.
• Example: If you insert a record/row into a table then the trigger
related/associated with the insert event on this table will be
executed before inserting the record into that table.
• If the record/row insertion fails, SQL Server will execute the
Instead of Trigger.
17
Logon triggers
 This type of trigger is executed against a LOGON event before a
user session is established to the SQL Server.

18
Database triggers
 When triggers can be used,
• Based on change in one table, we want to update other table.
• Automatically update derived columns whose values change based on other
columns.
• Logging.
• Enforce business rules.

19
Triggers (syntax)
 CREATE [OR ALTER] TRIGGER trigger_name
ON table_name
{ FOR | AFTER | INSTEAD OF }
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }

AS
BEGIN
Executable statements
END;

20
Triggers
 CREATE [OR ALTER ] TRIGGER trigger_name:-
• This clause creates a trigger with the given name or overwrites an existing
trigger.
 ON table_name:-
• This clause identifies the name of the table or view to which the trigger is
related.
 { FOR | AFTER | INSTEAD OF }:-
• This clause indicates at what time the trigger should be fired. Before
executing DML statements or after executing DML statements.

21
Triggers
 { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] } :-
• This clause determines on which kind of statement the trigger should be
fired.
• Either on insert or update or delete or combination of any or all.
• More than one statement can be used together separated by comma. The
trigger gets fired at all the specified triggering event.

22
Example of triggers
 Trigger to display a message when we perform insert operation on
student table.

CREATE TRIGGER student_msg


on Student
AFTER INSERT
AS
BEGIN
print ‘Record inserted successfully'
END

23
Example of triggers
 OUTPUT:- Trigger is created.
 Now when you perform insert operation on student table.
 SQL:> Insert into student values (101, ‘Raj’, ‘CE’);
 It displays following message after executing insert statement.
 Output:- Record inserted successfully
 We get message that “Record inserted successfully” it indicates
that trigger has executed after the insertion operation.

24
Example of triggers
 Trigger to display a message when we perform insert, update or
delete operation on student table.

CREATE TRIGGER student_msg


on Student
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
print ‘One record is affected'
END

25
Example of triggers
 OUTPUT:- Trigger is created.
 Now when you perform insert, update or delete operation on
student table.
 SQL:> Insert into student values (102, ‘Raj’, ‘CE’); OR
Update student set Dept=‘EC’ where Rno=101 OR
Delete from student where Rno=101
 It displays following message after executing insert, update or
delete statement.
 Output:- One record is affected
 We get message that “One record is affected” it indicates that
trigger has executed after the insertion operation.

26
Example of triggers
 Trigger to insert history into Audit table when we perform insert
operation on student table.
CREATE TRIGGER tgr_student_forinsert
ON Student
FOR INSERT
AS
BEGIN
DECLARE @id int
SELECT @rno= rno from INSERTED
INSERT INTO Audit VALUES
('New student with rno=‘ + cast(@rno as varchar(10)) +
'is added on‘ + cast(getdate() as varchar(50)))
END

27
Cursor
 Cursors are database objects used to traverse the results of a
select SQL query.
 It is a temporary work area created in the system memory when
a select SQL statement is executed.
 This temporary work area is used to store the data retrieved from
the database, and manipulate this data.
 It points to a certain location within a record set and allow the
operator to move forward (and sometimes backward, depending
upon the cursor type).
 We can process only one record at a time.
 The set of rows the cursor holds which is called the active set
(active data set).
 Cursors are often criticized for their high overhead.

28
Types of cursor
 There are two types of cursors in PL/SQL:
1. Implicit cursors:
• These are created by default by SQL itself when DML statements like, insert,
update, and delete statements are executed.
• They are also created when a SELECT statement returns just one row.
• We cannot use implicit cursors for user defined work.
2. Explicit cursors:
• Explicit cursors are user defined cursors written by the developer.
• They can be created when a SELECT statement returns more than one row.
• Even though the cursor stores multiple records, only one record can be
processed at a time, which is called as current row.
• When you fetch a row, the current row position moves to next row.

29
Steps to manage explicit cursor
1. Declare Cursor: A cursor is declared by defining the SQL
statement that returns a result set.
2. Open: A Cursor is opened and populated by executing the SQL
statement defined by the cursor.
3. Fetch: When the cursor is opened, rows can be fetched from the
cursor one by one or in a block to perform data manipulation.
4. Close: After data manipulation, close the cursor explicitly.
5. Deallocate: Finally, delete the cursor definition and release all
the system resources associated with the cursor.

30
Explicit cursor
 An explicit cursor is defined in the declaration section of the
PL/SQL Block.
 It is created on a SELECT Statement which returns more than one
row. A suitable name for the cursor.
 General syntax for creating a cursor:
CURSOR cursor_name IS select_statement;
• cursor_name – A suitable name for the cursor.
• select_statement – A select query which returns multiple rows

31
How to use explicit cursor?
 There are four steps in using an Explicit Cursor.
1. DECLARE the cursor in the Declaration section.
2. OPEN the cursor in the Execution Section.
3. FETCH the data from the cursor into PL/SQL variables or records in the
Execution Section.
4. CLOSE the cursor in the Execution Section before you end the PL/SQL
Block.

32
Syntax of explicit cursor
DECLARE variables;
records;
create a cursor;
BEGIN
OPEN cursor;
FETCH cursor;
process the records;
CLOSE cursor;
END;

33
Example of cursor
 Cursor to insert record from student table to student1 table if branch is CE.
DECLARE @rno int, @name varchar(50),@branch varchar(50);
DECLARE cursor_student CURSOR
FOR SELECT rno, name, branch FROM student;
OPEN cursor_student;
FETCH NEXT FROM cursor_student INTO @rno, @name, @branch;
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@branch='CE')
INSERT INTO student1 values (@rno, @name, @branch)
FETCH NEXT FROM cursor_student INTO @rno, @name, @branch;
END;
CLOSE cursor_student;
DEALLOCATE cursor_student;

34
Example of cursor
 Cursor to update SPI (SPI=SPI-7) if SPI remains greater than or
equal to ZERO after update.
DECLARE
@rno int, @spi decimal(8,2);
DECLARE cursor_student CURSOR
FOR SELECT rno, spi FROM student;
OPEN cursor_student;
FETCH NEXT FROM cursor_student INTO @rno, @spi;
WHILE @@FETCH_STATUS = 0

35
Example of cursor (Cont…)
 Cursor to update SPI (SPI=SPI-7) if SPI remains greater than or
equal to ZERO after update.
BEGIN
set @spi=@spi-7
if (@spi<0)
print 'SPI must be greater than 0'
else
update student set spi=@spi where rno=@rno
FETCH NEXT FROM cursor_student INTO @rno, @spi;
END;
CLOSE cursor_student;
DEALLOCATE cursor_student;

36
Relational Calculus

 What is Relational Calculus?

 Relational calculus is a non-procedural query language


that tells the system what data to be retrieved but doesn’t
tell how to retrieve it.

 Contrary to Relational Algebra which is a procedural


query language to fetch data and which also explains
how it is done, Relational Calculus in non-procedural
query language and has no description about how the
query will work or the data will b fetched. It only focusses
on what to do, and not on how to do it.
Tuple Relational Calculus
Tuple Relational Calculus

 A nonprocedural query language, where each query is of the form


{t | P (t) }
 It is the set of all tuples t such that predicate P is true for t
 t is a tuple variable, t[A] denotes the value of tuple t on attribute A
 t ∈ r denotes that tuple t is in relation r
 P is a formula similar to that of the predicate calculus
Predicate Calculus Formula

1. Set of attributes and constants


2. Set of comparison operators: (e.g., <, ≤, =, ≠, >, ≥)
3. Set of connectives: and (∧), or (v)‚ not (¬)
4. Implication (⇒) x ⇒ y, if x if true, then y is true
x ⇒ y ≡ ¬x v y
5. Set of quantifiers:
 ∃ t ∈ r (Q(t)) ≡ ”there exists” a tuple in t in relation r
such that predicate Q(t) is true
 ∀t ∈ r (Q(t)) ≡ Q is true “for all” tuples t
in relation r
Tuple Relational Calculus
Tuple Relational Calculus
Tuple Relational Calculus
Tuple Relational Calculus
Banking Example
branch (branch-name, branch-city, assets)

customer (customer-name, customer-street, customer-only)

account (branch-name, account-number, balance)

loan (branch-name, loan-number, amount)

depositor (customer-name, account-number)

borrower (customer-name, loan-number)


Example Queries

 Find the branch-name, loan-number, and amount for loans of over


$1200
{t | t ∈ loan ∧ t [amount] > 1200}

 Find the loan number for each loan of an amount greater than
$1200
{t | ∃ s ∈ loan (t[loan-number] = s[loan-number]
∧ s [amount] > 1200}

Notice that a relation on schema [customer-name] is implicitly


defined by the query
Example Queries

 Find the names of all customers having a loan, an account,


or both at the bank
{t | ∃s ∈ borrower(t[customer-name] = s[customer-name])
v ∃u ∈ depositor(t[customer-name] = u[customer-name])

 Find the names of all customers who have a loan and an


account at the bank

{t | ∃s ∈ borrower(t[customer-name] = s[customer-name])
∧ ∃u ∈ depositor(t[customer-name] = u[customer-name])
Example Queries

 Find the names of all customers having a loan at the


Perryridge branch
{t | ∃s ∈ borrower(t[customer-name] = s[customer-name]
∧ ∃u ∈ loan(u[branch-name] = “Perryridge”
∧ u[loan-number] = s[loan-number]))}

 Find the names of all customers who have a loan at the


Perryridge branch, but no account at any branch of the
bank
{t | ∃s ∈ borrower(t[customer-name] = s[customer-name]
∧ ∃u ∈ loan(u[branch-name] = “Perryridge”
∧ u[loan-number] = s[loan-number]))
∧ not ∃v ∈ depositor (v[customer-name] =
t[customer-name]) }
Example Queries

 Find the names of all customers having a loan from the


Perryridge branch, and the cities they live in

{t | ∃s ∈ loan(s[branch-name] = “Perryridge”
∧ ∃u ∈ borrower (u[loan-number] = s[loan-
number]
∧ t [customer-name] = u[customer-name])
∧ ∃ v ∈ customer (u[customer-name] =
v[customer-name]
∧ t[customer-city] = v[customer-
city])))}
Example Queries

 Find the names of all customers who have an account at


all branches located in Brooklyn:

{t | ∃ c ∈ customer (t[customer.name] = c[customer-


name]) ∧
∀ s ∈ branch(s[branch-city] = “Brooklyn” ⇒
∃ u ∈ account ( s[branch-name] = u[branch-
name]
∧ ∃ s ∈ depositor ( t[customer-name] =
s[customer-name]
∧ s[account-number] = u[account-
number] )) )}
Safety of Expressions

 It is possible to write tuple calculus expressions that


generate infinite relations.
 For example, {t | ¬ t ∈ r} results in an infinite relation
if the domain of any attribute of relation r is infinite
 To guard against the problem, we restrict the set of
allowable expressions to safe expressions.
 An expression {t | P(t)} in the tuple relational calculus
is safe if every component of t appears in one of the
relations, tuples, or constants that appear in P
Domain Relational Calculus

 A nonprocedural query language equivalent in power to


the tuple relational calculus
 Each query is an expression of the form:

{ < x1, x2, …, xn > | P(x1, x2, …, xn)}

 x1, x2, …, xn represent domain variables


 P represents a formula similar to that of the predicate
calculus
Example Queries

 Find the branch-name, loan-number, and amount for


loans of over $1200

{< b, l, a > | < b, l, a > ∈ loan ∧ a > 1200}


 Find the names of all customers who have a loan of over
$1200

{< c > | ∃ b, l, a (c, l > ∈ borrower ∧ < b, l, a > ∈ loan ∧


a > 1200)}
 Find the names of all customers who have a loan from
the Perryridge branch and the loan amount:

{< c, a > | ∃ l (< c, l > ∈ borrower


Example Queries

 Find the names of all customers having a loan, an


account, or both at the Perryridge branch:
{< c > | ∃ l({< c, l > ∈ borrower
∧ ∃ b,a(< b, l, a > ∈ loan ∧ b = “Perryridge”))
∧ ∃ a(< c, a > ∈ depositor
∧ ∃ b,n(< b, a, n > ∈ account ∧ b =
“Perryridge”))}

 Find the names of all customers who have an account at


all branches located in Brooklyn:
{< c > | ∀ x,y,z(< x, y, z > ∈ branch ∧ y = “Brooklyn”) ⇒
∃ a,b(< x, y, z > ∈ account ∧ < c,a > ∈ depositor)}

You might also like