0% found this document useful (0 votes)
10 views84 pages

Dbms Unit 2

The document provides an overview of SQL, detailing its components such as Data Definition Language (DDL), Data Manipulation Language (DML), and Data Control Language (DCL). It covers SQL syntax for creating, altering, and dropping tables, as well as operations for inserting, updating, and deleting data. Additionally, it explains querying techniques, including basic structures, set operations, aggregate functions, and nested subqueries.

Uploaded by

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

Dbms Unit 2

The document provides an overview of SQL, detailing its components such as Data Definition Language (DDL), Data Manipulation Language (DML), and Data Control Language (DCL). It covers SQL syntax for creating, altering, and dropping tables, as well as operations for inserting, updating, and deleting data. Additionally, it explains querying techniques, including basic structures, set operations, aggregate functions, and nested subqueries.

Uploaded by

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

DATABASE MANGEMENT SYSTEMS

Unit-2: Introduction to SQL &


Formal Relational Query Languages
Overview of the SQL Query Language

IBM developed the original version of


SQL
originally called Sequel in early
1970s
Structured Query Language
The SQL language has several parts:
✔ Data Definition Language (DDL)
✔ Data Manipulation Language (DML)
✔ Data Control Language (DCL)
SQL Data Definition
• The set of relations in a database must be specified to the
system by means of a data-definition language (DDL)
• The SQL DDL allows specification of not only a set of
relations, but also information about each relation,
including:
✔ The schema for each relation.
✔ The types of values associated with each attribute.
✔ The integrity constraints.
✔ The set of indices to be maintained for each relation.
✔ The security and authorization information for each
relation.
✔ The physical storage structure of each relation on
disk.
SQL Data Definition(Cont.)
Basic Data Types:
• char(n) / varchar(n) / varchar2(n)
• number / number(p,d)
• date
• int / smallint
• float(n)
• real, double precision
Each type may include a special value called
the null value. A null value indicates an absent
value that may exist but be unknown or that
may not exist at all.
SQL Data Definition(Cont.)
Basic Schema Definition: Create Table
The Syntax (general form) of the create table with
example
create table r
(
create table student
A1 D1, (
A2 D2, sid varchar2(20),
..., sname varchar2(15),
An Dn, tmarks number(5),
integrity-constraint1, avg number(5,2),
...,
integrity-constraintk
primary key(sid)
); );
SQL Data Definition(Cont.)
∙ SQL supports a number of different integrity constraints:
primary key (Aj1 , Aj2, . . . , Ajm ): The primary-key
specification says that attributes Aj1 , Aj2, . . . , Ajm form the
primary key for the relation. The primarykey attributes are
required to be nonnull and unique.
foreign key (Ak1 , Ak2, . . . , Akn ) references s: The foreign
key specification says that the values of attributes (Ak1 ,
Ak2, . . . , Akn ) for any tuple in the relation must correspond
to values of the primary key attributes of some tuple in
relation s.
not null: The not null constraint on an attribute specifies that
the null value is not allowed for that attribute
SQL Data Definition(Cont.)
Alter table
The Syntax of the alter table with example
alter table r alter table student
add A D;
add rank number(3);
alter table r alter table student
drop A; drop rank;

Drop table
The Syntax of the drop table with example
drop table r; drop table student;
SQL Data Manipulation
Insert
Type-1:
insert into student values (‘A101’, ’Mahesh’, 520, 85.73);
Type-2:
insert into student(sid, sname, tmarks, avg) values
(‘A101’, ’Mahesh’, 520, 85.73);
Type-3:
insert into student values(‘&sid’, ‘&sname’, &tmarks,
&avg);
SQL Data Manipulation(Cont.)

Update
update student update student
set tmarks=520 set avg=tmarks/5;
where sid=‘A101’;

Delete
delete * delete
from student; from student
Where sid=‘A105’;
Basic Structure of SQL Queries
• SQL query consists of three clauses:
select, from, and where.

• query takes as its input the relations listed in


the from clause

• operates on them as specified in the where


and select clauses

• then produces a relation as the result


Basic Structure of SQL Queries (Cont.)

Queries on a Single Relation


select sname from student;
select sname, tmarks from student;

select distinct sname from student;

select all sname from student;

select eid, ename, dname, salary * 1.5


from employee;

select ename from employee


