DBMS Unit 2 Notes Full

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 40

UNIT-2

RELATIONAL ALGEBRA AND RELATIONAL CALCULUS

Q) What is the input to a relational query ? what is the result of evaluating a


query ?
Ans : The inputs and outputs of a query are relations. A query is
evaluated using instances of each input relation and it produces an
instance of the output relation.
Queries often involve the computation of intermediate results, which
are themselves relation instances; and if we use field names to refer to
fields, the definition of query language constructs must specify the
names of fields for all intermediate relation instances.

we present a number of sample queries using the following schema:

Sailors(sid: integer, sname: string, rating: integer, age: real)


Boats( bid: integer, bname: string, color: string)
Reserves (sid: integer, bid: integer, day: date)

The key fields are underlined, and the domain of each field is listed
after the field name. Thus, sid is the key for Sailors, bid is the key for
Boats, and all three fields together form the key for Reserves.
Q) Database systems use some variant of relational algebra to represent query
evaluation plans. Explain why algebra is suitable for this purpose.

Ans.) Queries in algebra are composed using a collection of operators.


A fundamental property is that every operator in the algebra accepts
(one or two) relation instances as arguments and returns a relation
instance as the result.
This property makes it easy to compose operators to form a complex
query .
A relational algebra expression is recursively defined to be a relation, a
unary algebra operator applied to a single expression, or a binary
algebra operator applied to two expressions. We describe the basic
operators of the algebra selection, projection, union, cross-product,
and difference
Q )Describe selection operator ?

Ans: ) Select Operation (σ)

Relational algebra includes operators to select rows from a relation (σ)


and to project columns (∏).
These operations allow us to manipulate data in a single relation.

Consider the instance of the Sailors relation shown in Figure.

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 − =, ≠, ≥, < , 
>,  ≤.

The expression
Q) Describe Projection operator ?

Ans :) Project Operation (∏)

The projection operator ∏ allows us to extract columns from a relation;

For example, we can find out all sailor names and ratings by using .
The expression
For example, we can compute the names and ratings of highly rated
sailors by combining two of the preceding queries.
Q) Describe the set operations of relational algebra?
Set Operations
The following standard operations on sets are also available in
relational algebra:
union (U),
intersection (n),
set-difference (-),
cross-product (x).
Union Operation (∪)
It performs binary union between two given relations and is
defined as

Notion − r U s

R U S returns relation instance containing all tuples that occur in either


relation instance R or S, or both.

R and S must be union compatible.

Schema of the result is defined to be that of R.


Intersection operation

: returns a relation instance


containing all tuples that occur in both R and S.
• Schema of the result is that of R.
Set Difference (−)
The result of set difference operation is tuples, which are present in
one relation but are not in the second relation.
Notation − r − s
R – S: returns a relation instance
containing all tuples that occur in R but not in S.

• Scheme of the result is the schema of R.


Cartesian Product (Χ)
Combines information of two different relations into one.
Notation − r Χ s
1 This operation allows us to combine information from several
relations.
Thus operation is denoted by X. thus operation is binary operation.
2 Suppose r1 & r2 are two relations, Cartesian product of these two
relation can be written as r1 X r2.
3 In other words Cartesian product of these two relation is the
concatenation of tuples belonging two relations.
4. if there is ‘m’ tuple in relation r1 and ‘n’ tuple in relation r2, then
there are ‘mn’ ways of choosing a pair of tuples.

Q) Explain how the rename operator is used.


Ans :) Rename Operation (ρ)

The results of relational algebra are also relations but without any
name. The rename operation allows us to rename the output relation.
'rename' operation is denoted with small Greek letterrho ρ.
Notation − ρ x (E)
Q) Define all the variants of the join operation?
Ans :

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.

• Can be defined as cross-product followed by selection and projection.


• We have several variants of join.

– Condition joins
– Equijoin
– Natural join

Condition joins

The most general version of the join operation accepts a join condition
c and a pair of relation instances as arguments and returns a relation
instance.

Thus is defined to be a cross-product followed by a selection.


Equijoin
A common special case of the join operation is when the join
condition consists solely of equalities of the form
R.name1 = s.name2, that is, equalities between two fields in Rand S.

Natural Join

A further special case of the join operation is an equijoin in


which equalities arc specified on all fields having the same name in
Rand S. In this case, we can simply omit the join condition; the default
is that the join condition is a collection of equalities on all common
fields.

Q) Define the division operator in term of the basic relational algebra


operations.

Ans : Division

