You are on page 1of 41

Relation : The main construct for representing data in relational model is a relation(table).

A relation is a set of records in the form of two dimensional table containing rows and
columns.

Relational model: The relational model represents the database as a collection of relations
i.e data is stored in the form of tables. A table has two properties - rows and columns.
Rows represent records and columns represent attributes.

Relation Schema : Relation schema defines the design and structure of the relation. It
consists of the relation name, set of attributes/field names/column names. Every attribute
would have an associated domain.
For example : Student is a schema :

Relation instance – An instance of a relation is a set of tuples, also called records, in


Student { name : String,
which each tuple has the same number of fields as the relation schema.
rollnumber : Integer,
Degree/arity: The total number of attributes in the relation is called the degree of the relation.
contactnumber : Integer,
Cardinality: Total
yearofadmission : number of rows present in the Table.

Integer,
Domain:course : String}
Every attribute has some pre-defined value and scope which is known as attribute
domain.

More formally, let R(fI:Dl, ... , fn:Dn) be a relation schema, and for each fi,1<= i <= n, let
Domi
be the set of values associated with the domain named Di.

{ (fI : d1 , ,fn: dn) / d1 E Dom1' ... ,dn E Domn}

HADIFA
ASST. PROFESSOR Page 1
The above instance contains six tuples and has five fields.

Note that no two rows are identical. This is a requirement of the relational model -each
relation is defined to be a set of unique tuples or rows.

Creating and Modifying Relations Using SQL

The CREATE TABLE statement is used to define a new table. To create the Students
relation, we can use the following statement:

1. CREATE TABLE Students ( sid INT,

NameVARCHAR(20),

Login VARCHAR(20),

Age INTEGER,

Gpa REAL);

2. INSERT: Tuples are inserted , using the INSERT command. We can insert a
single tuple into the Students table as follows:

INSERT INTO Students (sid, name, login, age, gpa) VALUES (53688,
'Smith', 'smith@ee', 18, 3.2);

We can optionally omit the list of column names in the INTO clause and list the
values in the appropriate order. Like

INSERT INTO Students VALUES (53688, 'Smith', 'smith@ee', 18, 3.2);

HADIFA
ASST. PROFESSOR Page 2
3. DELETE: We can delete tuples using the DELETE command. We can delete
all Students tuples with name equal to Smith using the command:

DELETE FROM Students S WHERE S.name = 'Smith'

4. UPDATE: We can modify the column values in an existing row using


the UPDATE command.
For example, we can increment the age of the student with sid 53688:

UPDATE Students S SET S.age = S.age + 1, WHERE S.sid = 53688

INTEGRITY CONSTRAINTS OVER RELATIONS

o Integrity constraints are a set of rules that are used to maintain the quality of information.

o Integrity constraints ensure that changes (update deletion, insertion) made to the database
by authorized users do not result in a loss of data consistency.

There are many types of integrity constraints.

1. Entity Integrity Constraint/Key constraints


2. Referential Integrity constraints/ Foreign key
3. Domain constraints
4. General constraints

1. Entity Integrity Constraint/ Key constraints

The entity integrity constraint states that primary key value can't be null.
 This is because the primary key value is used to identify individual rows in relation
and if the primary key has a null value, then we can't identify those rows.
 A table can contain a null value other than the primary key field.

HADIFA
ASST. PROFESSOR Page 3
 PRIMARY KEY:

Primary key uniquely identifies each record in a table. It must have unique values and
cannot contain nulls. In the below example the ROLL_NO field is marked as primary key,
that means the ROLL_NO field cannot have duplicate and null values.

CREATE TABLE STUDENT(


ROLL_NO INT NOT NULL,
STU_NAME VARCHAR (35) NOT NULL UNIQUE,
STU_AGE INT NOT NULL,
STU_ADDRESS VARCHAR (35) UNIQUE,
PRIMARY KEY (ROLL_NO)
);

The UNIQUE keyword ensures that all values in a column are different.

Specifying Primary Key Constraints in SQL

CREATE TABLE Students ( sid INT, name


VARCHAR (30) ,Login VARCHAR(20) ,
Age INT, gpa REAL,
UNIQUE (name, age),
CONSTRAINT StudentsKey PRIMARY KEY (sid) );

This definition says that sid is the primary key and the combination of name and age is
also a key. The definition of the primary key also illustrates that a constraint should
precede with CONSTRAINT constraint-name

HADIFA
ASST. PROFESSOR Page 4
 CANDIDATE KEY
o The minimal set of attribute which can uniquely identify a tuple is known
as candidate key.
o They can contain null values. These are the subset of super key.
o The remaining attributes except for primary key are considered as a candidate key.
o For example: In the EMPLOYEE table, id is best suited for the primary key. Rest
of the attributes like SSN, Passport_Number, and License_Number, etc. are
considered as a candidate key.

 SUPER KEY

Super key is a (maximum) set of an attribute which can uniquely identify a tuple. Super
key is a superset of a candidate key.

E.g: Let R be a relation with columns(A,B,C,D,E,F) such that by making AB as key we are
able to identify all other columns i.e CDEF

Keys Is super key or

not AB---- CDEF yes

CD----ABEF yes

CB----DF no

ABD---CEF yes

HADIFA
ASST. PROFESSOR Page 5
DF---ABCE yes

D---BC no

DEF---ABC yes

By making AB as key we are able to identify all other columns i.e CDEF. Similarly using
CD,ABD,DF and DEF we are able to identify all. So all these are super key.

But by using CB we can only identify D and F. Hence CB is not a super key.

AB is a proper subset of super key ABD, when AB alone is able to identify all attributes,
then we need not need ABD. Hence ABD is only super key and AB is candidate key.

NOTE: Each candidate key is super key but not vice versa.

2. Referential Integrity Constraint-

Foreign keys are the columns of a table that points to the primary key of another table. They
act as a cross-reference between tables.

It states that if a foreign key exists in a relation then either the foreign key value must match a
primary key value of some tuple in its home relation or the foreign key value must be null.
The rules are:

1. You can't delete a record from a primary table if matching records exist in a related table.
2. You can't change a primary key value in the primary table if that record has related
records in foreign table.
3. You can't enter a value in the foreign key field of the related table that doesn't exist in the
primary key of the primary table.
4. However, you can enter a Null value in the foreign key, specifying that the records are
unrelated.

HADIFA
ASST. PROFESSOR Page 6
o E.g: In a company, every employee works in a specific department, and employee
and department are two different entities. So we can't store the information of the
department in the employee table. That's why we link these two tables through the
primary key of one table.
o We add the primary key of the DEPARTMENT table, Department_Id as a new
attribute in the EMPLOYEE table.
o Now in the EMPLOYEE table, Department_Id is the foreign key, and both the
tables are related.

Example :2

If we try to insert the tuple (55555, Artl04, A) into E1, the IC is violated because there is no
tuple in 51 with sid 55555; the database system should reject such an insertion. Similarly,
if we delete the tuple (53666, Jones, jones@cs,18, 3.4) from 51, it violate the foreign key
constraint because the tuple (53666, Historyl05, B) in El contains studid value 53666, the
sid of the deleted Students tuple. The DBMS should disallow the deletion or, perhaps, also
delete the Enrolled tuple that refers to the deleted Students tuple

HADIFA
ASST. PROFESSOR Page 7
Specifying Foreign Key Constraints in SQL

CREATE TABLE Enrolled ( studid INT ,


cid INT,
grade CHAR(10),
PRIMARY KEY (studid, cid),
FOREIGN KEY (studid) REFERENCES Students)

The foreign key constraint states that every studid value in Enrolled must also appear in
Students, that is, studid in Enrolled is a foreign key referencing Students. Specifically,
every studid value in Enrolled must appear as the value in the primary key field, sid, of
Students.

3. Domain constraint ( Refer 3rd unit for detailed description)

A domain is a unique set of values permitted for an attribute in a table. For example, a domain of
month-of-year can accept January….December as possible values, a domain of integers can
accept whole numbers that are negative, positive and zero.
The data type of domain includes string, character, integer, time, date, currency, etc. The value of
the attribute must be available in the corresponding domain.

HADIFA
ASST. PROFESSOR Page 8
4. General Constraints

Sometimes specifying general constraints (like age should be greater than 18,etc) are
necessary.

Current relational database systems support such general constraints in the form of table
constraints and assertions. Table constraints are associated with a single table and checked
whenever that table is modified. In contrast, assertions involve several tables and are
checked whenever any of these tables is modified.

ENFORCING INTEGRITY CONSTRAINTS

If an insert, delete, or update command causes a violation, it is rejected. Every potential IC


violation is generally checked at the end of each SQL statement execution, although it can
be deferred until the end of the transaction executing the statement

The following insertion violates the constraint that the primary key cannot contain null:
INSERT
INTO Students (sid, name,
login, age, gpa) VALUES (null,
'Mike', 'mike@ee', 17,3.4)

Of course, a similar problem arises whenever we try to insert a tuple with a value in a field
that is not in the domain associated with that field, that is, whenever we violate a domain
constraint. Deletion does not cause a violation of, primary key or unique constraints.
However, an update can cause violations, similar to an insertion.

In Foreign key case: The impact of foreign key constraints is more complex because SQL
sometimes tries to rectify a foreign key constraint violation instead of simply rejecting the
change.

In addition to the instance S1 of Students, consider the instance of Enrolled shown above.
Deletions of Enrolled tuples do not violate referential integrity, but insertions of Enrolled
tuples could. The following insertion is illegal because there is no Students tuple with sid
51111:

HADIFA
ASST. PROFESSOR Page 9
INSERT
INTO Enrolled (cid, grade, studid)
VALUES ('Hindi101', 'B', 51111);

On the other hand, insertions of Students tuples do not violate referential integrity, and
deletions of Students tuples could cause violations. Further, updates on either Enrolled or
Students that change the studid (respectively, sid) value could potentially violate referential
integrity.

SQL provides several alternative ways to handle foreign key violations. We must
consider three basic questions:

1. What should we do if an Enrolled row is inserted, with a studid column value that
does not appear in any row of the Students table?
In this case, the INSERT command is simply rejected.

2. What should we do if a Students row is deleted?


The options are:
• Delete all Enrolled rows that refer to the deleted Students row.
• Disallow the deletion of the Students row if an Enrolled row refers to it.
• Set the studid column to the sid of some (existing) 'default' student, for every
Enrolled row that refers to the deleted Students row.

3. What should we do if the primary key value of a Students row is updated?


The options here are similar to the previous case.

SQL allows us to choose any of the above options on DELETE and UPDATE. For
example, we can specify that when a Students row is deleted, all Enrolled rows that refer to
it are to be deleted as well, but that when the sid column of a Students row is modified, this
update is to be rejected if an Enrolled row refers to the modified Students row:

HADIFA
ASST. PROFESSOR Page 10
CREATE TABLE Enrolled ( studid
CHAR(20) , cid CHAR(20) ,
grade CHAR(10),
PRIMARY KEY (studid, dd),
FOREIGN KEY (studid) REFERENCES
Students ON DELETE
CASCADE ON UPDATE NO
ACTION)

The default option is NO ACTION, which means that the action (DELETE or UPDATE) is
to be rejected, The CASCADE keyword says that, if a Students row is deleted, all Enrolled
rows that refer to it are to be deleted as well. If the UPDATE clause specified CASCADE,
and the sid column of a Students row is updated, this update is also carried out in each
Enrolled row that refers to the updated Students row.

TRANSACTION AND CONSTRAINTS

A program that runs against a database is called a transaction, and it can contain several
statements (queries, inserts, updates, etc.) that access the database.

By default, a constraint is checked at the end of every SQL statement that could lead to a
violation, and if there is a violation, the statement is rejected. Sometimes this approach is
too inflexible. Consider the following variants of the Students and Courses relations; every
student is required to have an honors course, and every course is required to have a grader,
who is some student.

CREATE TABLE Students ( sid


INT , name CHAR(30),
login CHAR
(20) , age
INTEGER,
honorsCHAR(10) NOT NULL,
gpa REAL)
PRIMARY
KEY (sid),
FOREIGN KEY (honors) REFERENCES Courses (cid));