where dname=‘AI’ and salary >90000;
Basic Structure of SQL Queries (Cont.)
Queries on Multiple Relations
A typical SQL query has the form
select A1, A2, ……, An
from r1, r2, ….., rm
where p;
select ename, employee.dname, salary
from employee, department
where employee.dname= department.dname;
(or)
select ename, e.dname, salary
from employee e, department d
where e.dname= d.dname;
select fname, cid
from faculty f, course c
where f.fid= c.fid and f.dname = ’AI’;
Basic Structure of SQL Queries (Cont.)

Natural join: The natural join operation operates on


two relations and produces a relation as the result.
Concatenates each tuple of the first relation with every
tuple of the second. Natural join considers only those
pairs of tuples with the same value on those attributes
that appear in the schemas of both relations.
select fname, cid
from faculty natural join course;

A from clause in an SQL query can have multiple relations


combined using natural join
select A1, A2, . . . , An
from r1 natural join r2 natural join … natural join rm
where P;
Basic Structure of SQL Queries (Cont.)

select fname, cname


from faculty natural join department, course
where course.cid=department.cid;

select fname, cname


from faculty natural join department natural join course;

select fname, cname


from (faculty natural join department) join course using
(course id);
Additional Basic Operations
The Rename Operation: SQL provides a way of renaming the
attributes and Tables using as clause.
old-name as new-name
 select fname as FacultyName, cid
 from faculty, course
 where faculty.fid = course.fid;

● select F.fname, C.cid


● from faculty as F, course as C
● where F.fid= C.fid;

● select distinct F.fname


● from faculty as F, faculty as S
● where F.salary > S.salary and S.dname = ’AI’;
Additional Basic Operations(cont.)

String Operations
SQL permits a variety of functions on character strings:

• Concatenating (using “||”)



SELECT 'Hello' || ' ' || 'World' AS concatenated_string FROM dual;
• extracting substrings

SELECT SUBSTR('Hello World', starting_pos,size) AS substring FROM
dual;
• finding the length of strings

SELECT LENGTH(sname) AS string_length FROM sailors;
• Converting strings to uppercase (using the function
upper(s) where s is a string)
• Converting strings to lowercase (using the function
lower(s) where s is a string)

• Removing spaces at the end of the string(using trim(s))



Additional Basic Operations(cont.)
String Operations
Pattern matching can be performed on strings, using the
operator like.
• Percent (%): The % character matches any substring.
• Underscore (_): The character matches any character.

Patterns are case sensitive; that is, uppercase characters do


not match lowercase characters, or vice versa.
• ’Intro%’ matches any string beginning with “Intro”.
• ’%Comp%’ matches any string containing “Comp” as a substring,
for example,’Intro. to Computer Science’, and ’Computational
Biology’.
• ’_ _ _ ’ matches any string of exactly three characters.
• ’ _ _ _%’ matches any string of at least three characters.
select cname
from customer
where city like ’%Hydera%’;
Additional Basic Operations(cont.)
String Operations
The escape character is used immediately before a
special pattern character to indicate that the special
pattern character is to be treated like a normal
character. We define the escape character for a like
comparison using the escape keyword.
• like ’ab\%cd%’ escape ’\’ matches all strings
beginning with “ab%cd”.
• like ’ab\\cd%’ escape ’\’ matches all strings
beginning with “ab\cd”.

Attribute Specification in Select Clause


The asterisk symbol “ * ” can be used in the select clause
to denote “all attributes.”
select faculty.*
from faculty, course
where faculty.fid= course.fid;
Additional Basic Operations(cont.)
Ordering the display of Tuples

The order by clause causes the tuples in the result of a


query to appear in sorted order.

select fname
from faculty
where dname = ’AI’
order by fname;

select *
from student
order by age desc, sname asc;
Additional Basic Operations(cont.)

Where Clause Predicates

SQL includes a between comparison operator to simplify


where clauses specify that a value be less than or equal
to some value and greater than or equal to some other
value.
select fname
from faculty
where salary between 90000 and 100000;

Instead of :
select fname
from faculty
where salary <= 100000 and salary >= 90000;

we can use the not between comparison operator.


Set Operations
The SQL operations union, intersect, and except operate
on relations and correspond to the mathematical set-theory
operations ∪, ∩, and −.
The Union Operation
(select cid
from course
where semester = ’Even’ and year= 2021)
union
(select cid
from course
where semester = ’Odd’ and year= 2022);

The union operation automatically eliminates duplicates.

If we want to retain all duplicates, we must write union all in pla


Set Operations(cont.)

The Intersect Operation


