Module 2
Module 2
LECTURE-19
Relational Algebra:
Basic operations:
1. Selection (σ) Selects a subset of rows from relation.
2. Projection (π) Selects a subset of columns from relation.
3. Cross-product (×) Allows us to combine two relations.
4. Set-difference ( ) Tuples in relation. 1, but not in relationn. 2.
5. Union (U) Tuples in reln. 1 and in reln. 2.
6. Rename( ρ) Use new name for the Tables or fields.
Additional operations:
7. Intersection (∩), Join( ), Division(÷): Not essential, but (very!) useful.
Since each operation returns a relation, operations can be composed! (Algebra is
“closed”.)
Projection
Deletes attributes that are not in projection list.
Schema of result contains exactly the fields in the projection list, with the same names that
they had in the (only) input relation. ( Unary Operation)
Projection operator has to eliminate duplicates! (as it returns a relation which is a set)
o Note: real systems typically don’t do duplicate elimination unless the user explicitly
asks for it. (Duplicate values may be representing different real world entity or
relationship).
Example: Consider the BOOK table:
Acc-No Title Author
100 “DBMS” “Silbershatz”
200 “DBMS” “Ramanuj”
300 “COMPILER” “Silbershatz”
400 “COMPILER” “Ullman”
500 “OS” “Sudarshan”
600 “DBMS” “Silbershatz”
Title
πTitle(BOOK) = “DBMS”
“COMPILER”
“OS”
Selection
Selects rows that satisfy selection condition.
No duplicates in result
Schema of result identical to schema of (only) input relation.
Result relation can be the input for another relational algebra operation! (Operator
composition.)
Example: For the example given above:
σAcc-no>300(BOOK) =
Acc- Title Author
No
400 “COMPILER “Ullman”
”
500 “OS” “Sudarshan”
600 “DBMS” “Silbershatz”
σTitle=”DBMS”(BOOK)=
All of these operations take two input relations, which must be union-compatible:
o Same number of fields.
o Corresponding’ fields have the same type.
What is the schema of result?
Consider:
Borrower Depositor
Cust- Loan-no Cust-name Acc-no
name Suleman A-100
Ram L-13 Radheshyam A-300
Shyam L-30 Ram A-401
Suleman L-42
List of customers who are either borrower or depositor at bank= πCust-name (Borrower) U
πCust-name (Depositor)=
Cust-name
Ram
Shyam Customers who are both borrowers and depositors = πCust-name
Suleman (Borrower) ∩ πCust-name (Depositor)=
Radeshyam
Cust-
name
Ram
Suleman
Customers who are borrowers but not depositors = πCust-name (Borrower) πCust-name
(Depositor)=
Cust-name
Shyam
Cartesian-Product or Cross-Product (S1 × R1)
Each row of S1 is paired with each row of R1.
Result schema has one field per field of S1 and R1, with field names `inherited’ if possible.
Consider the borrower and loan tables as follows:
Borrower: Loan:
Cust-name Loan-no Loan-no Amount
Ram L-13 L-13 1000
Shyam L-30 L-30 20000
Suleman L-42 L-42 40000
The rename operation can be used to rename the fields to avoid confusion when two field names are
same in two participating tables:
Loan-borrower:
Cust- Loan-No-1 Loan- Amount
name No-2
Ram L-13 L-13 1000
Ram L-13 L-30 20000
Ram L-13 L-42 40000
Shyam L-30 L-13 1000
Shyam L-30 L-30 20000
Shyam L-30 L-42 40000
Suleman L-42 L-13 1000
Suleman L-42 L-30 20000
Suleman L-42 L-42 40000
Rename Operation:
It can be used in two ways :
return the result of expression E in the table named x.
return the result of expression E in the table named x with the attributes
renamed to A1, A2,…, An.
It’s benefit can be understood by the solution of the query “ Find the largest account balance
in the bank”
It can be solved by following steps:
Find out the relation of those balances which are not largest.
Consider Cartesion product of Account with itself i.e. Account × Account
Compare the balances of first Account table with balances of second Account table in the
product.
For that we should rename one of the account table by some other name to avoid the
confusion
It can be done by following operation
ΠAccount.balance (σAccount.balance < d.balance(Account× ρd(Account))
So the above relation contains the balances which are not largest.
Subtract this relation from the relation containing all the balances i.e . Πbalance (Account).
So the final statement for solving above query is
Πbalance (Account)- ΠAccount.balance (σAccount.balance < d.balance(Account× ρd(Account))
LECTURE-20
Additional Operations
Natural Join ( )
Forms Cartesian product of its two arguments, performs selection forcing equality on
those attributes that appear in both relations
For example consider Borrower and Loan relations, the natural join between them
will automatically perform the selection on the table returned by
Borrower × Loan which force equality on the attribute that appear in both Borrower
and Loan i.e. Loan-no and also will have only one of the column named Loan-No.
That means = σBorrower.Loan-no = Loan.Loan-no (Borrower × Loan).
The table returned from this will be as follows:
Eliminate rows that does not satisfy the selection criteria “σBorrower.Loan-no = Loan.Loan-no” from Borrower
× Loan =
Borrower.Cust- Borrower.Loan- Loan.Loan- Loan.Amount
name no no
Ram L-13 L-13 1000
Ram L-13 L-30 20000
Ram L-13 L-42 40000
Shyam L-30 L-13 1000
Shyam L-30 L-30 20000
Shyam L-30 L-42 40000
Suleman L-42 L-13 1000
Suleman L-42 L-30 20000
Suleman L-42 L-42 40000
i.e. =
Cust-name Loan-no Amount
Ram L-13 1000
Shyam L-30 20000
Suleman L-42 40000
Division Operation:
denoted by ÷ is used for queries that include the phrase “for all”.
For example “Find customers who has an account in all branches in branch city
Agra”. This query can be solved by following statement.
ΠCustomer-name. branch-name ( ) ÷ Πbranch-name (σBranch-city=”Agra”(Branch)
The division operations can be specified by using only basic operations as follows:
Let r(R) and s(S) be given relations for schema R and S with
r ÷ s = ΠR-S(r) - ΠR-S ((ΠR-S (r) × s) - ΠR-S,S (r))
LECTURE-21
The formula P(t) is formed using atoms which uses the relations, tuples of relations and fields of
tuples and following symbols
These atoms can then be used to form formulas with following symbols
For example : here are some queries and a way to express them using tuple calculus:
o Find the branch-name, loan-number and amount for loans over Rs 1200.
.
o Find the loan number for each loan of an amount greater that Rs1200.
o Find the names of all the customers who have a loan from the Sadar branch.
o Find all customers who have a loan , an account, or both at the bank
o Find only those customers who have both an account and a loan.
o Find all customers who have an account but do not have loan.
o Find all customers who have an account at all branches located in Agra
Domain Relational Calculus
1. Domain relational calculus is another non procedural language for expressing database
queries.
2. A query is specified as:
{<x1,x2,…,xn> | P(x1,x2,…,xn)} where x1,x2,…,xn represents domain variables. P represent a
predicate formula as in tuple calculus
Since the domain variables are referred in place of tuples the formula doesn’t refer the fields
of tuples rather they refer the domain variables.
For example the queries in domain calculus are mentioned as follows:
o Find the branch-name, loan-number and amount for loans over Rs 1200.
.
o Find the loan number for each loan of an amount greater that Rs1200.
o Find the names of all the customers who have a loan from the Sadar branch and find
the loan amount
o Find names of all customers who have a loan , an account, or both at the Sadar
Branch
o Find only those customers who have both an account and a loan.
o Find all customers who have an account but do not have loan.
o Find all customers who have an account at all branches located in Agra
Outer Join.
Outer join operation is an extension of join operation to deal with missing information
Suppose that we have following relational schemas:
Employee( employee-name, street, city)
Fulltime-works(employee-name, branch-name, salary)
A snapshot of these relations is as follows:
Employee: employee- street city
name
Ram M G Road Agra
Shyam New Mandi Mathura
Road
Suleman Bhagat Singh Aligarh
Road
Fulltime-works
Right join: =
Full join: =
Views
In SQL create view command is used to define a view as follows:
create view v as <query expression>
where <query expression> is any legal query expression and v is the view name.
The view consisting of branch names and the names of customers who have either an
account or a loan at the branch. This can be defined as follows:
The attributes names may be specified explicitly within a set of round bracket after the name
of view.
The view names may be used as relations in subsequent queries. Using the view
Allcustomer
Find all customers of Sadar branch
select customer-name
from All-customer
where branch-name= “Sadar”
A create-view clause creates a view definition in the database which stays until a command
- drop view view-name - is executed.
Modification of Database
Deletion
In SQL we can delete only whole tuple and not the values on any particular
attributes. The command is as follows:
Insertion
In SQL we either specify a tuple to be inserted or write a query whose result is a
set of tuples to be inserted. Examples are as follows:
Insert an account of account number A-9732 at the Sadar branch having balance
of Rs 1200
insert into Account
values(“Sadar”, “A-9732”, 1200)
the values are specified in the order in which the corresponding attributes are
listed in the relation schema.
SQL allows the attributes to be specified as part of the insert statement
insert into Account(account-number, branch-name, balance)
values(“A-9732”, “Sadar”, 1200)
insert into Account(branch-name, account-number, balance)
values(“Sadar”, “A-9732”, 1200)
Provide for all loan customers of the Sadar branch a new Rs 200 saving account
for each loan account they have. Where loan-number serve as the account number
for these accounts.
insert into Account
select branch-name, loan-number, 200
from Loan
where branch-name = “Sadar”
Updates
Used to change a value in a tuple without changing all values in the tuple.
Suppose that annual interest payments are being made, and all balances are to be
increased by 5 percent.
update Account
set balance = balance * 1.05
Suppose that accounts with balances over Rs10000 receive 6 percent interest,
whereas all others receive 5 percent.
update Account
set balance = balance * 1.06
where balance > 10000
update Account
set balance = balance * 1.05
where balance <= 10000
Data Definition Language
Data Types in SQL
char(n): fixed length character string, length n.
varchar(n): variable length character string, maximum length n.
int: an integer.
smallint: a small integer.
numeric(p,d): fixed point number, p digits( plus a sign), and d of the p digits are
to right of the decimal point.
real, double precision: floating point and double precision numbers.
float(n): a floating point number, precision at least n digits.
date: calendar date; four digits for year, two for month and two for day of month.
time: time of day n hours minutes and seconds.
Domains can be defined as
create domain person-name char(20).
the domain name person-name can be used to define the type of an attribute just like
built-in domain.
Schema Definition in SQL
create table command is used to define relations.
create table r (A1D1, A2D2,… , AnDn,
<integrity constraint1>,
…,
<integrity constraintk>)
where r is relation name, each Ai is the name of attribute, Di is the domain type of
values of Ai. Several types of integrity constraints are available to define in SQL.
Integrity Constraints
Integrity Constraints guard against accidental damage to the database.
Integrity constraints are predicates pertaining to the database.
Domain Constraints:
Predicates defined on the domains are Domain constraints.
Simplest Domain constraints are defined by defining standard data types of the attributes
like Integer, Double, Float, etc.
We can define domains by create domain clause also we can define the constraints on such
domains as follows:
create domain hourly-wage numeric(5,2)
constraint wage-value-test check(value >= 4.00)
So we can use hourly-wage as data type for any attribute where DBMS will automatically
allow only values greater than or equal to 4.00.
Other examples for defining Domain constraints are as follows:
create domain account-number char(10)
constraint account-number-null-test check(value not null)
create domain account-type char(10)
constraint account-type-test
check (value in ( “Checking”, “Saving”))
By using the later domain of two above the DBMS will allow only values for any attribute having
type as account-type i.e. Checking and Saving.
Referential Integrity:
Foreign Key: If two table R and S are related to each other, K1 and K2 are primary keys of
the two relations also K1 is one of the attribute in S. Suppose we want that every row in S
must have a corresponding row in R, then we define the K1 in S as foreign key. Example in
our original database of library we had a table for relation BORROWEDBY, containing two
fields Card No. and Acc. No. . Every row of BORROWEDBY relation must have
corresponding row in USER Table having same Card No. and a row in BOOK table having
same Acc. No.. Then we will define the Card No. and Acc. No. in BORROWEDBY relation
as foreign keys.
In other way we can say that every row of BORROWEDBY relation must refer to some row
in BOOK and also in USER tables.
Such referential requirement in one table to another table is called Referential Integrity.
LECTURE-25
Selections in QBE
QBE uses skeleton tables to represent table name and fieldnames like:
Table name Field1 Field2 …..
For selection, P operator along with variable name/constant name is used to display one or more
fields.
Example 1:
Consider the relation: student (name, roll, marks)
The following query can be represented as:
SQL: select name from student where marks>50;
student name roll marks
P.X >50
Here X is a constant; alternatively we can use _X as a variable.
Example 2:
For the relation given above
The following query can be represented as:
SQL: select * from student where marks>50 and marks <80;
student name roll marks
P. _X
CONDITION
_X>50 _X<80
Insertions in QBE:
Uses operator I. on the table.
Example: Consider the following query on Student table
SQL: insert into student values (‘abc’,10,60);
Deletions in QBE:
Uses operator D. on the table.
Example: Consider the following query on Student table
SQL: delete from student where marks=0;
Updation in QBE:
Uses operator U. on the table.
Example: Consider the following query on Student table
SQL: update student set mark=50 where roll=40;