HADIFA
ASST. PROFESSOR Page 11
CREATE TABLE Courses
(cid INT, cname CHAR ( 10) ,
credits INTEGER,
grader CHAR(20) NOT NULL,
PRIMARY KEY (dd)
FOREIGN KEY (grader) REFERENCES Students (sid))

Whenever a Students tuple is inserted, a check is made to see if the "honors” course is in
the Courses relation, and whenever a Courses tuple is inserted, a check is made to see that
the grader is in the Students relation. One cannot be inserted without the other. The only
way to accomplish this insertion is to defer (delay) the constraint checking that would
normally be carried out at the end of an INSERT statement.

SQL allows a constraint to be in DEFERRED or IMMEDIATE mode.

Syntax: SET CONSTRAINT ConstraintFoo DEFERRED

QUERYING RELATIONAL DATA

We can retrieve rows corresponding to students who are younger than 18 with the
following SQL query:

SELECT *
FROM
Students S
WHERE
S.age < 18

The symbol ,*, means that we retain all fields of selected tuples in the result. Think of S as
a variable that takes on the value of each tuple in Students, one tuple after the other. The
condition S. age < 18 in the WHERE clause specifies that we want to select only tuples
in which the age field has a value less than 18. This query evaluates to the relation shown
below.

HADIFA
ASST. PROFESSOR Page 12
Students with age <18 on Student Instance