(select cid
from course
where semester = ’Even’ and year= 2021)
intersect
(select cid
from course
where semester = ’Odd’ and year= 2022);

The intersect operation automatically eliminates duplicates.

If we want to retain all duplicates, we must write


intersect all in place of intersect:
Set Operations(cont.)

The Except Operation


(select cid
from course
where semester = ’Even’ and year= 2021)
except
(select cid
from course
where semester = ’Odd’ and year= 2022);

The except operation eliminates duplicates.

If we want to retain duplicates, we must write except all


in place of except:
Null Values
Null values present special problems in relational operations, including
arithmetic operations, comparison operations, and set operations. SQL
therefore treats as unknown the result of any comparison involving a
null value.

Boolean Operations
The predicate in a where clause can involve Boolean operations such
as and, or, and not on the results of comparisons, the definitions of the
Boolean operations are extended to deal with the value unknown.
and: The result of true and unknown is unknown, false and unknown is
false, while unknown and unknown is unknown.

or: The result of true or unknown is true, false or unknown is


unknown, while unknown or unknown is unknown.

not: The result of not unknown is unknown.


If the where clause predicate evaluates to either false or unknown for a
tuple, that tuple is not added to the result.
select fname
from faculty
where salary is null;
Aggregate Functions
Aggregate functions are functions that take a collection (a set or
multiset) of values as input and return a single value.
• Average: avg
• Minimum: min
• Maximum: max
• Total: sum
• Count: count
The input to sum and avg must be a collection of numbers, but the
other operators can operate on collections of nonnumeric data
types, such as strings, as well.
select sum (salary)
from faculty;
select avg (salary) select avg (salary) as average salary
from faculty from faculty
where dname= ’AI’; where dname= ’AI’;

select count (distinct cid)


from course
where semester = ’Even’ and year = 2020;
Aggregate Functions(cont.)
Aggregation with Grouping

select dname, avg (salary) as average salary


from faculty
group by dname;

select dname, count (distinct fid) as faculty count


from faculty natural join course
where semester = ’Even’ and year = 2020
group by dname;

select dname, fid, avg (salary)


from faculty
group by dname;
Aggregate Functions(cont.)

The Having Clause


it is useful to state a condition that applies to groups rather
than to tuples.

select dname, avg (salary) as average salary


from faculty
group by dname
having avg (salary) > 45000;

select cid, semester, year, secid, avg (total_credits)


from registration natural join student
where year = 2020
group by cid, semester, year, secid
having count (sid) >= 2;
Nested Subqueries
A Nested subquery is a select-from where expression that is
nested within another query.
Set Membership

SQL allows testing tuples for membership in a relation.


The in connective tests for set membership, where the set is a
collection of values produced by a select clause.
The not in connective tests for the absence of set membership.

select distinct cid


from course
where semester = ’Even’ and year= 2020 and cid not in
(select cid
from course
where semester = ’Odd’ and year= 2021);
Nested Subqueries(cont.)
select distinct cid
from course
where semester = ’Odd’ and year= 2020 and cid not in
(select cid
from course
where semester = ’Even’ and year= 2021);

select distinct fname


from faculty
where fname not in (’Amar’, ’Eswar’);

select count (distinct fid)


from class
where (cid, secid, semester, year) in
(select cid, secid, semester, year
from course
where course.fid= 10101);
Nested Subqueries(cont.)

Set Comparison
SQL also allows < some, <= some, >= some, = some, and <> some com
select fname from faculty
where salary > some (select salary from faculty where dname = ’AI’);

SQL also allows < all, <= all, >= all, = all, and <> all comparisons.
select fname from faculty
where salary > all (select salary from faculty where dname = ’AI’);

select dname from faculty


group by dname
having avg (salary) >= all (select avg (salary) from faculty group by dname);
Nested Subqueries(cont.)
Test for Empty Relations
SQL includes a feature for testing whether a subquery has
any tuples in its result.
The exists construct returns the value true if the argument
subquery is nonempty. Using the exists construct, we can
write the query “Find all courses taught in both the Fall 2009
semester and in the Spring 2010 semester” in still another
way:
select cid
from section as S
where semester = ’Odd’ and year= 2020 and exists
(select *
from section as T
where semester = ’Even’ and year= 2021 and
S.cid= T.cid);
Nested Subqueries(cont.)
A subquery that uses a correlation name from an outer query
is called a correlated subquery.
select distinct S.sid, S.sname
from student as S
where exists (( select cid
from course
where dname = ’AI’) except
(select C.cid
from class as C
where S.sid = C.sid));

