DBMS Unit 2
DBMS Unit 2
UNIT- II
Relational Algebra and Calculus: Relational Algebra - Selection and Projection, Set
operations, Renaming, Joins, Division, Examples of Algebra Queries, Relational calculus -
Tuple relational Calculus - Domain relational calculus - Expressive Power of Algebra and
calculus.
Form of Basic SQL Query - Examples of Basic SQL Queries, Introduction to Nested Queries,
Correlated Nested Queries, Set - Comparison Operators, Aggregate Operators, NULL values -
Comparison using Null values - Logical connectives - AND, OR and NOT - Impact on SQL
Constructs, Outer Joins, Disallowing NULL values, Complex Integrity Constraints in SQL
Triggers and Active Data bases.
The relational algebra is a procedural query language. It consists of a set of operations that take
one or two relations as input and produce a new relation as their result. The fundamental
operations in the relational algebra are select, project, union, set difference, Cartesian
product, and rename. In addition to the fundamental operations, there are several other
operations namely, set intersection, natural join, division, and assignment.
Fundamental Operations The select, project, and rename operations are called unary
operations, because they operate on one relation. The other three operations operate on pairs of
relations and are, therefore, called binary operations. Various operations are shown as follows:
UNIT – II / 1
DBMS NOTES (R15) VTA – CSE
from a relation
Notation : σp (r)
Where σ stands for selection predicate and r stands for relation. p is prepositional logic formula
which may use connectors like and, or, and not. These terms may use relational operators like −
=, ≠, ≥, < , >, ≤.
Ex 1 : To select those tuples of the loan relation where the branch is “Perryridge,”
Ans : σ branch-name = “Perryridge” (loan)
Ex 2 : Selects tuples from books where subject is 'database'.
σsubject = "database"(Books)
Ex 3 : Selects tuples from books where subject is 'database' and 'price' is 450.
σsubject = "database" and price = "450"(Books)
Ex 4 : Selects tuples from books where subject is 'database' and 'price' is
450 or those books published after 2010.
UNIT – II / 2
DBMS NOTES (R15) VTA – CSE
Project Operation (∏) : Projection is the operation of selecting certain attributes from a
relation R to form a new relation. i.e The projection operator π allows us to extract
Ex 1 : Selects columns named as subject and author from the relation Books
UNIT – II / 3
DBMS NOTES (R15) VTA – CSE
Ex1 : Select the names of the authors who have either written a book or an article or both.
Notation : r − s
Ex2 : Provides the name of authors who have written books but not articles
∏ author (Books) − ∏ author (Articles)
Notation : r Χ s
The rename operation allows us to rename the output relation. 'rename' operation is denoted with
UNIT – II / 4
DBMS NOTES (R15) VTA – CSE
Set intersection
Assignment
Natural join
Set intersection : R ∩ S' returns a relation instance containing all tuples that occur in both R and
S. The relations Rand S must be union-compatible.
Assignment : It provides a convenient way to express complex queries. Assignment must always
be made to a temporary relation variable.
Joins : The join operation is one of the most useful operations in relational algebra and the
most commonly used way to combine information from two or more relations. Although a join
can be defined as a cross-product followed by selections and projections. It is denoted by ⋈.
Condition Join or Theta Join : Theta join combines tuples from different relations provided
they satisfy the theta condition. The join condition is denoted by the symbol θ.
Notation : R1 ⋈θ R2
or
R1 and R2 are relations having attributes (A1, A2, .., An) and (B1, B2,.. ,Bn) such that the
attributes don’t have anything in common, that is R1 ∩ R2 = Φ.
Student
SID Name Std
101 Alex 10
102 Maria 11
UNIT – II / 5
DBMS NOTES (R15) VTA – CSE
Subjects
Class Subject
10 Math
10 English
11 Music
11 Sports
Ex : STUDENT ⋈Student.Std = Subject.Class SUBJECT
Student_detail
SID Name Std Class Subject
101 Alex 10 10 Math
101 Alex 10 10 English
102 Maria 11 11 Music
102 Maria 11 11 Sports
Equijoin
When Theta join uses only equality comparison operator, it is said to be equijoin. The above
example corresponds to equijoin.
Natural Join ( ⋈)
It is a binary operator that is written as (R ⋈S) where R and S are relations. The result of the
natural join is the set of all combinations of tuples in R and S that are equal on their common
attribute names. For an example consider the tables Employee and Dept and their natural join:
Employee
Name EmpId DeptName
Dept
DeptName Manager ⋈
Employee Dept
Harry 3415 Finance Finance George DeptNam
Name EmpId Manager
Sally 2241 Sales Sales Harriet e
George 3401 Finance Production Charles Harry 3415 Finance George
Harriet 2202 Sales Sally 2241 Sales Harriet
George 3401 Finance George
Harriet 2202 Sales Harriet
UNIT – II / 6
DBMS NOTES (R15) VTA – CSE
Note : The Default join operation used in the join is Natural Join. But Natural Join operation
results in some loss of Information.
Outer Joins
Theta Join, Equijoin, and Natural Join are called inner joins. An inner join includes only
those tuples with matching attributes and the rest are discarded in the resulting relation.
Therefore, we need to use outer joins to include all the tuples from the participating relations in
the resulting relation. There are three kinds of outer joins − left outer join, right outer join,
and full outer join.
All the tuples from the Left relation, R, are included in the resulting relation. If there are
tuples in R without any matching tuple in the Right relation S, then the S-attributes of the
resulting relation are made NULL.
All the tuples from the Right relation, S, are included in the resulting relation. If there are tuples
in S without any matching tuple in R, then the R-attributes of resulting relation are made NULL.
All the tuples from both participating relations are included in the resulting relation. If there are
no matching tuples for both relations, their respective unmatched attributes are made NULL.
Employee
UNIT – II / 7
DBMS NOTES (R15) VTA – CSE
Works
Division : The division is a binary operation that is written as R ÷ S. The result consists of the
restrictions of tuples in R to the attribute names unique to R, i.e., in the header of R but not in the
header of S, for which it holds that all their combinations with tuples in S are present in R.
Ex 1 :
UNIT – II / 9
DBMS NOTES (R15) VTA – CSE
Eugene Database1
Eugene Compiler1
Sarah Database1
Sarah Database2
Ex 2 :
UNIT – II / 10
DBMS NOTES (R15) VTA – CSE
Output − The above query will yield the same result as the previous one.
In DRC, the filtering variable uses the domain of attributes instead of entire tuple values
Notation −
{ a1, a2, a3, ..., an | P (a1, a2, a3, ... ,an)}
Where a1, a2 are attributes and P stands for formulae built by inner attributes.
For example −
Output − Yields Article, Page, and Subject from the relation TutorialsPoint, where subject is
database.
UNIT – II / 11
DBMS NOTES (R15) VTA – CSE
Just like TRC, DRC can also be written using existential and universal quantifiers. DRC also
involves relational operators.
– e.g.,
The expressive power of relational algebra is often used as a metric of how powerful a relational
database query language is. If a query language can express all the queries that we can express in
relational algebra, it is said to be relationally complete. A practical query language is expected to
be relationally complete; in addition, commercial query languages typically support features
that allow us to express some queries that cannot be expressed in relational algebra.
UNIT – II / 12
DBMS NOTES (R15) VTA – CSE
Every query must have a SELECT clause, which specifies columns to be retained in the
result, and a FROM clause, which specifies a cross-product of tables. The optional WHERE
clause specifies selection conditions on the tables mentioned in the FROM clause.
• The from-list in the FROM clause is a list of table names. A table name can be followed
by a range variable; a range variable is particularly useful when the same table name appears
more than once in the from-list.
• The select-list is a list of column names of tables named in the from-list. Column names
can be prefixed by a range variable.
• The condition in the WHERE clause is a boolean combination (i.e., an expression using
the logical connectives AND, OR, and NOT)
• The DISTINCT keyword is optional. It indicates that the table computed as an answer
to this query should not contain duplicates, that is, two copies of the same row. The default is
that duplicates are not eliminated.
UNIT – II / 13
DBMS NOTES (R15) VTA – CSE
UNIT – II / 14
DBMS NOTES (R15) VTA – CSE
SQL provides three set-manipulation constructs. SQL supports these operations under the names
UNION, INTERSECT, and EXCEPT. Set operators are used to join the results of two (or more)
SELECT statements.
UNIT – II / 15
DBMS NOTES (R15) VTA – CSE
UNION is used to combine the results of two or more Select statements. However it will
eliminate duplicate rows from its result set. In case of union, number of columns and data type
must be same in both the tables.
Example of UNION
ID Name
1 abhi
2 adam
ID Name
2 adam
3 Chester
ID NAME
1 abhi
2 adam
3 Chester
Union All
This operation is similar to Union. But it also shows the duplicate rows.
UNIT – II / 16
DBMS NOTES (R15) VTA – CSE
ID NAME
1 abhi
2 adam
2 adam
3 Chester
Intersect
Intersect operation is used to combine two SELECT statements, but it only retuns the records
which are common from both SELECT statements. In case of Intersect the number of columns
and data type must be same. MySQL does not support INTERSECT operator.
ID NAME
2 adam
Minus
Minus operation combines result of two Select statements and return only those result which
belongs to first set of result. MySQL does not support INTERSECT operator. MINUS and
EXCEPT are exact synonyms.
UNIT – II / 17
DBMS NOTES (R15) VTA – CSE
ID NAME
1 abhi
NESTED QUERIES
A nested query is a query that has another query embedded within it; the embedded query
is called a sub query. i.e Subquery or Inner query or Nested query is a query in a query. A
subquery typically appears within the WHERE clause of a query. Subqueries can sometimes
appear in the FROM clause or the HAVING clause
The subquery can be nested inside a SELECT, INSERT, UPDATE, or DELETE statement or
inside another subquery.
A subquery is usually added within the WHERE Clause of another SQL SELECT statement.
You can use the comparison operators, such as >, <, or =. The comparison operator can also
be
a multiple-row operator, such as IN, ANY, or ALL.
A subquery is also called an inner query or inner select, while the statement containing a
subquery is also called an outer query or outer select.
The inner query executes first before its parent query so that the results of inner query can be
passed to the outer query.
Correlated Subquery
A query is called correlated subquery when both the inner query and the outer query are
interdependent. For every row processed by the inner query, the outer query is processed as well.
The inner query depends on the outer query before it can be processed.
UNIT – II / 18
DBMS NOTES (R15) VTA – CSE
Ex : Display total salary department wise where the dept wise total salary is above 5000.
SQL > select deptno,sum(sal) from emp group by deptno having sum(sal) >= 5000;
SQL > Select * from emp where sal = (select max(sal) from emp);
UNIT – II / 19
DBMS NOTES (R15) VTA – CSE
SQL > Select sal from (select sal from emp order sal desc) where rownum <= 5;
Ex : To find the employees whose salary is equal to the salary of at least one employee in
department of id 300?
Ex : To find the employees whose salary is greater than at least on employee in department of id
500?
Ex : Write a query to find the employees whose salary is less than the salary of all employees in
department of id 100?
UNIT – II / 20
DBMS NOTES (R15) VTA – CSE
Ex . Write a query to list the department names which have at least one employee?
Ex : Write a query to find the departments which do not have employees at all?
NULL VALUES
The SQL NULL is the term used to represent a missing value. A NULL value in a table is a
value in a field that appears to be blank.
A field with a NULL value is a field with no value. It is very important to understand that a
NULL value is different than a zero value or a field that contains spaces.
A field with a NULL value is one that has been left blank during record creation.
UNIT – II / 21
DBMS NOTES (R15) VTA – CSE
There are three Logical Operators namely, AND, OR, and NOT. These operators
compare two conditions at a time to determine whether a row can be selected for the output.
When retrieving data using a SELECT statement, you can use logical operators in the WHERE
clause, which allows you to combine more than one condition.
Logical
Description
Operators
For the row to be selected at least one of
OR
the conditions must be true.
For a row to be selected all the specified
AND
conditions must be true.
For a row to be selected the specified
NOT
condition must be false.
Trigger is like a ‘Daemon that monitors a data base, and is executed when the data base is
modified in a way that matches the event specification
A data base that has a set of associated triggers is called an active data base.
UNIT – II / 22
DBMS NOTES (R15) VTA – CSE
+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+
The following program creates a row level trigger for the customers table that would fire for
INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This
trigger will display the salary difference between the old values and new values:
UNIT – II / 23
DBMS NOTES (R15) VTA – CSE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/
When the above code is executed at SQL prompt, it produces the following result:
Trigger created.
Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT
statement, which will create a new record in the table:
Old salary:
New salary: 7500
Salary difference:
Because this is a new record so old salary is not available and above result is coming as null.
Now, let us perform one more DML operation on the CUSTOMERS table. Here is one UPDATE
statement, which will update an existing record in the table:
UPDATE customers
SET salary = salary + 500
WHERE id = 2;
UNIT – II / 24
DBMS NOTES (R15) VTA – CSE