In addition to selecting a subset of tuples, a query can extract a subset of the fields of each
selected tuple we can compute the names and logins of students who are younger than 18
with the following query:

SELECT S.name,
S.login FROM
Students SWHERE
S.age < 18

We can also combine information in the Students and Enrolled relations. If we want to
obtain the names of all students who obtained an A and the id of the course in which they
got an A, we could write the following query:

SELECT S.name, E.cid


FROM Students S,
Enrolled E
WHERE S.sid = E.studid AND E.grade = 'A'

This query can be understood as follows: "If there is a Students tuple S and an Enrolled
tuple E such that S.sid = E.studid (so that S describes the student who is enrolled in E) and
E.grade = 'A', then print the student's name and the course id."

When evaluated on the instances of Students and Enrolled relation, this query returns a
single tuple, (Smith, Topology,112).

HADIFA
ASST. PROFESSOR Page 13
LOGICAL DATABASE DESIGN

 Entity Sets to Tables

An entity set is mapped to a relation in a straightforward way:

The following SQL statement captures the preceding information, including the domain
constraints and key information:

CREATE TABLE Employees


(ssn INT, name VARCHAR(30) ,
lot INT, PRIMARY KEY (ssn) );

HADIFA
ASST. PROFESSOR Page 14
 Relationship Sets (without Constraints) to Tables