select distinct S.sid, S.sname


from student as S
where not exists ((select cid
from course
where dname = ’AI’) except
(select C.cid
from classs as C
where S.sid = C.sid));
Nested Subqueries(cont.)
Test for the Absence of Duplicate Tuples
SQL includes a boolean function for testing whether a subquery has
duplicate tuples in its result.
The unique construct returns the value true if the argument
subquery contains no duplicate tuples. Using the unique construct,
we can write the query “Find all courses that were offered at most
once in 2020” as follows:
select C.cid
from course as C
where unique (select T.cid
from class as T
where C.cid= T.cid and T.year = 2009);
We can test for the existence of duplicate tuples in a
subquery by using the not unique construct
select C.cid
from course as C
where not unique (select T.cid
from class as T
where C.cid= T.cid and T.year = 2009);
Nested Subqueries(cont.)
Subqueries in the From Clause
SQL allows a subquery expression to be used in the from
clause.
select dept_name, avg_salary
from (select dept_name, avg (salary) as avg_salary
from faculty
group by dept_name)
where avg_salary > 45000;

select dept_name, avg_salary


from (select dept_name, avg (salary)
from faculty
group by dept_name) as dept_avg (dept_name,
avg_salary)
where avg_salary > 45000;
Nested Subqueries(cont.)
Subqueries in the From Clause

select max (tot_salary)


from (select dept_name, sum(salary)
from faculty
group by dept_name) as dept_total (dept name, tot salary);

SQL:2003 allows a subquery in the from clause that is prefixed


by the lateral keyword to access attributes of preceding
tables or subqueries in the from clause.

select fname, salary, avg_salary


from faculty f101, lateral (select avg(salary) as avg_salary
from ifaculty f102
where f102.dname= f101.dname);

Without the lateral clause, the subquery cannot


access the correlation variable f101 from the
Nested Subqueries(cont.)
The with Clause
The with clause provides away of defining a temporary relation whose
definition is available only to the query in which the with clause occurs.
with max_budget (value) as
(select max(budget)
from department)
select budget
from department, max_budget
where department.budget = max_budget.value;
The with clause defines the temporary relation max budget, which is
used in the immediately following query.
with dept_total (dept_name, value) as
(select dept_name, sum(salary)
from faculty
Group by dept_name),dept_total_avg(value) as
(select avg(value)
from dept_total)
select dept_name
from dept_total, dept_total_avg
where dept_total.value >= dept_total_avg.value;
Nested Subqueries(cont.)
Scalar Subqueries
SQL allows subqueries to occur wherever an expression
returning a value is permitted, provided the subquery
returns only one tuple containing a single attribute; such
subqueries are called scalar subqueries.

select dept_name, (select count(*) from faculty


where department.dept_name = faculty.dept_ name) as
num_faculties
from department;
Formal Relational Query Languages
• The Relational Algebra
• Tuple Relational Calculus

The Relational Algebra


• 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.
• There are several other operations—namely,
set intersection, natural join, and assignment
Fundamental Operations
• select, project, and rename operations are called unary
operations, because they operate on one relation.

• other three operations operate on pairs of relations and


are, therefore, called binary operations.

The Select Operation(σ)


The select operation selects tuples that satisfy a given
predicate. We use the lowercase Greek letter sigma (σ) to
denote selection. The predicate appears as a subscript to σ.
The argument relation is in parentheses after the σ.
For example, to select those tuples of the Instructor relation
where the faculty is in the “Physics” department, we write:
σdept_name=“Physics”(Instructor)
Fundamental Operations(cont.)
The Select
Operation
Fundamental Operations(cont.)
• We can find all instructors with salary greater than
Rs.90,000 by writing:

• we can combine several predicates into a larger predicateby


using the connectives and (∧), or (∨), and not ( ¬ ). Thus, to
find the instructors in Physics with a salary greater than
Rs.90,000, we write:

• The selection predicate may include comparisons between


two attributes. To illustrate, consider the relation
department. To find all departments whose name is the
same as their building name, we can write:
Fundamental Operations(cont.)
The Project Operation(pi (∏)):
The project operation is a unary operation
that returns its argument relation , with certain
attributes left out. Since a relation is a set, any
duplicate rows are eliminated.

Projection is denoted by the uppercase Greek


letter pi (∏). List those attributes that we wish to
appear in the result as a subscript to ∏ and
argument relation follows in parentheses.
Fundamental Operations(cont.)
The Project
Operation
Fundamental Operations(cont.)
Composition of Relational Operations