We discuss division through an example. Consider two relation


instances A and B in which A has (exactly) two fields x and y and B has
just one field y, with the same domain as in A.
We define the division operation AlB as the set of all x values (in the
form of unary tuples) such that for every y value in (a tuple of) B, there
is a tuple (x,y) in A.
More Examples of Algebra Queries

(Q1) Find the names of sailors who have reserved boat 103

This query can be written as follows:


(Q7)

Q) RELATIONAL CALCULUS

Ans : Relational calculus is an alternative to relational algebra.


The algebra, which is procedural, the calculus is nonprocedural, or
declarative

Relational calculus are two variants :

1. tuple relational calculus (TRC). Variables in TRC take on tuples as


values.
2. domain relational calculus (DRC), the variables range over field
values.

Tuple Relational Calculus

A tuple variable is a variable that takes on tuples of a particular relation


schema as values.

A tuple relational calculus query has the form { T I p(T) }, where T is a


tuple variable and p(T) denotes a formula that describes T;
The result of this query is the set of all tuples t for which the formula
p(T) evaluates to true with T = t.

Syntax of TRC Queries

Examples :
Domain Relational Calculus

A domain variable is a variable that ranges over the values in the


domain of some attribute.

A DRC query has the form {(XI,X2, ... ,Xn ) I P((XI,X2, ... ,Xn ))}, where
each Xi is either a domain variable or a constant and p( (Xl, X2, ... ,xn ))
denotes a DRC formula
Example :
q) expalin expressive power of algebra and calculus ?

Ans )

This query is syntactically correct.

However, it asks for all tuples S such that S is not in Sailors.

The set of such S tuples is obviously infinite, in the context of infinite


domains such as the set of all integers. This simple example illustrates
an unsafe query

How calculus queries are restricted to be safe. Consider a set I of


relation instances, with one instance per relation that appears in the
query Q. Let Dom(Q, i) be the set of all constants that appear in these
relation
instances I or in the formulation of the query Q itself. Since we allow
only finite instances I, Dom(Q, i) is also finite.
SQL: QUERIES, CONSTRAINTS, TRIGGERS

SQL : Structured Query Language (SQL) is the most widely used


commercial relational database language. It was originally
developed at IBM in the SEQUEL XRM and System-R projects
(1974-1977).

Q) What are the parts of basic SQL query ? Are the input and
result tables of an SQL querry sets or multisets ?
How can obtain a set of tuples as the result of a query ?

Ans: THE FORM OF A BASIC SQL QUERY


The basic form of an SQL query is as follows:

SELECT [DISTINCT] select-list


FROM from-list
WHERE qualification

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
We now consider the syntax of a basic SQL query in more detail.

• 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 (expressions involving) column names of


tables named in the from-list. Column names can be prefixed by a
range variable.

• The qualification in the WHERE clause is a boolean combination (i.e.,


an expression using the logical connectives AND, OR, and NOT) of
conditions of the form expression op expression, where op is one of the
comparison operators {<, <=, =, <>, >=, >}.2 An expression is a column
name, a constant, or an (arithmetic or string) expression.

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

Let us consider a simple example

(Q1) Find the names and ages of all sailors.

SELECT DISTINCT S.sname, S.age


FROM Sailors S

(Q2) Find all sailors with a rating above 7.

SELECT S.sid, S.sname, S.rating, S.age


FROM Sailors AS S
WHERE S.rating > 7

(Q3) Find the names of sailors Who have reserved boat number 103.

SELECT S.sname
FROM Sailors S, Reserves R
WHERE S.sid = R.sid AND R.bid=103

(Q4) Find the sids of sailors who have reserved a Red boat.

SELECT R.sid
FROM Boats B ,Reserves R
WHERE B.bid = R.bid AND B.color = ‘red’
(Q5) Find the colors of boats reserved by Lubber.

SELECT B.color
FROM Sailors S, Reserves R, Boats B
WHERE S.sid = R.sid AND R.bid = B.bid AND S.sname = 'Lubber'

(Q6) Find the names of sailors who have Reserved at least one boat.

SELECT S.sname
FROM Sailors S, Reserves R
WHERE S.sid = R.sid
Q) What operation does provide over (multi)set of tuples , and how
would you use these in writing queries ?
Ans :

UNION, INTERSECT, AND EXCEPT

SQL provides three set-manipulation constructs it is natural to consider


the use of operations such as union, intersection, and difference.

SQL supports these operations under the names UNION, INTERSECT,


and EXCEPT.

SQL also provides other set operations:

1. IN (to check if an element is in a given set),


2. op ANY, op ALL (to compare a value with the elements in a given
set, using comparison operator op),
3. EXISTS (to check if a set is empty).
4. IN and EXISTS can be prefixed by NOT

(Q1) Find the names of sailors who have reserved a red a green boat.

SELECT S.sname
FROM Sailors S, Reserves R, Boats B
WHERE S.sid = R.sid AND R.bid = B.bid AND (B.color = 'red' OR
B.color = 'green')
(Q2) Find the names of sailors who have reserved a red a green boat.

SELECT S.sname
FROM Sailors S, Reserves R, Boats B
WHERE S.sid = R.sid AND R.bid = B.bid AND (B.color = 'red' AND
B.color = 'green')

(Q3) Find the names of sailors who have reserved a red 01' a green
boat.

SELECT S.sname
FROM Sailors S, Reserves R, Boats B
WHERE S.sid = R.sid AND R.bid = B.bid AND B.color = 'red'
EXCEPT
SELECT S.sname
FROM Sailors S, Reserves R, Boats B
WHERE S.sid = R.sid AND R.bid = B.bid AND B.color = 'green'

(Q4) Find all sids of sailors who have a rating of 10 or reserved boat
104.

SELECT S.sid
FROM Sailors S
WHERE S.rating = 10
UNION
SELECT R.sid
FROM Reserves R
WHERE R.bid = 104
Q) What are Nested Queries ? What is correlation in Nested Queries ?
How would you use the operator IN,EXISTS,UNIQUE,ANY,AND ALL in
writing nested queries ? why are they useful ? Illustrate your answer
by showing how to write the division operator in SQL?

Ans :

NESTED QUERIES

A nested query is a query that has another query embedded within it;
the embedded query is called a subquery.

A subquery typically appears within the WHERE clause of a query.


Subqueries can sometimes appear in the FROM clause or the HAVING
clause.

IN (to check if an element is in a given set)

(Ql) Find the names of sailors who have reserved boat 103.

SELECT S.sname
FROM Sailors S
WHERE S.sid IN ( SELECT R.sid
FROM Reserves R
WHERE R.bid = 103 )
(Q2) Find the names of sailors 'who have reserved a red boat.