To represent a relationship, we must be able to identify each participating entity and give
values to the descriptive attributes of the relationship.

1. Create a table for the relationship set.


2. Add all primary keys of the participating entity sets as fields of thetable.
3. Add a field for each attribute of the relationship.
4. Declare a primary key using all key fields from the entity sets.
5. Declare foreign key constraints for all these fields from the entity sets

 Translating Relationship Sets with Key Constraints

If a relationship set involves n entity sets and some of them are linked via arrows (i.e
constraint) in the ER diagram, then the key for anyone of these m entity sets constitutes a
key for the relation to which the relationship set is mapped.

HADIFA
ASST. PROFESSOR Page 15
The constraint here is that a department should have at most one manager but an employee
can work in any department. An employee with ssn (id) can work in different departments.
Therefore ssn can’t be used as primary key because it does not uniquely identifies a tuple.
Therefore only did is used as primary key. (The key of only department entity (i.e did ) is
constituting as a key for this relation.)

Second approach: Avoid creating a distinct table for the relationship set and add the
information about the relationship set in the table corresponding to the entity set with the
key, taking advantage of the key constraint.

Here we are simply adding ssn and since directly to department entity set because the
constraint is on it. (Department should have at most one manager)

Note: Since ssn is not a part of primary key it can contain null values.

HADIFA
ASST. PROFESSOR Page 16
 Translating Relationship Sets with Participation Constraints

The above figure captures the participation (total participation ) constraint that every
department must have a manager. Every department is required to have a manager, due to
the participation constraint, and at most one manager, due to the key constraint. So ssn
cannot be null here.