“Find the name of all instructors in the


Physics department.” We write:

since the result of a relational-algebra operation is


of the same type(relation) as its inputs, relational-
algebra operations can be composed together into
a relational-algebra expression.
Fundamental Operations(cont.)
The Union
Operation
Fundamental Operations(cont.)
The Union Operation
• To find the set of all courses taught in the Fall
2009 semester, we write:

• To find the set of all courses taught in the Spring


2010 semester, we write:

• to find the set of all courses taught in the Fall


2009 semester, the Spring 2010 semester, or
both.
Fundamental Operations(cont.)
The Union
Operation
Fundamental Operations(cont.)
The Union Operation

for a union operation r ∪ s to be valid, we require


that two conditions hold:

1. The relations r and s must be of the same arity.


That is, they must have the same number of
attributes.
2. The domains of the ith attribute of r and the
ith attribute of s must be the same, for all i.

r and s can be either database relations or


temporary relations that are the result of
relational-algebra expressions.
Fundamental Operations(cont.)
The Set-Difference Operation

The set-difference operation, denoted by −,allows


us to find tuples that are in one relation but are
not in another. The expression r − s produces a
relation containing those tuples in r but not in s.

We can find all the courses taught in the Fall 2009


semester but not in Spring 2010 semester by
writing:
Fundamental Operations(cont.)
The Set-Difference
Operation
Fundamental Operations(cont.)
The Cartesian-Product Operation

The Cartesian-product operation, denoted by a


cross (×), allows us to combine information from
any two relations. We write the Cartesian product of
relations r1 and r2 as r1 × r2.

For example,
the relation schema for r = instructor × teaches is:

(instructor.ID, instructor.name, instructor.dept


name, instructor.salary teaches.ID, teaches.course
id, teaches.sec id, teaches.semester, teaches.year)
Fundamental Operations(cont.)
The Cartesian-Product
Operation
Fundamental Operations(cont.)
The Cartesian-Product
Operation
Fundamental Operations(cont.)
The Cartesian-Product
Operation
Fundamental Operations(cont.)
The Cartesian-Product
Operation
Fundamental Operations(cont.)
The 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
letter rho ρ.

Query to rename the relation Student as Male


Student and the attributes of Student – RollNo,
SName as (Sno, Name).
ρMaleStudent(Sno,Name)πRollNo,SName(σCondition(Student))
Fundamental Operations(cont.)
The Rename Operation

Query to rename the attributes Name, Age of table


Department to A,B.
ρ (A, B) (Department)

Query to rename the table name Project to Pro and


its attributes to P, Q, R.
ρ Pro(P, Q, R) (Project)

Query to rename the first attribute of the table


Student with attributes A, B, C to P.
ρ (P, B, C) (Student)
Fundamental Operations(cont.)
Formal Definition of the Relational Algebra

A basic expression in the relational algebra consists


of either one of the following:

 A relation in the database


 A constant relation

A constant relation is written by listing its tuples


within { },

for example
{ (22222, Einstein, Physics, 95000), (76543, Singh,
Finance, 80000) }.
Fundamental Operations(cont.)
Formal Definition of the Relational Algebra

Let E1 and E2 be relational-algebra expressions.


Then, the following are all relational-algebra
expressions:
• E1 ∪ E2
• E1 − E2
• E1 × E2
• (E1), where P is a predicate on attributes in E1
(E1), where S is a list consisting of some of the
attributes in E1
• (E1), where x is the new name for the result of E1
Additional Relational-Algebra Operations
The Set-Intersection Operation
Suppose that we wish to find the set of all courses taught in
both the Fall 2009 and the Spring 2010 semesters. Using set
intersection, we can write:
Additional Relational-Algebra Operations
The Natural-Join Operation
Join is a combination of a Cartesian product
followed by a selection process. A Join operation
pairs two tuples from different relations, if and
only if a given join condition is satisfied.

Theta (θ) Join


Theta join combines tuples from different relations
provided they satisfy the theta condition. The join
condition is denoted by the symbol θ.
R1 ⋈θ R2
Additional Relational-Algebra Operations
The Natural-Join Operation
The natural join is a binary operation that allows
us to combine certain selections and a
Cartesian product into one operation.
It is denoted by the join symbol ⋈.

instructor natural join teaches considers only