SELECT S.sname
FROM Sailors S
WHERE S.sid IN ( SELECT R.sid
FROM Reserves R
WHERE R.bid IN (IN (SELECT B.bid
FROM Boats B
WHERE B.color = 'red' )

(Q3) Find the names of sailors who have not reserved a red boat.

SELECT S.sname
FROM Sailors S
WHERE S.sid NOT IN ( SELECT R.sid
FROM Reserves R
WHERE R.bid IN (SELECT B.bid
FROM Boats B
WHERE B.color = 'red' )
Correlated Nested Queries

EXISTS (to check if a set is empty).

(Q1) Find the names of sailors who have reserved boat number 103.

SELECT S.sname
FROM Sailors S
WHERE EXISTS ( SELECT *
FROM Reserves R
WHERE R.bid = 103 AND R.sid = S.sid )

Set-Comparison Operators

op ANY, op ALL (to compare a value with the elements in a given set,
using comparison operator op),

SQL also supports op ANY and op ALL, where op is one of the arithmetic
comparison operators {<, <=, =, <>, >=, >}.

(Q1) Find sailors whose rating is better than some sailor called Horatio.

SELECT S.sid
FROM Sailors S
WHERE S.rating > ANY ( SELECT S2.rating
FROM Sailors S2
WHERE S2.sname = 'Horatio' )

If there are several sailors called Horatio, this query finds all sailors
whose rating is better than that of some sailor called Horatio.
(Q24J Find the sailor's with the highest rating.

SELECT S.sid
FROM Sailors S
WHERE S.rating >= ALL ( SELECT S2.rating FROM Sailors S2 )

Q) What aggregate operator does SQL support ?

AGGREGATE OPERATORS

1. COUNT ([DISTINCT] A): The number of (unique) values in the A column.


2. SUM ([DISTINCT] A): The sum of all (unique) values in the A column.
3. AVG ([DISTINCT] A): The average of all (unique) values in the A column.
4. MAX (A): The maximum value in the A column.
5. MIN (A): The minimum value in the A column.

(Q1) Find the average age of all sailors.

SELECT AVG (S.age)


FROM Sailors S

(Q2) Find the average age of sailors with a rating of 10.

SELECT AVG (S.age)


FROM Sailors S
WHERE S.rating = 10

(Q3) Find the name and age of the oldest sailor.

SELECT S.sname, MAX (S.age)


FROM Sailors S
(Q4) Count the nmnber of different sailor names.

SELECT COUNT ( DISTINCT S.sname )


FROM Sailors S

(Q5) Find the names of sailors who are older than the oldest sailor with
a rating of 10.

SELECT S.sname
FROM Sailors S
WHERE S.age > ( SELECT MAX ( S2.age )
FROM Sailors S2
WHERE S2.rating = 10 )

Q ) what are null values ? are they supported in relational model.


Ans :

SQL provides a special column value called null , We use null when the
column value is either Unknown or inapplicable.

Comparisons Using Null Values

SQL also provides a special comparison operator IS NULL to test


whether a column value is null;
for example, we can say rating IS NULL, which would evaluate to true
on the row representing Dan. We can also say rating IS NOT NULL,
which would evaluate to false on the row for Dan.
Logical Connectives AND, OR, and NOT

We must define the logical operators AND, OR, and NOT using in logic
in which expressions evaluate to true, false, or unknown.

Outer Joins

Some interesting variants of the join operation that rely on null values,
called outer joins, are supported in SQL.
Consider the join of two tables, say Sailors Reserves.
Tuples of Sailors that do not match some row in Reserves according to
the join condition c do not appear in the result.
In an outer join, on the other hanel, Sailor rows without a matching
Reserves row appear exactly once in the result, with the result columns
inherited from Reserves assigned null values.

In a left outer join, Sailor rows without a matching Reserves row


appear in the result, but not vice versa.
In a right outer join, Reserves rows without a matching Sailors row
appear in the result, but not vice versa.
In a full outer join, both Sailors and Reserves rows without a match
appear in the result.

Disallowing Null Values

We can disallow null values by specifying NOT NULL as part of the field
definition;
for example, sname CHAR(20) NOT NULL. In addition, the fields in a
primary key are not allowed to take on null values. Thus, there is an
implicit NOT NULL constraint for every field listed in a PRIMARY KEY
constraint.
Q) What type of SQL constraints can be specified using the query
language?
Ans :

Constraints over a Single Table


We can specify complex constraints over a single table using table
constraints, which have the form CHECK conditional-expression.

For example, to ensure that rating must be an integer in the range 1 to


10, we could use:

CREATE TABLE Sailors ( sid INTEGER,


sname CHAR(10),
rating INTEGER,
age REAL,
PRIMARY KEY (sid),
CHECK (rating >= 1 AND rating <= 10 ))

To enforce the constraint that Interlake boats cannot be reserved,


we could use:

CREATE TABLE Reserves (sid INTEGER,


bid INTEGER,
day DATE,
FOREIGN KEY (sid) REFERENCES Sailors
FOREIGN KEY (bid) REFERENCES Boats
CONSTRAINT noInterlakeRes
CHECK ( 'Interlake' <>
( SELECT B.bname
FROM Boats B
WHERE B.bid = Reserves.bid )))
Domain Constraints and Distinct Types

A user can define a new domain using the CREATE DOMAIN statement,
which uses CHECK constraints.

CREATE DOMAIN ratingval INTEGER DEFAULT 1


CHECK ( VALUE >= 1 AND VALUE <= 10 )

INTEGER is the underlying, or source, type for the domain ratingval, and
every ratingval value must be of this type.
Values in ratingval are further restricted by using a CHECK constraint; in
defining this constraint, we use the keyword VALUE to refer to a value
in the domain. By using this facility, we can constrain the values that
belong to a domain using the full power of SQL queries. Once a domain
is defined, the name of the domain can be used to restrict column
values in a table; we can use the following line in a schema declaration,
for example:

Rating ratingval

Or

CREATE TYPE ratingtype AS INTEGER

This statement defines a new distinct type called ratingtype, with


INTEGER as its source type.
Assertions

Table constraints are associated with a single table, although the


conditional expression in the CHECK clause can refer to other tables.
Thus, when a constraint involves two or more tables, the table
constraint mechanism is sometimes cumbersome and not quite what is
desired.
To cover such situations, SqL supports the creation of assertions, which
are constraints not associated with anyone table.

As an example, suppose that we wish to enforce the constraint that the


number of boats plus the number of sailors should be less than 100.

CREATE TABLE Sailors ( sid INTEGER,


sname CHAR ( 10) ,
rating INTEGER,
age REAL,
PRIMARY KEY (sid),
CHECK ( rating >= 1 AND rating <= 10)
CHECK ( ( SELECT COUNT (S.sid) FROM Sailors S )
+ ( SELECT COUNT (B. bid) FROM Boats B )< 100
))

This solution suffers from two drawbacks. It is associated with Sailors,


although it involves Boats in a completely symmetric way.
More important, if the Sailors table is empty, this constraint is defined
(as per the semantics of table constraints) to always hold, even if we
have more than 100 rows in Boats. we could extend this constraint
specification to check that Sailors is nonempty, but this approach
becomes cumbersome. The best solution is to create an assertion, as
follows:

CREATE ASSERTION smallClub

CHECK (( SELECT COUNT (S.sid) FROM Sailors S )


+ ( SELECT COUNT (B. bid) FROM Boats B) < 100 )

Q) What are the trigger .What are its three parts ? What are the
differences between row-level and statement –level trigger ?
Ans :
A trigger is a procedure that is automatically invoked by the DBMS in
response to specified changes to the database, and is typically specified
by the DBA.
A database that has a set of associated triggers is called an active
database.
A trigger description contains three parts:

- Event : A change to the database that activates the trigger.


- Condition : A query or test that is run when the trigger is activated.
- Action : A procedure that is executed when the trigger is
activated and its condition is true.

A trigger can be thought of as a 'daemon' that monitors a databa.se,


and is executed when the database is modified in a way that matches
the event specification.

An insert, delete, or update statement could activate a trigger,

A condition in a trigger can be a true/false statement (e.g., all employee


salaries are less than $100,000) or a query. A query is interpreted as
true if the answer set is nonempty and false if the query has no
answers. If the condition part evaluates to true, the action associated
with the trigger is executed.

A trigger action can examine the answers to the query in the condition
part of the trigger, refer to old and new values of tuples modified by
the statement activating the trigger, execute Hew queries, and make
changes to the database.

In fact, an action can even execute a series of data-definition


commands (e.g., create new tables, change authorizations) and
transaction-oriented commands (e.g., commit) or call host-language
procedures.

Example :
If the action depends on individual changed records, for example, we
have to examine the age field of the inserted Students record to decide
whether to increment the count, the triggering event should be defined
to occur for each modified record; the FOR EACH ROW clause is used to
do this. Such a trigger is called a row-level trigger.

the iniLcount trigger is executed just once per INSERT statement,


regardless of the number of records inserted, because we have omitted
the FOR EACH ROW phrase. Such a trigger is called a statement-level
trigger.

Q) Explain DESIGNING ACTIVE DATABASES ?

Why Triggers Can Be Hard to Understand

In an active database system, when the DBMS is about to execute a


statement that modifies the databa.se, it checks whether some trigger
is activated by the statement. If so, the DBMS processes the trigger by
evaluating its condition part, and then (if the condition evaluates to
true) executing its action part.

An important point is that the execution of the action part of a trigger


could in turn activate another trigger. In particular, the execution of the
action part of a trigger could a,gain activate the sarne trigger; such
triggers are called recursive triggers.
Constraints versus Triggers

A constraint also prevents the data from being made inconsistent by


any kind of statement, whereas a trigger is activated by a specific kind
of statement (INSERT, DELETE, or UPDATE). Again, this restriction
makes
a constraint easier to understand.

On the other hand, triggers allow us to maintain database integrity in


more flexible ways

Suppose that we have a table called Orders with fields itemid, quantity,
customerid, and unitprice.
When a customer places an order, the first three field values are filled
in by the user (in this example, a sales clerk).
The fourth field's value can be obtained from a table called Items, but it
is important to include it in the Orders table to have a complete record
of the order, in case the price of the item is subsequently changed.
We can define a trigger to look up this value and include it in the fourth
field of a newly inserted record. In addition to reducing the number of
fields that the clerk has to type in, this trigger eliminates the possibility
of an entry error leading to an inconsistent price in the Orders table

Uses Of Triggers

Triggers can alert users to unusual events (& reflected in updates to the
database).
For example, we may want to check whether a customer placing an
order has made enough purchases in the past month to qualify for an
additional discount; if so, the sales clerk must be informed so that he
(or she) can tell the customer
Triggers can generate a log of events to support auditing and security
checks.
For example, each time a customer places an order, we can create a
record with the customer's ID and current credit limit and insert this
record in a customer history table. Subsequent analysis of this table
might suggest candidates for an increased credit limit (e.g., customers
who have never failed to pay a bill on time and who have come within
10% of their credit limit at least three times in the last month)..

You might also like