CREATE TABLE DepLMgr ( did INTEGER,


dname VARCHAR(20) ,
budget REAL,
ssn INT NOT NULL,
since DATE,
PRIMARY KEY (did),
FOREIGN KEY (ssn) REFERENCES Employees ON DELETE NO ACTION)

The NO ACTION ensures that an Employees tuple cannot be deleted while it is pointed to
by a Dept-Mgr tuple. If we wish to delete such an Employees tuple, we must first change
the DepLMgr tuple to have a new employee as manager.

 Translating Weak Entity Sets

HADIFA
ASST. PROFESSOR Page 17
 Create a table for the weak entity set.
 Make each attribute of the weak entity set a field of the table.
 Add fields for the primary key of the identifying owner entity.
 Declare a foreign these identifying owner fields.
 Delete any tuples in the table (rooms) if corresponding tuple is deleted from
primary( buildings) entity.

 Translating Class Hierarchies

HADIFA
ASST. PROFESSOR Page 18
CREATE table PTStudents (

mn interger,

ptfrac integer,

primary key (mn),

foreign key (mn) references Students );

 Translating ER Diagrams with Aggregation

The relation sponsors is participating in monitors relation. The Sponsors relationship


set is mapped as

Create table sponsors ( pid int,


did int,
since Date,
Primary key (pid,did),
Foreign key (pid) REFERENCES
Projects, Foreign key (did) REFERENCES Department);

HADIFA
ASST. PROFESSOR Page 19
For the Monitors relationship set, we create a relation with the following attributes:
 The key attributes of Employees (ssn),
 The key attributes of Sponsors relation (did,pid),
 The descriptive attributes of Monitors (until)

There is a special case in which this translation can be refined by dropping the Sponsors

relation. Consider the Sponsors relation. It has attributes pid, did, and since;
However, if Sponsors has no descriptive attributes and has total participation in Monitors,
then sponsors can be dropped.

VIEWS

Views in SQL are kind of virtual tables. A view also has rows and columns as they are in a
real table in the database. We can create a view by selecting fields from one or more tables
present in the database. A view rows are not explicitly stored in the database but are
computed as needed from a view definition.

We can create View using CREATE VIEW statement. A View can be created from a
single table or multiple tables.

Syntax:

CREATE VIEW view_name

AS SELECT column1,

column2.....

FROM

table_name

WHERE

condition;

HADIFA
ASST. PROFESSOR Page 20
Examples:

 Creating View from a single table:

Student Detail

In this example we will create a View named DetailsView from the table StudentDetails.
Query:

 CREATE VIEW DetailsView AS

 SELECT NAME, ADDRESS


To see the data in the View, we can query the view in the same manner as we query a table.
 FROM StudentDetails
SELECT * FROM DetailsView;
 WHERE S_ID < 5;
Output:

Types of Views

1. Read Only: If the view is used to only look at the table and nothing else, such
a view is called as read only view.

HADIFA
ASST. PROFESSOR Page 21
2. Updatable View: If the view is used to look at the table as well as to
do modifications then such a view is called as updatable view.

UPDATES ON VIEW

Consider the following view:

CREATE VIEW GoodStudents


(sid, gpa) AS SELECT S.sid, S.gpa
FROM
Students S
WHERE
S.gpa> 3.0

We can implement a command to modify the gpa of a GoodStudents row by modifying the
corresponding row in Students. We can delete a GoodStudents row by deleting the
corresponding row from Students. We can insert a GoodStudents row by inserting a row
into Students, using null values in columns of Students that do not appear in GoodStudents
(e.g., sname, login).

Note that primary key columns are not allowed to contain null values. Therefore, if we
attempt to insert rows through a view that does not contain the primary key of the
underlying table, the insertions will be rejected. For example, if GoodStudents contained
sname but not cid, we could not insert rows into Students through insertions to
GoodStudents.

An important observation is that an INSERT or UPDATE may change the underlying base
table so that the resulting (i.e., inserted or modified) row is not in the view. For example, if
we try to insert a row (51234, 2.8) into the view, this row can be (padded with null values
in the other fields of Students and then) added to the underlying Students table, but it will
not appear in the GoodStudents view because it does not satisfy the view condition gpa >
3.0.