those pairs of tuples where both the tuple from
instructor and the tuple from teaches have the
same value on the common attribute ID.
Additional Relational-Algebra Operations
The Natural-Join Operation
Additional Relational-Algebra Operations
The Natural-Join Operation
Additional Relational-Algebra Operations
The Natural-Join Operation
The theta join operation is a variant of the
natural-join operation that allows us to combine
a selection and a Cartesian product into a single
operation.

Consider relations r (R) and s(S), and let be a


predicate on attributes in the schema R ∪ S.
The theta join operation r ⋈θ s is defined as
follows:
Additional Relational-Algebra Operations
The Assignment Operation
The assignment operation, denoted by ←, works
like assignment in a programming language. To
illustrate this operation, consider the definition of
the natural-join operation. We could write r ⋈ s
as:

The evaluation of an assignment does not result


in any relation being displayed to the user.
Rather, the result of the expression to the right
of the ← is assigned to the relation variable on
the left of the←.
Additional Relational-Algebra Operations
Outer join Operations
The outer-join operation is an extension of the
join operation to deal with missing information.

The outer join operation works in a manner


similar to the natural join operation we have
already studied, but preserves those tuples that
would be lost in an join by creating tuples in the
result containing null values. outer-join operation to
avoid this loss of information.
Additional Relational-Algebra Operations
Outer join Operations

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.
Additional Relational-Algebra Operations
Outer join Operations
Additional Relational-Algebra Operations
Outer join Operations

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.
Additional Relational-Algebra Operations
Outer join Operations

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.
Extended Relational-Algebra Operations
Relational-algebra operations that provide the ability to
write queries that cannot be expressed using the basic
relational-algebra operations are called extended
relational-algebra operations.

Generalized Projection:
extends the projection operation by allowing operations such as
arithmetic and string functions to be used in the projection list.
generalized-projection operation has the form:

where E is any relational-algebra expression, and each of F1, F2,


. . . , Fn is an arithmetic expression involving constants and
attributes in the schema of E.
Extended Relational-Algebra Operations
Aggregation: aggregate operation permits the use of aggregate
functions such as min or average, on sets of values.

Aggregate functions take a collection of values and return a


single value as a result. For example, the aggregate function sum
takes a collection of values and returns the sum of the values.
Thus, the function sum applied on the collection:
{1, 1, 3, 4, 4, 11} results 24.

The collections on which aggregate functions operate can have


multiple occurrences of a value; the order in which the values
appear is not relevant are called multisets.
Tuple Relational Calculus
• The tuple relational calculus, by contrast, is a
nonprocedural query language.
• describes the desired information without giving
a specific procedure for obtaining that
information.
• A query in the tuple relational calculus is
expressed as:

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.
The Tuple Relational Calculus
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.

Example: Table-1: Customer Table-2: Branch


The Tuple Relational Calculus
Table-3: Account Table-4: Loan
The Tuple Relational Calculus
Table-5: Borrower Table-6: Depositor
The Tuple Relational Calculus
Find the loan number, branch, amount of
Queries-1:
loans of greater than or equal to 10000 amount.

{t| t ∈ loan ∧ t[amount]>=10000} Resulting relation:

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


The Tuple Relational Calculus
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:
The Tuple Relational Calculus
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]) ∧ ∃ u ∈ depositor( t[customer-
name] = u[customer-name])}
Resulting relation:
The Tuple Relational Calculus
Queries-4: Find the names of all customers having
a loan at the “ABC” branch.
{t | ∃ s ∈ borrower(t[customer-name] =
s[customer-name] ∧ ∃ u ∈ loan(u[branch-name]
= “ABC” ∧
u[loan-number] = s[loan-number]))}
Resulting relation:
The Tuple Relational Calculus
Safety of Expressions
A tuple relational calculus expression may
generate an infinite expression.
We need to restrict the relational calculus a bit.

• The of a
denoted
domain dom(P), formula P, is the
referenced in P. set of all
• These include valuesvalues
mentioned in P as well
as values that appear in a tuple of a relation
mentioned in P.
• So, the domain of P is the set of all values
explicitly appearing in P or that appear in
relations mentioned is P.
The Tuple Relational Calculus

Safety of Expressions
We may say an expression { t | P} is safe if all
values that appear in the result are values
from dom(P)

A SAFE EXPRESSION is one that is guaranteed


to yield a finite number of tuples as its
results. Otherwise, it is called UNSAFE.

{ t | not(EMPLOYEE) } is UNSAFE!
THANK YOU

You might also like