The SQL default action is to allow this insertion, but we can disallow it by adding the
clause WITH CHECK OPTION to the definition of the view. In this case, only rows that
will actually appear in the view are permissible insertions.

HADIFA
ASST. PROFESSOR Page 22
DESTROYING/ALTERING TABLES AND VIEWS

DROP VIEW: A view can be dropped using the DROP VIEW command, which is just
like DROP TABLE.

Syntax:
DROP VIEW view_name;
ALTER TABLE
view_name: Name of: ALTER
the ViewTABLE modifies
which we want tothedelete.
structure of an existing table. To add a
column called maiden-name to Students, for example, we would use the following command:

Syntax: ALTER TABLE Students


ADD COLUMN maiden-name
CHAR(10) ;

RELATION ALGEBRA OPERATORS

 Selection (σ): Selection operator is used to select tuples from a relation based on
some condition. A new relation is created by selecting only those rows requested
by the user satisfying a specified condition.

Syntax: σ (Cond)(Relation Name)


E.g: σ (AGE>18)
We can(STUDENT)
also combine several conditions by using logical connectives, AND/OR

 Projection (π): The projection eliminates all attributes of the input relation but
those mentioned in the projection list. That means all other unnecessary fields are
projected out.

Syntax:
∏(Column 1,Column 2….Column n)(Relation Name)

E.g: Extract ROLL_NO and NAME from STUDENT relation


∏(ROLL_NO,NAME)(STUDENT)

HADIFA
ASST. PROFESSOR Page 23
Union (U): Union on two relations R1 and R2 can only be computed if R1 and R2 are union
compatible (i.e These two relation should have same number of attributes and corresponding
attributes in two relations have same domain) . Union operator when applied on two relations R1
and R2 will give a relation with tuples which are either in R1 or in R2. The tuples which are in
both R1 and R2 will appear only once in result relation

Syntax:
Relation1 U Relation2

 Intersection (∩): Defines a relation consisting of a set of all tuple that are in both
A and B. However, A and B must be union-compatible.

 Set Difference/ Minus (-): Two relations R1 and R2 can only be computed if R1
and R2 are union compatible. Minus operator when applied on two relations as
R1-R2 will give a relation with tuples which are in R1 but not in R2.

Syntax:
Relation1 - Relation2

HADIFA
ASST. PROFESSOR Page 24
 Rename(ρ): Rename operator is used to give another name to a relation.

Syntax:
ρ(Relation2, Relation1)
E.g: To rename STUDENT relation to STUDENT1, we can use rename operator like:

ρ(STUDENT1, STUDENT)
 Cross Product(X): Cross product is used to join two relations. For every row of
Relation1, each row of Relation2 is concatenated. If Relation1 has m tuples and and
Relation2 has n tuples, cross product of Relation1 and Relation2 will have m X n
tuples.

Syntax:
Relation1 X Relation2
AB
(Name Age Sex )
(Id Course)

Ram14 MF DS
Sona 15 M DBMS
kim20

AXB
Name Age Sex Id Course

Ram 14 M 1 DS
Ram 14 M 2 DBMS
Sona 15 F 1 DS
Sona 15 F 2 DBMS
Kim 20 M 1 DS
Kim 20 M 2 DBMS

HADIFA
ASST. PROFESSOR Page 25
JOINS

Join operation is essentially a cartesian product followed by a selection criterion. Join


operation denoted by ⋈.

Various forms of join operation are:

Inner Joins:

 Theta/condition join
 EQUI join
 Natural join

Outer join:

 Left Outer Join


 Right Outer Join
 Full Outer Join

 Theta/Condition Join
Theta join combines tuples from different relations provided they satisfy the theta condition.

HADIFA
ASST. PROFESSOR Page 26
S1 x R1

As an example, the result is shown below.

Notation R1 ⋈θ R2

Student

SID Name Std

101 Alex 10

102 Maria 11

HADIFA
ASST. PROFESSOR Page 27
Subjects

Class Subject

10 Math

10 English

11 Music

11 Sports

Cross product of students and subjects relation is

Student_detail

SID Name Std Class Subject

101 Alex 10 10 Maths

101 Alex 10 10 English

101 Alex 10 11 Music

101 Alex 10 11 Sports

HADIFA
ASST. PROFESSOR Page 28
102 Maria 11 10 Maths

102 Maria 11 10 English

102 Maria 11 11 Music

102 Maria 11 11 Sports

STUDENT ⋈Student.Std < Subject.Class SUBJECT

Student_detail

SID Name Std Class Subject

101 Alex 10 11 Music

101 Alex 10 11 Sports

HADIFA
ASST. PROFESSOR Page 29
 Equijoin

When Theta join uses only equality comparison operator, it is said to be equijoin.

An equal sign (=) is used as comparison operator in the where clause to refer equality.

Student

SID Name Std

101 Alex 10

102 Maria 11

HADIFA
ASST. PROFESSOR Page 30
Subjects

Class Subject

10 Math

10 English

11 Music

11 Sports

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

HADIFA
ASST. PROFESSOR Page 31
OUTER JOIN

In an outer join, along with tuples that satisfy the matching criteria, we also include some
or all tuples that do not match the criteria.

 Left Outer Join(A B)

In the left outer join, operation allows keeping all tuple in the left relation. However, if
there is no matching tuple is found in right relation, then the attributes of right relation in
the join result are filled with null values

Consider the following 2 Tables

Num Square

2 4

3 9

4 16

Num Cube

2 8

3 18

5 75

HADIFA
ASST. PROFESSOR Page 32
A
B
A⋈B

Num Square Cube

2 4 4

3 9 9

4 16 null

 Right Outer Join: ( A B)

In the right outer join, operation allows keeping all tuple in the right relation. However, if
there is no matching tuple is found in the left relation, then the attributes of the left relation
in the join result are filled with null values.

A B
A⋈B

Num Cube Square

2 8 4

3 18 9

5 75 null

HADIFA
ASST. PROFESSOR Page 33
Full Outer Join: ( A B)

In a full outer join, all tuples from both relations are included in the result, irrespective of
the matching condition.

A B
A⋈B

Num Cube Square

2 4 8

3 9 18

4 16 null

5 null 75

 Division operator
Division is typically required when you want to find out entities that are interacting with
all entities of a set of different type entities. The division operator is used when we have to
evaluate queries which contain the keyword ‘all’.

Given two relations(tables): R(x,y)

, S(y). where R and S are tables

x and y : column of R

y : column of S

R(x,y) div S(y) means gives all distinct values of x from R that are associated with all
values of y in S.

HADIFA
ASST. PROFESSOR Page 34
Computation of Division: R(x,y) div S(y) Steps:

 Find out all possible combinations of S(y) with R(x) by computing R(x) x(cross
join) S(y), say r1
 Subtract actual R(x,y) from r1, say r2
 x in r2 are those that are not associated with every value in S(y); therefore
R(x)- r2(x) gives us x that are associated with all values in S

Example

Figure 2 explains that when the division operation is performed (R/S), it will retrieve only
those lecturer from relation R who has taken a subject “Prolog” and “Database” from relation
S.

HADIFA
ASST. PROFESSOR Page 35
Relational Calculus
Relational calculus is a non procedural query language. It informs the system what to do
with the relation, but does not inform how to perform it.

 Tuple Relational Calculus (TRC) in DBMS

A tuple relational calculus is a non procedural query language which specifies to select the
tuples in a relation. It can select the tuples with range of values or tuples for certain
attribute values etc. The resulting relation can have one or more tuples.

In Tuple Calculus, a query is expressed as


{t| P(t)}

where t = resulting tuples, P(t) = known as Predicate and these are the conditions that are
used to fetch t
Thus, it generates set of all tuples t, such that Predicate P(t) is true for t.

 P(t) may have various conditions logically combined with OR (∨), AND (𝖠), NOT(¬).
 It also uses 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(t) is true “for all” tuples in relation r.

{t | EMPLOYEE (t) and t.SALARY>10000} – implies that it selects the tuples from
EMPLOYEE relation such that resulting employee tuples will have salary greater than
10000. It is example of selecting a range of values.

{t | EMPLOYEE (t) AND t.DEPT_ID = 10} – this select all the tuples of employee name
who work for Department 10.

A tuple variable is a variable that takes on tuples of a particular relation schema as values. The
variable which is used in the condition is called tuple variable. In above example t.SALARY
and t.DEPT_ID are tuple variables.

HADIFA
ASST. PROFESSOR Page 36
Predicate contains the following

1. Set of comaprision operators (=,>=,<=)

2. Set of connectives

p, P /\ q, P V q, p q

3. set of quantifiers: ∃ and ∀

Any tuple variable with 'For All' or 'there exists' condition is termed as a bound variable.
These are the variables whose meaning does not change if the tuple variable is replaced by
another tuple variable.

Any tuple variable without any 'For All' or 'there exists' condition is called Free Variable.
These are the variables whose meaning changes if the tuple variable is replaced by another
tuple variable.

Example
Table: Loan

LOAN BRANCH
NUMBER NAME AMOUNT

L33 ABC 10000

L35 DEF 15000

L49 GHI 9000

L98 DEF 65000


Table-: Borrower
CUSTOMER NAME LOAN NUMBER

Saurabh L33

Mehak L49

Ria L98

HADIFA
ASST. Page
Table-: Depositor
CUSTOMER NAME ACCOUNT NUMBER

Saurabh 1111

Mehak 1113

Sumiti 1114
Queries-1: Find the loan number, branch, amount of loans of greater than or equal to
10000 amount.
{t| t ∈ loan 𝖠 t[amount]>=10000}
Resulting relation:

LOAN BRANCH
NUMBER NAME AMOUNT

L33 ABC 10000

L35 DEF 15000

L98 DEF 65000


In the above query, t[amount] is known as tupple variable.

Queries-2: Find the loan number for each loan of an amount greater or equal to 10000.
{t| ∃ s ∈ loan(t[loan number] = s[loan number]

𝖠 s[amount]>=10000)}

Resulting relation:

LOAN NUMBER

L33

L35

L98

HADIFA
ASST. Page
Queries-3: 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])
Resulting relation:
𝖠 ∃ u ∈ depositor( t[customer-name] = u[customer-name])}
CUSTOMER NAME

Saurabh

Mehak

 Domain Relational Calculus

In contrast to tuple relational calculus, domain relational calculus uses list of attribute to be
selected from the relation based on the condition. It is same as TRC, but differs by
selecting the attributes rather than selecting whole tuples. It is denoted as below:

{< a1, a2, a3, … an > | P(a1, a2, a3, … an)}

Where a1, a2, a3, … an are attributes of the relation and P is the
condition. Here each attribute is given a variable name

Thus, it generates set of all tuples t, such that Predicate P(t) is true for t.

 P(t) may have various conditions logically combined with OR (∨), AND (𝖠), NOT(¬).
 It also uses 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(t) is true “for all” tuples in relation r.

Any tuple variable with 'For All' or 'there exists' condition is termed as a bound
variable. These are the variables whose meaning does not change if the tuple
variable is replaced by another tuple variable.

Any tuple variable without any 'For All' or 'there exists' condition is called Free
Variable. These are the variables whose meaning changes if the tuple variable is
replaced by another tuple variable.

HADIFA
ASST. Page
Example

Table: Loan

LOAN BRANCH
NUMBER NAME AMOUNT

L33 ABC 10000

L35 DEF 15000

L49 GHI 9000

L98 DEF 65000

Table-: Borrower
CUSTOMER NAME LOAN NUMBER

Saurabh L33

Mehak L49

Ria L98

Table-: Depositor
CUSTOMER NAME ACCOUNT NUMBER

Saurabh 1111

Mehak 1113

Sumiti 1114

HADIFA
ASST. Page
Query-1: Find the loan number, branch, amount of loans of greater than or equal to 100
amount.
Resulting relation:
{≺l, b, a≻ | ≺l, b, a≻ ∈ loan 𝖠 (a ≥ 100)}

LOAN NUMBER BRANCH NAME AMOUNT

L01 Main 200

L03 Main 150

L10 Sub 90

Query-2: Find the loan number for each loan of an amount greater or equal to 150.
{≺l≻ | ∃ b, a (≺l, b, a≻ ∈ loan 𝖠 (a ≥ 150)}
Resulting relation:

LOAN NUMBER

L01

L03

HADIFA
ASST. Page

You might also like