SlideShare a Scribd company logo
1 of 180
Download to read offline
UNIT-2
Course Name: Database Management System
04/18/22
Department of Computer Science &
Engineering
Course Outcome (CO): At the
ends of this course students will
have:
CO1: Awareness of database
management basics and different
models that we use for database.
CO2: Design and architecture of
relational model, relational
algebra and SQL queries.
CO3: Implement different form of
normalization.
CO4: Logical representation of
internet database.
CO5: Analysis and concepts of
transaction, concurrency and
recovery systems
Outline
• Relational Model concepts
• Integrity Constraints
• Relational Algebra
Unary Relational Operations
Relational Algebra Operations From Set Theory
Binary Relational Operations
Additional Relational Operations
• Relational Calculus
Tuple Relational Calculus
Domain Relational Calculus
• SQL
Slide 5- 4
Relational Model Concepts
The relational Model of Data is based on the concept of a
Relation
The strength of the relational approach to data management comes
from the formal foundation provided by the theory of relations
We review the essentials of the formal relational model in this
chapter
In practice, there is a standard model based on SQL – this is
described in Chapters 8 and 9
Note: There are several important differences between the formal
model and the practical model, as we shall see
Slide 5- 5
Relational Model Concepts
A Relation is a mathematical concept based on
the ideas of sets
The model was first proposed by Dr. E.F. Codd
of IBM Research in 1970 in the following
paper:
"A Relational Model for Large Shared Data Banks,"
Communications of the ACM, June 1970
The above paper caused a major revolution in the
field of database management and earned Dr.
Codd the coveted ACM Turing Award
Slide 5- 6
Informal Definitions
Informally, a relation looks like a table of values.
A relation typically contains a set of rows.
The data elements in each row represent certain facts that
correspond to a real-world entity or relationship
In the formal model, rows are called tuples
Each column has a column header that gives an indication of the
meaning of the data items in that column
In the formal model, the column header is called an attribute name
(or just attribute)
Slide 5- 7
Example of a Relation
Slide 5- 8
Informal Definitions
Key of a Relation:
Each row has a value of a data item (or set of items) that
uniquely identifies that row in the table
Called the key
In the STUDENT table, SSN is the key
Sometimes row-ids or sequential numbers are assigned as
keys to identify the rows in a table
Called artificial key or surrogate key
Slide 5- 9
Formal Definitions - Schema
The Schema (or description) of a Relation:
Denoted by R(A1, A2, .....An)
R is the name of the relation
The attributes of the relation are A1, A2, ..., An
Example:
CUSTOMER (Cust-id, Cust-name, Address, Phone#)
CUSTOMER is the relation name
Defined over the four attributes: Cust-id, Cust-name, Address,
Phone#
Each attribute has a domain or a set of valid values.
For example, the domain of Cust-id is 6 digit numbers.
Slide 5- 10
Formal Definitions - Tuple
A tuple is an ordered set of values (enclosed in angled brackets
‘< … >’)
Each value is derived from an appropriate domain.
A row in the CUSTOMER relation is a 4-tuple and would consist
of four values, for example:
<632895, "John Smith", "101 Main St. Atlanta, GA 30332", "(404)
894-2000">
This is called a 4-tuple as it has 4 values
A tuple (row) in the CUSTOMER relation.
A relation is a set of such tuples (rows)
Slide 5- 11
Formal Definitions - Domain
A domain has a logical definition:
Example: “USA_phone_numbers” are the set of 10 digit phone numbers valid
in the U.S.
A domain also has a data-type or a format defined for it.
The USA_phone_numbers may have a format: (ddd)ddd-dddd where each d is
a decimal digit.
Dates have various formats such as year, month, date formatted as yyyy-
mm-dd, or as dd mm,yyyy etc.
The attribute name designates the role played by a domain in a relation:
Used to interpret the meaning of the data elements corresponding to that
attribute
Example: The domain Date may be used to define two attributes named
“Invoice-date” and “Payment-date” with different meanings
Slide 5- 12
Formal Definitions - State
The relation state is a subset of the Cartesian
product of the domains of its attributes
each domain contains the set of all possible values
the attribute can take.
Example: attribute Cust-name is defined over the
domain of character strings of maximum
length 25
dom(Cust-name) is varchar(25)
The role these strings play in the CUSTOMER
relation is that of the name of a customer.
Slide 5- 13
Formal Definitions - Summary
Formally,
Given R(A1, A2, .........., An)
r(R)  dom (A1) X dom (A2) X ....X dom(An)
R(A1, A2, …, An) is the schema of the relation
R is the name of the relation
A1, A2, …, An are the attributes of the relation
r(R): a specific state (or "value" or “population”) of relation R –
this is a set of tuples (rows)
r(R) = {t1, t2, …, tn} where each ti is an n-tuple
ti = <v1, v2, …, vn> where each vj element-of dom(Aj)
Slide 5- 14
Formal Definitions - Example
Let R(A1, A2) be a relation schema:
Let dom(A1) = {0,1}
Let dom(A2) = {a,b,c}
Then: dom(A1) X dom(A2) is all possible combinations:
{<0,a> , <0,b> , <0,c>, <1,a>, <1,b>, <1,c> }
The relation state r(R)  dom(A1) X dom(A2)
For example: r(R) could be {<0,a> , <0,b> , <1,c> }
this is one possible state (or “population” or “extension”) r of the
relation R, defined over A1 and A2.
It has three 2-tuples: <0,a> , <0,b> , <1,c>
Slide 5- 15
Definition Summary
Informal Terms Formal Terms
Table Relation
Column Header Attribute
All possible Column
Values
Domain
Row Tuple
Table Definition Schema of a Relation
Populated Table State of the Relation
Slide 5- 16
Example – A relation STUDENT
Slide 5- 17
Characteristics Of Relations
Ordering of tuples in a relation r(R):
The tuples are not considered to be ordered, even
though they appear to be in the tabular form.
Ordering of attributes in a relation schema R
(and of values within each tuple):
We will consider the attributes in R(A1, A2, ..., An)
and the values in t=<v1, v2, ..., vn> to be ordered .
(However, a more general alternative definition of
relation does not require this ordering).
Slide 5- 18
Same state as previous Figure (but
with different order of tuples)
Slide 5- 19
Characteristics Of Relations
Values in a tuple:
All values are considered atomic (indivisible).
Each value in a tuple must be from the domain of the
attribute for that column
If tuple t = <v1, v2, …, vn> is a tuple (row) in the relation
state r of R(A1, A2, …, An)
Then each vi must be a value from dom(Ai)
A special null value is used to represent values that
are unknown or inapplicable to certain tuples.
Slide 5- 20
Characteristics Of Relations
Notation:
We refer to component values of a tuple t by:
t[Ai] or t.Ai
This is the value vi of attribute Ai for tuple t
Similarly, t[Au, Av, ..., Aw] refers to the subtuple of
t containing the values of attributes Au, Av, ...,
Aw, respectively in t
Slide 5- 21
Relational Integrity Constraints
Constraints are conditions that must hold on all valid relation
states.
There are three main types of constraints in the relational model:
Key constraints
Entity integrity constraints
Referential integrity constraints
Another implicit constraint is the domain constraint
Every value in a tuple must be from the domain of its attribute (or
it could be null, if allowed for that attribute)
Slide 5- 22
Key Constraints
Superkey of R:
Is a set of attributes SK of R with the following condition:
No two tuples in any valid relation state r(R) will have the same value
for SK
That is, for any distinct tuples t1 and t2 in r(R), t1[SK]  t2[SK]
This condition must hold in any valid state r(R)
Key of R:
A "minimal" superkey
That is, a key is a superkey K such that removal of any attribute
from K results in a set of attributes that is not a superkey (does
not possess the superkey uniqueness property)
Slide 5- 23
Key Constraints (continued)
Example: Consider the CAR relation schema:
CAR(State, Reg#, SerialNo, Make, Model, Year)
CAR has two keys:
Key1 = {State, Reg#}
Key2 = {SerialNo}
Both are also superkeys of CAR
{SerialNo, Make} is a superkey but not a key.
In general:
Any key is a superkey (but not vice versa)
Any set of attributes that includes a key is a superkey
A minimal superkey is also a key
Slide 5- 24
Key Constraints (continued)
If a relation has several candidate keys, one is chosen arbitrarily
to be the primary key.
The primary key attributes are underlined.
Example: Consider the CAR relation schema:
CAR(State, Reg#, SerialNo, Make, Model, Year)
We chose SerialNo as the primary key
The primary key value is used to uniquely identify each tuple in a
relation
Provides the tuple identity
Also used to reference the tuple from another tuple
General rule: Choose as primary key the smallest of the candidate
keys (in terms of size)
Not always applicable – choice is sometimes subjective
Slide 5- 25
CAR table with two candidate keys –
LicenseNumber chosen as Primary Key
Slide 5- 26
Relational Database Schema
Relational Database Schema:
A set S of relation schemas that belong to the same
database.
S is the name of the whole database schema
S = {R1, R2, ..., Rn}
R1, R2, …, Rn are the names of the individual
relation schemas within the database S
Following slide shows a COMPANY database
schema with 6 relation schemas
Slide 5- 27
COMPANY Database Schema
Slide 5- 28
Entity Integrity
Entity Integrity:
The primary key attributes PK of each relation schema R in S
cannot have null values in any tuple of r(R).
This is because primary key values are used to identify the individual
tuples.
t[PK]  null for any tuple t in r(R)
If PK has several attributes, null is not allowed in any of these
attributes
Note: Other attributes of R may be constrained to disallow
null values, even though they are not members of the
primary key.
Slide 5- 29
Referential Integrity
A constraint involving two relations
The previous constraints involve a single relation.
Used to specify a relationship among tuples in
two relations:
The referencing relation and the referenced
relation.
Slide 5- 30
Referential Integrity
Tuples in the referencing relation R1 have
attributes FK (called foreign key attributes)
that reference the primary key attributes PK of
the referenced relation R2.
A tuple t1 in R1 is said to reference a tuple t2 in R2
if t1[FK] = t2[PK].
A referential integrity constraint can be
displayed in a relational database schema as a
directed arc from R1.FK to R2.
Slide 5- 31
Referential Integrity (or foreign key)
Constraint
Statement of the constraint
The value in the foreign key column (or columns)
FK of the the referencing relation R1 can be
either:
(1) a value of an existing primary key value of a
corresponding primary key PK in the referenced
relation R2, or
(2) a null.
In case (2), the FK in R1 should not be a part of
its own primary key.
Slide 5- 32
Displaying a relational database
schema and its constraints
Each relation schema can be displayed as a row of attribute
names
The name of the relation is written above the attribute names
The primary key attribute (or attributes) will be underlined
A foreign key (referential integrity) constraints is displayed as a
directed arc (arrow) from the foreign key attributes to the
referenced table
Can also point the the primary key of the referenced relation for
clarity
Next slide shows the COMPANY relational schema diagram
Slide 5- 33
Referential Integrity Constraints for COMPANY database
Slide 5- 34
Other Types of Constraints
Semantic Integrity Constraints:
based on application semantics and cannot be
expressed by the model per se
Example: “the max. no. of hours per employee for
all projects he or she works on is 56 hrs per week”
A constraint specification language may have
to be used to express these
SQL-99 allows triggers and ASSERTIONS to
express for some of these
Slide 5- 35
Populated database state
Each relation will have many tuples in its current relation state
The relational database state is a union of all the individual
relation states
Whenever the database is changed, a new state arises
Basic operations for changing the database:
INSERT a new tuple in a relation
DELETE an existing tuple from a relation
MODIFY an attribute of an existing tuple
Next slide shows an example state for the COMPANY database
Slide 5- 36
Populated database state for COMPANY
Slide 5- 37
Update Operations on Relations
INSERT a tuple.
DELETE a tuple.
MODIFY a tuple.
Integrity constraints should not be violated by
the update operations.
Several update operations may have to be
grouped together.
Updates may propagate to cause other updates
automatically. This may be necessary to
Slide 5- 38
Update Operations on Relations
In case of integrity violation, several actions can
be taken:
Cancel the operation that causes the violation
(RESTRICT or REJECT option)
Perform the operation but inform the user of the
violation
Trigger additional updates so the violation is
corrected (CASCADE option, SET NULL option)
Execute a user-specified error-correction routine
Slide 5- 39
Possible violations for each
operation
INSERT may violate any of the constraints:
Domain constraint:
if one of the attribute values provided for the new tuple is not of the
specified attribute domain
Key constraint:
if the value of a key attribute in the new tuple already exists in
another tuple in the relation
Referential integrity:
if a foreign key value in the new tuple references a primary key value
that does not exist in the referenced relation
Entity integrity:
if the primary key value is null in the new tuple
Slide 5- 40
Possible violations for each
operation
DELETE may violate only referential integrity:
If the primary key value of the tuple being deleted is referenced
from other tuples in the database
Can be remedied by several actions: RESTRICT, CASCADE, SET
NULL (see Chapter 8 for more details)
RESTRICT option: reject the deletion
CASCADE option: propagate the new primary key value into the
foreign keys of the referencing tuples
SET NULL option: set the foreign keys of the referencing tuples to
NULL
One of the above options must be specified during database design
for each foreign key constraint
Slide 5- 41
Possible violations for each
operation
UPDATE may violate domain constraint and NOT NULL
constraint on an attribute being modified
Any of the other constraints may also be violated, depending on
the attribute being updated:
Updating the primary key (PK):
Similar to a DELETE followed by an INSERT
Need to specify similar options to DELETE
Updating a foreign key (FK):
May violate referential integrity
Updating an ordinary attribute (neither PK nor FK):
Can only violate domain constraints
Relational Algebra
03/28/22
Department of Computer Science &
Engineering
Slide 6- 43
Relational Algebra Overview
Relational algebra is the basic set of operations
for the relational model
These operations enable a user to specify basic retrieval
requests (or queries)
The result of an operation is a new relation,
which may have been formed from one or
more input relations
This property makes the algebra “closed” (all objects
in relational algebra are relations)
Slide 6- 44
Relational Algebra Overview (continued)
The algebra operations thus produce new
relations
These can be further manipulated using operations of
the same algebra
A sequence of relational algebra operations
forms a relational algebra expression
The result of a relational algebra expression is also a
relation that represents the result of a database query (or
retrieval request)
Slide 6- 45
Brief History of Origins of Algebra
Muhammad ibn Musa al-Khwarizmi (800-847 CE) wrote a book
titled al-jabr about arithmetic of variables
Book was translated into Latin.
Its title (al-jabr) gave Algebra its name.
Al-Khwarizmi called variables “shay”
“Shay” is Arabic for “thing”.
Spanish transliterated “shay” as “xay” (“x” was “sh” in Spain).
In time this word was abbreviated as x.
Where does the word Algorithm come from?
Algorithm originates from “al-Khwarizmi"
Reference: PBS (http://www.pbs.org/empires/islam/innoalgebra.html)
Slide 6- 46
Relational Algebra Overview
Relational Algebra consists of several groups of operations
Unary Relational Operations
SELECT (symbol:  (sigma))
PROJECT (symbol:  (pi))
RENAME (symbol:  (rho))
Relational Algebra Operations From Set Theory
UNION (  ), INTERSECTION (  ), DIFFERENCE (or MINUS, – )
CARTESIAN PRODUCT ( x )
Binary Relational Operations
JOIN (several variations of JOIN exist)
DIVISION
Additional Relational Operations
OUTER JOINS, OUTER UNION
AGGREGATE FUNCTIONS (These compute summary of information: for
example, SUM, COUNT, AVG, MIN, MAX)
Slide 6- 47
Database State for COMPANY
All examples discussed below refer to the COMPANY database shown here.
Slide 6- 48
Unary Relational Operations: SELECT
The SELECT operation (denoted by  (sigma)) is used to select a subset of
the tuples from a relation based on a selection condition.
The selection condition acts as a filter
Keeps only those tuples that satisfy the qualifying condition
Tuples satisfying the condition are selected whereas the other
tuples are discarded (filtered out)
Examples:
Select the EMPLOYEE tuples whose department number is 4:
 DNO = 4 (EMPLOYEE)
Select the employee tuples whose salary is greater than $30,000:
 SALARY > 30,000 (EMPLOYEE)
Slide 6- 49
Unary Relational Operations: SELECT
In general, the select operation is denoted by 
<selection condition>(R) where
the symbol  (sigma) is used to denote the select operator
the selection condition is a Boolean (conditional)
expression specified on the attributes of relation R
tuples that make the condition true are selected
appear in the result of the operation
tuples that make the condition false are filtered out
discarded from the result of the operation
Slide 6- 50
Unary Relational Operations: SELECT (contd.)
SELECT Operation Properties
The SELECT operation  <selection condition>(R) produces a relation S that
has the same schema (same attributes) as R
SELECT  is commutative:
 <condition1>( < condition2> (R)) =  <condition2> ( < condition1> (R))
Because of commutativity property, a cascade (sequence) of SELECT
operations may be applied in any order:
<cond1>(<cond2> (<cond3> (R)) = <cond2> (<cond3> (<cond1> ( R)))
A cascade of SELECT operations may be replaced by a single
selection with a conjunction of all the conditions:
<cond1>(< cond2> (<cond3>(R)) =  <cond1> AND < cond2> AND < cond3>(R)))
The number of tuples in the result of a SELECT is less than (or
equal to) the number of tuples in the input relation R
Slide 6- 51
The following query results refer to this database
state
Slide 6- 52
Unary Relational Operations: PROJECT
PROJECT Operation is denoted by  (pi)
This operation keeps certain columns (attributes)
from a relation and discards the other columns.
PROJECT creates a vertical partitioning
The list of specified columns (attributes) is kept in each
tuple
The other attributes in each tuple are discarded
Example: To list each employee’s first and last
name and salary, the following is used:
LNAME, FNAME,SALARY(EMPLOYEE)
Slide 6- 53
Unary Relational Operations: PROJECT (cont.)
The general form of the project operation is:
<attribute list>(R)
 (pi) is the symbol used to represent the project
operation
<attribute list> is the desired list of attributes from
relation R.
The project operation removes any duplicate
tuples
This is because the result of the project operation
must be a set of tuples
Mathematical sets do not allow duplicate elements.
Slide 6- 54
Unary Relational Operations: PROJECT (contd.)
PROJECT Operation Properties
The number of tuples in the result of projection
<list>(R) is always less or equal to the number of
tuples in R
If the list of attributes includes a key of R, then the
number of tuples in the result of PROJECT is equal to
the number of tuples in R
PROJECT is not commutative
 <list1> ( <list2> (R) ) =  <list1> (R) as long as <list2>
contains the attributes in <list1>
Slide 6- 55
Examples of applying SELECT and PROJECT
operations
Slide 6- 56
Relational Algebra Expressions
We may want to apply several relational algebra
operations one after the other
Either we can write the operations as a single
relational algebra expression by nesting the
operations, or
We can apply one operation at a time and create
intermediate result relations.
In the latter case, we must give names to the
relations that hold the intermediate results.
Slide 6- 57
Single expression versus sequence of relational
operations (Example)
To retrieve the first name, last name, and salary of all employees
who work in department number 5, we must apply a select and
a project operation
We can write a single relational algebra expression as follows:
FNAME, LNAME, SALARY( DNO=5(EMPLOYEE))
OR We can explicitly show the sequence of operations, giving a
name to each intermediate relation:
DEP5_EMPS   DNO=5(EMPLOYEE)
RESULT   FNAME, LNAME, SALARY (DEP5_EMPS)
Slide 6- 58
Unary Relational Operations: RENAME
The RENAME operator is denoted by  (rho)
In some cases, we may want to rename the
attributes of a relation or the relation name or
both
Useful when a query requires multiple operations
Necessary in some cases (see JOIN operation later)
Slide 6- 59
Unary Relational Operations: RENAME (contd.)
The general RENAME operation  can be
expressed by any of the following forms:
S (B1, B2, …, Bn )(R) changes both:
the relation name to S, and
the column (attribute) names to B1, B1, …..Bn
S(R) changes:
the relation name only to S
(B1, B2, …, Bn )(R) changes:
the column (attribute) names only to B1, B1, …..Bn
Slide 6- 60
Unary Relational Operations: RENAME (contd.)
For convenience, we also use a shorthand for
renaming attributes in an intermediate relation:
If we write:
• RESULT   FNAME, LNAME, SALARY (DEP5_EMPS)
• RESULT will have the same attribute names as
DEP5_EMPS (same attributes as EMPLOYEE)
• If we write:
• RESULT (F, M, L, S, B, A, SX, SAL, SU, DNO)
 FNAME, LNAME, SALARY (DEP5_EMPS)
• The 10 attributes of DEP5_EMPS are renamed to F,
M, L, S, B, A, SX, SAL, SU, DNO, respectively
Slide 6- 61
Example of applying multiple operations and
RENAME
Slide 6- 62
Relational Algebra Operations from
Set Theory: UNION
UNION Operation
Binary operation, denoted by 
The result of R  S, is a relation that includes all
tuples that are either in R or in S or in both R and
S
Duplicate tuples are eliminated
The two operand relations R and S must be “type
compatible” (or UNION compatible)
R and S must have same number of attributes
Each pair of corresponding attributes must be type
compatible (have same or compatible domains)
Slide 6- 63
Relational Algebra Operations from
Set Theory: UNION
Example:
To retrieve the social security numbers of all employees who either
work in department 5 (RESULT1 below) or directly supervise an
employee who works in department 5 (RESULT2 below)
We can use the UNION operation as follows:
DEP5_EMPS  DNO=5 (EMPLOYEE)
RESULT1   SSN(DEP5_EMPS)
RESULT2(SSN)  SUPERSSN(DEP5_EMPS)
RESULT  RESULT1  RESULT2
The union operation produces the tuples that are in either RESULT1
or RESULT2 or both
Slide 6- 64
Example of the result of a UNION operation
UNION Example
Slide 6- 65
Relational Algebra Operations from
Set Theory
Type Compatibility of operands is required for the binary set
operation UNION , (also for INTERSECTION , and SET
DIFFERENCE –, see next slides)
R1(A1, A2, ..., An) and R2(B1, B2, ..., Bn) are type compatible
if:
they have the same number of attributes, and
the domains of corresponding attributes are type compatible (i.e.
dom(Ai)=dom(Bi) for i=1, 2, ..., n).
The resulting relation for R1R2 (also for R1R2, or R1–R2,
see next slides) has the same attribute names as the first
operand relation R1 (by convention)
Slide 6- 66
Relational Algebra Operations from Set Theory:
INTERSECTION
INTERSECTION is denoted by 
The result of the operation R  S, is a relation
that includes all tuples that are in both R and S
The attribute names in the result will be the same
as the attribute names in R
The two operand relations R and S must be “type
compatible”
Slide 6- 67
Relational Algebra Operations from Set Theory:
SET DIFFERENCE (cont.)
SET DIFFERENCE (also called MINUS or
EXCEPT) is denoted by –
The result of R – S, is a relation that includes all
tuples that are in R but not in S
The attribute names in the result will be the same
as the attribute names in R
The two operand relations R and S must be “type
compatible”
Slide 6- 68
Example to illustrate the result of UNION,
INTERSECT, and DIFFERENCE
Slide 6- 69
Some properties of UNION, INTERSECT, and
DIFFERENCE
Notice that both union and intersection are commutative
operations; that is
R  S = S  R, and R  S = S  R
Both union and intersection can be treated as n-ary operations
applicable to any number of relations as both are associative
operations; that is
R  (S  T) = (R  S)  T
(R  S)  T = R  (S  T)
The minus operation is not commutative; that is, in general
R – S ≠ S – R
Slide 6- 70
Relational Algebra Operations from Set Theory:
CARTESIAN PRODUCT
CARTESIAN (or CROSS) PRODUCT Operation
This operation is used to combine tuples from two relations in a
combinatorial fashion.
Denoted by R(A1, A2, . . ., An) x S(B1, B2, . . ., Bm)
Result is a relation Q with degree n + m attributes:
Q(A1, A2, . . ., An, B1, B2, . . ., Bm), in that order.
The resulting relation state has one tuple for each combination of
tuples—one from R and one from S.
Hence, if R has nR tuples (denoted as |R| = nR ), and S has nS tuples,
then R x S will have nR * nS tuples.
The two operands do NOT have to be "type compatible”
Slide 6- 71
Relational Algebra Operations from Set Theory:
CARTESIAN PRODUCT (cont.)
Generally, CROSS PRODUCT is not a
meaningful operation
Can become meaningful when followed by other
operations
Example (not meaningful):
FEMALE_EMPS   SEX=’F’(EMPLOYEE)
EMPNAMES   FNAME, LNAME, SSN (FEMALE_EMPS)
EMP_DEPENDENTS  EMPNAMES x DEPENDENT
EMP_DEPENDENTS will contain every combination of
EMPNAMES and DEPENDENT
whether or not they are actually related
Slide 6- 72
Relational Algebra Operations from Set Theory:
CARTESIAN PRODUCT (cont.)
To keep only combinations where the
DEPENDENT is related to the EMPLOYEE,
we add a SELECT operation as follows
Example (meaningful):
FEMALE_EMPS   SEX=’F’(EMPLOYEE)
EMPNAMES   FNAME, LNAME, SSN (FEMALE_EMPS)
EMP_DEPENDENTS  EMPNAMES x DEPENDENT
ACTUAL_DEPS   SSN=ESSN(EMP_DEPENDENTS)
RESULT   FNAME, LNAME, DEPENDENT_NAME (ACTUAL_DEPS)
RESULT will now contain the name of female employees and
their dependents
Slide 6- 73
Example of applying CARTESIAN PRODUCT
Slide 6- 74
Binary Relational Operations:
JOIN
JOIN Operation (denoted by )
The sequence of CARTESIAN PRODECT followed by SELECT is
used quite commonly to identify and select related tuples from
two relations
A special operation, called JOIN combines this sequence into a
single operation
This operation is very important for any relational database with
more than a single relation, because it allows us combine related
tuples from various relations
The general form of a join operation on two relations R(A1, A2, . .
., An) and S(B1, B2, . . ., Bm) is:
R <join condition>S
where R and S can be any relations that result from general
relational algebra expressions.
Slide 6- 75
Binary Relational Operations: JOIN (cont.)
Example: Suppose that we want to retrieve the name of the
manager of each department.
To get the manager’s name, we need to combine each
DEPARTMENT tuple with the EMPLOYEE tuple whose SSN
value matches the MGRSSN value in the department tuple.
We do this by using the join operation.
DEPT_MGR  DEPARTMENT MGRSSN=SSN EMPLOYEE
MGRSSN=SSN is the join condition
Combines each department record with the employee who manages
the department
The join condition can also be specified as
DEPARTMENT.MGRSSN= EMPLOYEE.SSN
Slide 6- 76
Example of applying the JOIN operation
Slide 6- 77
Some properties of JOIN
Consider the following JOIN operation:
R(A1, A2, . . ., An) S(B1, B2, . . ., Bm)
R.Ai=S.Bj
Result is a relation Q with degree n + m attributes:
Q(A1, A2, . . ., An, B1, B2, . . ., Bm), in that order.
The resulting relation state has one tuple for each combination of
tuples—r from R and s from S, but only if they satisfy the join
condition r[Ai]=s[Bj]
Hence, if R has nR tuples, and S has nS tuples, then the join result
will generally have less than nR * nS tuples.
Only related tuples (based on the join condition) will appear in the
result
Slide 6- 78
Some properties of JOIN
The general case of JOIN operation is called a
Theta-join: R S
theta
The join condition is called theta
Theta can be any general boolean expression on
the attributes of R and S; for example:
R.Ai<S.Bj AND (R.Ak=S.Bl OR R.Ap<S.Bq)
Most join conditions involve one or more
equality conditions “AND”ed together; for
example:
R.Ai=S.Bj AND R.Ak=S.Bl AND R.Ap=S.Bq
Slide 6- 79
Binary Relational Operations: EQUIJOIN
EQUIJOIN Operation
The most common use of join involves join
conditions with equality comparisons only
Such a join, where the only comparison operator
used is =, is called an EQUIJOIN.
In the result of an EQUIJOIN we always have one or
more pairs of attributes (whose names need not be
identical) that have identical values in every tuple.
The JOIN seen in the previous example was an
EQUIJOIN.
Slide 6- 80
Binary Relational Operations:
NATURAL JOIN Operation
NATURAL JOIN Operation
Another variation of JOIN called NATURAL JOIN — denoted by
* — was created to get rid of the second (superfluous) attribute
in an EQUIJOIN condition.
because one of each pair of attributes with identical values is
superfluous
The standard definition of natural join requires that the two join
attributes, or each pair of corresponding join attributes, have
the same name in both relations
If this is not the case, a renaming operation is applied first.
Slide 6- 81
Binary Relational Operations
NATURAL JOIN (contd.)
Example: To apply a natural join on the DNUMBER attributes of
DEPARTMENT and DEPT_LOCATIONS, it is sufficient to write:
DEPT_LOCS  DEPARTMENT * DEPT_LOCATIONS
Only attribute with the same name is DNUMBER
An implicit join condition is created based on this attribute:
DEPARTMENT.DNUMBER=DEPT_LOCATIONS.DNUMBER
Another example: Q  R(A,B,C,D) * S(C,D,E)
The implicit join condition includes each pair of attributes with the same
name, “AND”ed together:
R.C=S.C AND R.D.S.D
Result keeps only one attribute of each such pair:
Q(A,B,C,D,E)
Slide 6- 82
Example of NATURAL JOIN operation
Slide 6- 83
Complete Set of Relational Operations
The set of operations including SELECT ,
PROJECT  , UNION , DIFFERENCE - ,
RENAME , and CARTESIAN PRODUCT X
is called a complete set because any other
relational algebra expression can be expressed
by a combination of these five operations.
For example:
R  S = (R  S ) – ((R - S)  (S - R))
R <join condition>S =  <join condition> (R X S)
Slide 6- 84
Binary Relational Operations: DIVISION
DIVISION Operation
The division operation is applied to two relations
R(Z)  S(X), where X subset Z. Let Y = Z - X (and hence Z = X
 Y); that is, let Y be the set of attributes of R that are not
attributes of S.
The result of DIVISION is a relation T(Y) that includes a tuple t if
tuples tR appear in R with tR [Y] = t, and with
tR [X] = ts for every tuple ts in S.
For a tuple t to appear in the result T of the DIVISION, the values
in t must appear in R in combination with every tuple in S.
Slide 6- 85
Example of DIVISION
Slide 6- 86
Recap of Relational Algebra Operations
Slide 6- 87
Additional Relational Operations: Aggregate
Functions and Grouping
A type of request that cannot be expressed in the basic relational
algebra is to specify mathematical aggregate functions on
collections of values from the database.
Examples of such functions include retrieving the average or total
salary of all employees or the total number of employee tuples.
These functions are used in simple statistical queries that
summarize information from the database tuples.
Common functions applied to collections of numeric values
include
SUM, AVERAGE, MAXIMUM, and MINIMUM.
The COUNT function is used for counting tuples or values.
Slide 6- 88
Aggregate Function Operation
Use of the Aggregate Functional operation ℱ
ℱMAX Salary (EMPLOYEE) retrieves the maximum salary value from
the EMPLOYEE relation
ℱMIN Salary (EMPLOYEE) retrieves the minimum Salary value from
the EMPLOYEE relation
ℱSUM Salary (EMPLOYEE) retrieves the sum of the Salary from the
EMPLOYEE relation
ℱCOUNT SSN, AVERAGE Salary (EMPLOYEE) computes the count
(number) of employees and their average salary
Note: count just counts the number of rows, without removing
duplicates
Slide 6- 89
Using Grouping with Aggregation
The previous examples all summarized one or more attributes for
a set of tuples
Maximum Salary or Count (number of) Ssn
Grouping can be combined with Aggregate Functions
Example: For each department, retrieve the DNO, COUNT SSN,
and AVERAGE SALARY
A variation of aggregate operation ℱ allows this:
Grouping attribute placed to left of symbol
Aggregate functions to right of symbol
DNO ℱCOUNT SSN, AVERAGE Salary (EMPLOYEE)
Above operation groups employees by DNO (department
number) and computes the count of employees and average
salary per department
Slide 6- 90
Examples of applying aggregate functions and
grouping
Slide 6- 91
Illustrating aggregate functions and grouping
Slide 6- 92
Additional Relational Operations (cont.)
Recursive Closure Operations
Another type of operation that, in general, cannot be
specified in the basic original relational algebra is
recursive closure.
This operation is applied to a recursive relationship.
An example of a recursive operation is to retrieve all
SUPERVISEES of an EMPLOYEE e at all levels
— that is, all EMPLOYEE e’ directly supervised
by e; all employees e’’ directly supervised by each
employee e’; all employees e’’’ directly supervised
by each employee e’’; and so on.
Slide 6- 93
Additional Relational Operations (cont.)
Although it is possible to retrieve employees at
each level and then take their union, we
cannot, in general, specify a query such as
“retrieve the supervisees of ‘James Borg’ at all
levels” without utilizing a looping mechanism.
The SQL3 standard includes syntax for recursive
closure.
Slide 6- 94
Additional Relational Operations (cont.)
Slide 6- 95
Additional Relational Operations (cont.)
The OUTER JOIN Operation
In NATURAL JOIN and EQUIJOIN, tuples without a matching (or
related) tuple are eliminated from the join result
Tuples with null in the join attributes are also eliminated
This amounts to loss of information.
A set of operations, called OUTER joins, can be used when we
want to keep all the tuples in R, or all those in S, or all those in
both relations in the result of the join, regardless of whether or
not they have matching tuples in the other relation.
Slide 6- 96
Additional Relational Operations (cont.)
The left outer join operation keeps every tuple in
the first or left relation R in R S; if no
matching tuple is found in S, then the
attributes of S in the join result are filled or
“padded” with null values.
A similar operation, right outer join, keeps every
tuple in the second or right relation S in the
result of R S.
A third operation, full outer join, denoted by
keeps all tuples in both the left and the right
relations when no matching tuples are found,
Slide 6- 97
Additional Relational Operations (cont.)
Slide 6- 98
Additional Relational Operations (cont.)
OUTER UNION Operations
The outer union operation was developed to take the
union of tuples from two relations if the relations
are not type compatible.
This operation will take the union of tuples in two
relations R(X, Y) and S(X, Z) that are partially
compatible, meaning that only some of their
attributes, say X, are type compatible.
The attributes that are type compatible are
represented only once in the result, and those
attributes that are not type compatible from either
relation are also kept in the result relation T(X, Y,
Z).
Slide 6- 99
Additional Relational Operations (cont.)
Example: An outer union can be applied to two relations whose
schemas are STUDENT(Name, SSN, Department, Advisor)
and INSTRUCTOR(Name, SSN, Department, Rank).
Tuples from the two relations are matched based on having the same
combination of values of the shared attributes— Name, SSN,
Department.
If a student is also an instructor, both Advisor and Rank will have a
value; otherwise, one of these two attributes will be null.
The result relation STUDENT_OR_INSTRUCTOR will have the
following attributes:
STUDENT_OR_INSTRUCTOR (Name, SSN, Department,
Advisor, Rank)
Slide 6- 100
Examples of Queries in Relational Algebra
n Q1: Retrieve the name and address of all employees who work for the
‘Research’ department.
RESEARCH_DEPT   DNAME=’Research’ (DEPARTMENT)
RESEARCH_EMPS  (RESEARCH_DEPT DNUMBER= DNOEMPLOYEEEMPLOYEE)
RESULT   FNAME, LNAME, ADDRESS (RESEARCH_EMPS)
n Q6: Retrieve the names of employees who have no dependents.
ALL_EMPS   SSN(EMPLOYEE)
EMPS_WITH_DEPS(SSN)   ESSN(DEPENDENT)
EMPS_WITHOUT_DEPS  (ALL_EMPS - EMPS_WITH_DEPS)
RESULT   LNAME, FNAME (EMPS_WITHOUT_DEPS * EMPLOYEE)
03/28/22
Department of Computer Science &
Engineering
Relational Calculus
Slide 6- 102
Relational Calculus
A relational calculus expression creates a new
relation, which is specified in terms of
variables that range over rows of the stored
database relations (in tuple calculus) or over
columns of the stored relations (in domain
calculus).
In a calculus expression, there is no order of
operations to specify how to retrieve the query
result—a calculus expression specifies only
what information the result should contain.
This is the main distinguishing feature between
Slide 6- 103
Relational Calculus
Relational calculus is considered to be a
nonprocedural language.
This differs from relational algebra, where we
must write a sequence of operations to specify
a retrieval request; hence relational algebra can
be considered as a procedural way of stating a
query.
Slide 6- 104
Tuple Relational Calculus
The tuple relational calculus is based on specifying a number of
tuple variables.
Each tuple variable usually ranges over a particular database
relation, meaning that the variable may take as its value any
individual tuple from that relation.
A simple tuple relational calculus query is of the form
{t | COND(t)}
where t is a tuple variable and COND (t) is a conditional expression
involving t.
The result of such a query is the set of all tuples t that satisfy
COND (t).
Slide 6- 105
Tuple Relational Calculus
Example: To find the first and last names of all employees whose
salary is above $50,000, we can write the following tuple
calculus expression:
{t.FNAME, t.LNAME | EMPLOYEE(t) AND
t.SALARY>50000}
The condition EMPLOYEE(t) specifies that the range relation
of tuple variable t is EMPLOYEE.
The first and last name (PROJECTION FNAME, LNAME) of each
EMPLOYEE tuple t that satisfies the condition
t.SALARY>50000 (SELECTION  SALARY >50000) will be
retrieved.
Slide 6- 106
The Existential and Universal Quantifiers
Two special symbols called quantifiers can appear in formulas;
these are the universal quantifier () and the existential
quantifier ().
Informally, a tuple variable t is bound if it is quantified, meaning
that it appears in an ( t) or ( t) clause; otherwise, it is free.
If F is a formula, then so are ( t)(F) and ( t)(F), where t is a
tuple variable.
The formula ( t)(F) is true if the formula F evaluates to true for
some (at least one) tuple assigned to free occurrences of t in F;
otherwise ( t)(F) is false.
The formula ( t)(F) is true if the formula F evaluates to true for
every tuple (in the universe) assigned to free occurrences of t in
F; otherwise ( t)(F) is false.
Slide 6- 107
The Existential and Universal Quantifiers
 is called the universal or “for all” quantifier
because every tuple in “the universe of” tuples
must make F true to make the quantified
formula true.
 is called the existential or “there exists”
quantifier because any tuple that exists in “the
universe of” tuples may make F true to make
the quantified formula true.
Slide 6- 108
Example Query Using Existential Quantifier
Retrieve the name and address of all employees who work for the ‘Research’
department. The query can be expressed as :
{t.FNAME, t.LNAME, t.ADDRESS | EMPLOYEE(t) and ( d)
(DEPARTMENT(d) and d.DNAME=‘Research’ and
d.DNUMBER=t.DNO) }
The only free tuple variables in a relational calculus expression should be
those that appear to the left of the bar ( | ).
In above query, t is the only free variable; it is then bound successively to
each tuple.
If a tuple satisfies the conditions specified in the query, the attributes FNAME,
LNAME, and ADDRESS are retrieved for each such tuple.
The conditions EMPLOYEE (t) and DEPARTMENT(d) specify the range
relations for t and d.
The condition d.DNAME = ‘Research’ is a selection condition and
corresponds to a SELECT operation in the relational algebra, whereas
the condition d.DNUMBER = t.DNO is a JOIN condition.
Slide 6- 109
Example Query Using Universal Quantifier
Find the names of employees who work on all the projects controlled by department
number 5. The query can be:
{e.LNAME, e.FNAME | EMPLOYEE(e) and ( ( x)(not(PROJECT(x)) or
not(x.DNUM=5)
OR ( ( w)(WORKS_ON(w) and w.ESSN=e.SSN and x.PNUMBER=w.PNO))))}
Exclude from the universal quantification all tuples that we are not interested in by
making the condition true for all such tuples.
The first tuples to exclude (by making them evaluate automatically to true) are those
that are not in the relation R of interest.
In query above, using the expression not(PROJECT(x)) inside the universally
quantified formula evaluates to true all tuples x that are not in the PROJECT
relation.
Then we exclude the tuples we are not interested in from R itself. The expression
not(x.DNUM=5) evaluates to true all tuples x that are in the project relation but are
not controlled by department 5.
Finally, we specify a condition that must hold on all the remaining tuples in R.
( ( w)(WORKS_ON(w) and w.ESSN=e.SSN and x.PNUMBER=w.PNO)
Slide 6- 110
Languages Based on Tuple Relational Calculus
The language SQL is based on tuple calculus. It uses the basic
block structure to express the queries in tuple calculus:
SELECT <list of attributes>
FROM <list of relations>
WHERE <conditions>
SELECT clause mentions the attributes being projected, the
FROM clause mentions the relations needed in the query, and
the WHERE clause mentions the selection as well as the join
conditions.
SQL syntax is expanded further to accommodate other operations.
(See Chapter 8).
Slide 6- 111
Languages Based on Tuple Relational Calculus
Another language which is based on tuple
calculus is QUEL which actually uses the
range variables as in tuple calculus. Its syntax
includes:
RANGE OF <variable name> IS <relation name>
Then it uses
RETRIEVE <list of attributes from range variables>
WHERE <conditions>
This language was proposed in the relational
DBMS INGRES.
Slide 6- 112
The Domain Relational Calculus
Another variation of relational calculus called the domain relational calculus,
or simply, domain calculus is equivalent to tuple calculus and to relational
algebra.
The language called QBE (Query-By-Example) that is related to domain
calculus was developed almost concurrently to SQL at IBM Research,
Yorktown Heights, New York.
Domain calculus was thought of as a way to explain what QBE does.
Domain calculus differs from tuple calculus in the type of variables used in
formulas:
Rather than having variables range over tuples, the variables range over
single values from domains of attributes.
To form a relation of degree n for a query result, we must have n of these
domain variables— one for each attribute.
Slide 6- 113
The Domain Relational Calculus
An expression of the domain calculus is of the
form
{ x1, x2, . . ., xn |
COND(x1, x2, . . ., xn, xn+1, xn+2, . . ., xn+m)}
where x1, x2, . . ., xn, xn+1, xn+2, . . ., xn+m are domain
variables that range over domains (of attributes)
and COND is a condition or formula of the domain
relational calculus.
• Six basic operators
– select: 
– project: 
– union: 
– set difference: –
– Cartesian product: x
– rename: 
03/28/22
Department of Computer Science &
Engineering
SQL
History
• IBM Sequel language developed as part of System R project at the IBM
San Jose Research Laboratory
• Renamed Structured Query Language (SQL)
• ANSI and ISO standard SQL:
– SQL-86
– SQL-89
– SQL-92
– SQL:1999 (language name became Y2K compliant!)
– SQL:2003
• Commercial systems offer most, if not all, SQL-92 features, plus varying
feature sets from later standards and special proprietary features.
– Not all examples here may work on your particular system.
Data Definition Language
• The schema for each relation.
• The domain of values associated with each attribute.
• Integrity constraints
• And as we will see later, also other information such as
– The set of indices to be maintained for each relations.
– Security and authorization information for each relation.
– The physical storage structure of each relation on disk.
The SQL data-definition language (DDL) allows the specification
of information about relations, including:
Domain Types in SQL
• char(n). Fixed length character string, with user-specified length n.
• varchar(n). Variable length character strings, with user-specified
maximum length n.
• int. Integer (a finite subset of the integers that is machine-dependent).
• smallint. Small integer (a machine-dependent subset of the integer
domain type).
• numeric(p,d). Fixed point number, with user-specified precision of p
digits, with d digits to the right of decimal point. (ex., numeric(3,1),
allows 44.5 to be stores exactly, but not 444.5 or 0.32)
• real, double precision. Floating point and double-precision floating
point numbers, with machine-dependent precision.
• float(n). Floating point number, with user-specified precision of at
least n digits.
• More are covered in Chapter 4.
Create Table Construct
• An SQL relation is defined using the create table command:
create table r (A1 D1, A2 D2, ..., An Dn,
(integrity-constraint1),
...,
(integrity-constraintk))
– r is the name of the relation
– each Ai is an attribute name in the schema of relation r
– Di is the data type of values in the domain of attribute Ai
• Example:
create table instructor (
ID char(5),
name varchar(20),
dept_name varchar(20),
salary numeric(8,2))
Integrity Constraints in Create
Table
• not null
• primary key (A1, ..., An )
• foreign key (Am, ..., An ) references r
Example:
create table instructor (
ID char(5),
name varchar(20) not null,
dept_name varchar(20),
salary numeric(8,2),
primary key (ID),
foreign key (dept_name) references department);
primary key declaration on an attribute automatically ensures not null
And a Few More Relation
Definitions
• create table student (
ID varchar(5),
name varchar(20) not null,
dept_name varchar(20),
tot_cred numeric(3,0),
primary key (ID),
foreign key (dept_name) references department);
• create table takes (
ID varchar(5),
course_id varchar(8),
sec_id varchar(8),
semester varchar(6),
year numeric(4,0),
grade varchar(2),
primary key (ID, course_id, sec_id, semester, year) ,
foreign key (ID) references student,
foreign key (course_id, sec_id, semester, year) references section);
– Note: sec_id can be dropped from primary key above, to ensure a student
cannot be registered for two sections of the same course in the same semester
And more still
• create table course (
course_id varchar(8),
title varchar(50),
dept_name varchar(20),
credits numeric(2,0),
primary key (course_id),
foreign key (dept_name) references
department);
Updates to tables
• Insert
– insert into instructor values (‘10211’, ’Smith’, ’Biology’, 66000);
• Delete
– Remove all tuples from the student relation
• delete from student
• Drop Table
– drop table r
• Alter
– alter table r add A D
• where A is the name of the attribute to be added to relation r and D is the
domain of A.
• All exiting tuples in the relation are assigned null as the value for the new
attribute.
– alter table r drop A
• where A is the name of an attribute of relation r
• Dropping of attributes not supported by many databases.
Basic Query Structure
• A typical SQL query has the form:
select A1, A2, ..., An
from r1, r2, ..., rm
where P
– Ai represents an attribute
– Ri represents a relation
– P is a predicate.
• The result of an SQL query is a relation.
The select Clause
• The select clause lists the attributes desired in the
result of a query
– corresponds to the projection operation of the relational
algebra
• Example: find the names of all instructors:
select name
from instructor
• NOTE: SQL names are case insensitive (i.e., you
may use upper- or lower-case letters.)
– E.g., Name ≡ NAME ≡ name
– Some people use upper case wherever we use bold font.
The select Clause (Cont.)
• SQL allows duplicates in relations as well
as in query results.
• To force the elimination of duplicates,
insert the keyword distinct after select.
• Find the department names of all
instructors, and remove duplicates
select distinct dept_name
from instructor
• The keyword all specifies that duplicates
should not be removed.
The select Clause (Cont.)
• An asterisk in the select clause denotes “all
attributes”
select *
from instructor
• An attribute can be a literal with no from
clause
select ‘437’
– Results is a table with one column and a single
row with value “437”
– Can give the column a name using:
select ‘437’ as FOO
The select Clause (Cont.)
• The select clause can contain arithmetic
expressions involving the operation, +, –, , and /,
and operating on constants or attributes of tuples.
– The query:
select ID, name, salary/12
from instructor
would return a relation that is the same as the instructor
relation, except that the value of the attribute salary is
divided by 12.
– Can rename “salary/12” using the as clause:
select ID, name, salary/12 as monthly_salary
The where Clause
• The where clause specifies conditions that the result must satisfy
– Corresponds to the selection predicate of the relational algebra.
• To find all instructors in Comp. Sci. dept
select name
from instructor
where dept_name = ‘Comp. Sci.'
• Comparison results can be combined using the logical connectives
and, or, and not
– To find all instructors in Comp. Sci. dept with salary > 80000
select name
from instructor
where dept_name = ‘Comp. Sci.' and salary > 80000
• Comparisons can be applied to results of arithmetic expressions.
The from Clause
• The from clause lists the relations involved in the query
– Corresponds to the Cartesian product operation of the relational
algebra.
• Find the Cartesian product instructor X teaches
select 
from instructor, teaches
– generates every possible instructor – teaches pair, with all
attributes from both relations.
– For common attributes (e.g., ID), the attributes in the resulting
table are renamed using the relation name (e.g., instructor.ID)
• Cartesian product not very useful directly, but useful
combined with where-clause condition (selection operation
in relational algebra).
Cartesian Product
instructor teaches
Examples
• Find the names of all instructors who have taught
some course and the course_id
– select name, course_id
from instructor , teaches
where instructor.ID = teaches.ID
• Find the names of all instructors in the Art
department who have taught some course and the
course_id
– select name, course_id
from instructor , teaches
where instructor.ID = teaches.ID and instructor.
dept_name = ‘Art’
The Rename Operation
• The SQL allows renaming relations and
attributes using the as clause:
old-name as new-name
• Find the names of all instructors who have a
higher salary than
some instructor in ‘Comp. Sci’.
– select distinct T.name
from instructor as T, instructor as S
where T.salary > S.salary and S.dept_name =
‘Comp. Sci.’
Self Join Example
n Relation emp-super
n Find the supervisor of “Bob”
n Find the supervisor of the supervisor of “Bob”
n Find ALL the supervisors (direct and indirect) of “Bob
person supervisor
Bob Alice
Mary Susan
Alice David
David Mary
String Operations
• SQL includes a string-matching operator for comparisons
on character strings. The operator like uses patterns that
are described using two special characters:
– percent ( % ). The % character matches any substring.
– underscore ( _ ). The _ character matches any character.
• Find the names of all instructors whose name includes the
substring “dar”.
select name
from instructor
where name like '%dar%'
• Match the string “100%”
like ‘100 %' escape ''
in that above we use backslash () as the escape character.
String Operations (Cont.)
• Patterns are case sensitive.
• Pattern matching examples:
– ‘Intro%’ matches any string beginning with “Intro”.
– ‘%Comp%’ matches any string containing “Comp” as a substring.
– ‘_ _ _’ matches any string of exactly three characters.
– ‘_ _ _ %’ matches any string of at least three characters.
• SQL supports a variety of string operations such as
– concatenation (using “||”)
– converting from upper to lower case (and vice versa)
– finding string length, extracting substrings, etc.
Ordering the Display of Tuples
• List in alphabetic order the names of all
instructors
select distinct name
from instructor
order by name
• We may specify desc for descending order
or asc for ascending order, for each
attribute; ascending order is the default.
– Example: order by name desc
• Can sort on multiple attributes
– Example: order by dept_name, name
Where Clause Predicates
• SQL includes a between comparison operator
• Example: Find the names of all instructors with
salary between $90,000 and $100,000 (that is, 
$90,000 and  $100,000)
– select name
from instructor
where salary between 90000 and 100000
• Tuple comparison
– select name, course_id
from instructor, teaches
where (instructor.ID, dept_name) = (teaches.ID,
’Biology’);
Duplicates
• In relations with duplicates, SQL can define how many
copies of tuples appear in the result.
• Multiset versions of some of the relational algebra
operators – given multiset relations r1 and r2:
1.  (r1): If there are c1 copies of tuple t1 in r1, and t1 satisfies
selections ,, then there are c1 copies of t1 in  (r1).
2. A (r ): For each copy of tuple t1 in r1, there is a copy of tuple
A (t1) in A (r1) where A (t1) denotes the projection of the single
tuple t1.
3. r1 x r2: If there are c1 copies of tuple t1 in r1 and c2 copies of
tuple t2 in r2, there are c1 x c2 copies of the tuple t1. t2 in r1 x r2
Duplicates (Cont.)
• Example: Suppose multiset relations r1 (A, B) and r2
(C) are as follows:
r1 = {(1, a) (2,a)} r2 = {(2), (3), (3)}
• Then B(r1) would be {(a), (a)}, while B(r1) x r2
would be
{(a,2), (a,2), (a,3), (a,3), (a,3), (a,3)}
• SQL duplicate semantics:
select A1,, A2, ..., An
from r1, r2, ..., rm
where P
is equivalent to the multiset version of the
expression:
))
(
( 2
1
,
,
, 2
1 m
P
A
A
A r
r
r
n



 
 
Set Operations
• Find courses that ran in Fall 2009 or in
Spring 2010
n Find courses that ran in Fall 2009 but not in Spring 2010
(select course_id from section where sem = ‘Fall’ and year = 2009)
union
(select course_id from section where sem = ‘Spring’ and year = 2010)
n Find courses that ran in Fall 2009 and in Spring 2010
(select course_id from section where sem = ‘Fall’ and year = 2009)
intersect
(select course_id from section where sem = ‘Spring’ and year = 2010)
(select course_id from section where sem = ‘Fall’ and year = 2009)
except
(select course_id from section where sem = ‘Spring’ and year = 2010)
Set Operations (Cont.)
• Find the salaries of all instructors that are less than the largest
salary.
– select distinct T.salary
from instructor as T, instructor as S
where T.salary < S.salary
• Find all the salaries of all instructors
– select distinct salary
from instructor
• Find the largest salary of all instructors.
– (select “second query” )
except
(select “first query”)
Set Operations (Cont.)
• Set operations union, intersect, and except
– Each of the above operations automatically
eliminates duplicates
nTo retain all duplicates use the
corresponding multiset versions union all,
intersect all and except all.
nSuppose a tuple occurs m times in r and n
times in s, then, it occurs:
– m + n times in r union all s
– min(m,n) times in r intersect all s
Null Values
• It is possible for tuples to have a null value, denoted
by null, for some of their attributes
• null signifies an unknown value or that a value does
not exist.
• The result of any arithmetic expression involving null
is null
– Example: 5 + null returns null
• The predicate is null can be used to check for null
values.
– Example: Find all instructors whose salary is null.
select name
from instructor
where salary is null
Null Values and Three Valued
Logic
• Three values – true, false, unknown
• Any comparison with null returns unknown
– Example: 5 < null or null <> null or null = null
• Three-valued logic using the value unknown:
– OR: (unknown or true) = true,
(unknown or false) = unknown
(unknown or unknown) = unknown
– AND: (true and unknown) = unknown,
(false and unknown) = false,
(unknown and unknown) = unknown
– NOT: (not unknown) = unknown
– “P is unknown” evaluates to true if predicate P evaluates to unknown
• Result of where clause predicate is treated as false if it evaluates to
unknown
Aggregate Functions
• These functions operate on the multiset
of values of a column of a relation, and
return a value
avg: average value
min: minimum value
max: maximum value
sum: sum of values
count: number of values
Aggregate Functions (Cont.)
• Find the average salary of instructors in the
Computer Science department
– select avg (salary)
from instructor
where dept_name= ’Comp. Sci.’;
• Find the total number of instructors who teach a
course in the Spring 2010 semester
– select count (distinct ID)
from teaches
where semester = ’Spring’ and year = 2010;
• Find the number of tuples in the course relation
– select count (*)
from course;
Aggregate Functions – Group By
• Find the average salary of instructors in each
department
– select dept_name, avg (salary) as avg_salary
from instructor
group by dept_name; avg_salary
Aggregation (Cont.)
• Attributes in select clause outside of aggregate
functions must appear in group by list
– /* erroneous query */
select dept_name, ID, avg (salary)
from instructor
group by dept_name;
Aggregate Functions – Having
Clause
• Find the names and average salaries of all departments
whose average salary is greater than 42000
Note: predicates in the having clause are applied after the
formation of groups whereas predicates in the where
clause are applied before forming groups
select dept_name, avg (salary)
from instructor
group by dept_name
having avg (salary) > 42000;
Null Values and Aggregates
• Total all salaries
select sum (salary )
from instructor
– Above statement ignores null amounts
– Result is null if there is no non-null amount
• All aggregate operations except count(*) ignore
tuples with null values on the aggregated attributes
• What if collection has only null values?
– count returns 0
– all other aggregates return null
Nested Subqueries
• SQL provides a mechanism for the nesting of subqueries. A subquery
is a select-from-where expression that is nested within another query.
• The nesting can be done in the following SQL query
select A1, A2, ..., An
from r1, r2, ..., rm
where P
as follows:
– Ai can be replaced be a subquery that generates a single value.
– ri can be replaced by any valid subquery
– P can be replaced with an expression of the form:
B <operation> (subquery)
Where B is an attribute and <operation> to be defined later.
Subqueries in the Where Clause
Subqueries in the Where Clause
• A common use of subqueries is to
perform tests:
– For set membership
– For set comparisons
– For set cardinality.
Set Membership
• Find courses offered in Fall 2009 and in Spring 2010
n Find courses offered in Fall 2009 but not in Spring 2010
select distinct course_id
from section
where semester = ’Fall’ and year= 2009 and
course_id in (select course_id
from section
where semester = ’Spring’ and year= 2010);
select distinct course_id
from section
where semester = ’Fall’ and year= 2009 and
course_id not in (select course_id
from section
where semester = ’Spring’ and year= 2010);
Set Membership (Cont.)
• Find the total number of (distinct) students who have taken course
sections taught by the instructor with ID 10101
n Note: Above query can be written in a much simpler manner.
The formulation above is simply to illustrate SQL features.
select count (distinct ID)
from takes
where (course_id, sec_id, semester, year) in
(select course_id, sec_id, semester, year
from teaches
where teaches.ID= 10101);
Set Comparison – “some” Clause
• Find names of instructors with salary greater than that of
some (at least one) instructor in the Biology department.
n Same query using > some clause
select name
from instructor
where salary > some (select salary
from instructor
where dept name = ’Biology’);
select distinct T.name
from instructor as T, instructor as S
where T.salary > S.salary and S.dept name = ’Biology’;
Definition of “some” Clause
• F <comp> some r   t  r such that (F <comp>
t )
Where <comp> can be:     
0
5
6
(5 < some ) = true
0
5
0
) = false
5
0
5
(5  some ) = true (since 0  5)
(read: 5 < some tuple in the relation)
(5 < some
) = true
(5 = some
(= some)  in
However, ( some)  not in
Set Comparison – “all” Clause
• Find the names of all instructors whose salary is greater than the
salary of all instructors in the Biology department.
select name
from instructor
where salary > all (select salary
from instructor
where dept name = ’Biology’);
Definition of “all” Clause
• F <comp> all r   t  r (F <comp> t)
0
5
6
(5 < all ) = false
6
10
4
) = true
5
4
6
(5  all ) = true (since 5  4 and 5  6)
(5 < all
) = false
(5 = all
( all)  not in
However, (= all)  in
Test for Empty Relations
• The exists construct returns the value
true if the argument subquery is
nonempty.
• exists r  r  Ø
• not exists r  r = Ø
Use of “exists” Clause
• Yet another way of specifying the query “Find all courses
taught in both the Fall 2009 semester and in the Spring 2010
semester”
select course_id
from section as S
where semester = ’Fall’ and year = 2009 and
exists (select *
from section as T
where semester = ’Spring’ and year= 2010
and S.course_id = T.course_id);
• Correlation name – variable S in the outer query
• Correlated subquery – the inner query
Use of “not exists” Clause
• Find all students who have taken all
courses offered in the Biology department.
select distinct S.ID, S.name
from student as S
where not exists ( (select course_id
from course
where dept_name = ’Biology’)
except
(select T.course_id
from takes as T
where S.ID = T.ID));
• First nested query lists all courses offered in Biology
• Second nested query lists all courses a particular student took
n Note that X – Y = Ø  X  Y
n Note: Cannot write this query using = all and its variants
Test for Absence of Duplicate
Tuples
• The unique construct tests whether a subquery has
any duplicate tuples in its result.
• The unique construct evaluates to “true” if a given
subquery contains no duplicates .
• Find all courses that were offered at most once in
2009
select T.course_id
from course as T
where unique (select R.course_id
from section as R
where T.course_id= R.course_id
and R.year = 2009);
Subqueries in the From Clause
Subqueries in the From Clause
• SQL allows a subquery expression to be used in the from clause
• Find the average instructors’ salaries of those departments where the
average salary is greater than $42,000.”
select dept_name, avg_salary
from (select dept_name, avg (salary) as avg_salary
from instructor
group by dept_name)
where avg_salary > 42000;
• Note that we do not need to use the having clause
• Another way to write above query
select dept_name, avg_salary
from (select dept_name, avg (salary)
from instructor
group by dept_name) as dept_avg (dept_name, avg_salary)
where avg_salary > 42000;
With Clause
• The with clause provides a way of defining a temporary
relation whose definition is available only to the query
in which the with clause occurs.
• Find all departments with the maximum budget
with max_budget (value) as
(select max(budget)
from department)
select department.name
from department, max_budget
where department.budget = max_budget.value;
Complex Queries using With
Clause
• Find all departments where the total salary is greater than the average
of the total salary at all departments
with dept _total (dept_name, value) as
(select dept_name, sum(salary)
from instructor
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;
Subqueries
Scalar Subquery
• Scalar subquery is one which is used where a single value is expected
• List all departments along with the number of instructors in each
department
select dept_name,
(select count(*)
from instructor
where department.dept_name = instructor.dept_name)
as num_instructors
from department;
• Runtime error if subquery returns more than one result tuple
Modification of the Database
• Deletion of tuples from a given relation.
• Insertion of new tuples into a given relation
• Updating of values in some tuples in a
given relation
Deletion
• Delete all instructors
delete from instructor
• Delete all instructors from the Finance department
delete from instructor
where dept_name= ’Finance’;
• Delete all tuples in the instructor relation for those instructors
associated with a department located in the Watson building.
delete from instructor
where dept name in (select dept name
from department
where building = ’Watson’);
Deletion (Cont.)
• Delete all instructors whose salary is less than the
average salary of instructors
delete from instructor
where salary < (select avg (salary)
from instructor);
 Problem: as we delete tuples from deposit, the average salary
changes
 Solution used in SQL:
1. First, compute avg (salary) and find all tuples to delete
2. Next, delete all tuples found above (without
recomputing avg or retesting the tuples)
Insertion
• Add a new tuple to course
insert into course
values (’CS-437’, ’Database
Systems’, ’Comp. Sci.’, 4);
• or equivalently
insert into course (course_id, title,
dept_name, credits)
values (’CS-437’, ’Database
Systems’, ’Comp. Sci.’, 4);
Insertion (Cont.)
• Add all instructors to the student relation with tot_creds set
to 0
insert into student
select ID, name, dept_name, 0
from instructor
• The select from where statement is evaluated fully before
any of its results are inserted into the relation.
Otherwise queries like
insert into table1 select * from table1
would cause problem
Updates
• Increase salaries of instructors whose salary
is over $100,000 by 3%, and all others by a
5%
– Write two update statements:
update instructor
set salary = salary * 1.03
where salary > 100000;
update instructor
set salary = salary * 1.05
where salary <= 100000;
– The order is important
– Can be done better using the case statement
(next slide)
Case Statement for Conditional
Updates
• Same query as before but with case statement
update instructor
set salary = case
when salary <=
100000 then salary * 1.05
else salary * 1.03
end
Updates with Scalar Subqueries
• Recompute and update tot_creds value for all students
update student S
set tot_cred = (select sum(credits)
from takes, course
where takes.course_id = course.course_id and
S.ID= takes.ID.and
takes.grade <> ’F’ and
takes.grade is not null);
• Sets tot_creds to null for students who have not taken any course
• Instead of sum(credits), use:
case
when sum(credits) is not null then sum(credits)
else 0
end
Department of Computer Science &
Engineering
A view is nothing more than a SQL statement that is stored in the
database with an associated name. A view is actually a composition of a
table in the form of a predefined SQL query.
A view can contain all rows of a table or select rows from a table. A view
can be created from one or many tables which depends on the written
SQL query to create a view.
Views, which are a type of virtual tables allow users to do the following −
Structure data in a way that users or classes of users find natural or
intuitive.
Restrict access to the data in such a way that a user can see and
(sometimes) modify exactly what they need and no more.
Summarize data from various tables which can be used to generate
reports.
Views
Department of Computer Science &
Engineering
Database views are created using the CREATE VIEW statement.
Views can be created from a single table, multiple tables or another
view.
To create a view, a user must have the appropriate system privilege
according to the specific implementation.
The basic CREATE VIEW syntax is as follows −
CREATE VIEW view_name AS SELECT column1,
column2..... FROM table_name WHERE [condition];
Consider the CUSTOMERS table having the following records −
ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ |
1 | Ramesh | 32 | Ahmedabad | 2000.00 |
2 | Khilan | 25 | Delhi | 1500.00 | |
3 | kaushik | 23 | Kota | 2000.00 | |
Following is an example to create a view from the CUSTOMERS table. This view would be used to have customer
name and age from the CUSTOMERS table.
SQL > CREATE VIEW CUSTOMERS_VIEW AS SELECT name, age FROM CUSTOMERS;
Now, you can query CUSTOMERS_VIEW in a similar way as you query an actual table. Following is an example for
the same.
SQL > SELECT * FROM CUSTOMERS_VIEW;

More Related Content

Similar to DBMS Unit-2.pdf

Fundamentals of database system - Relational data model and relational datab...
Fundamentals of database system  - Relational data model and relational datab...Fundamentals of database system  - Relational data model and relational datab...
Fundamentals of database system - Relational data model and relational datab...Mustafa Kamel Mohammadi
 
Dbms ii mca-ch4-relational model-2013
Dbms ii mca-ch4-relational model-2013Dbms ii mca-ch4-relational model-2013
Dbms ii mca-ch4-relational model-2013Prosanta Ghosh
 
4_RelationalDataModelAndRelationalMapping.pdf
4_RelationalDataModelAndRelationalMapping.pdf4_RelationalDataModelAndRelationalMapping.pdf
4_RelationalDataModelAndRelationalMapping.pdfLPhct2
 
Upload a presentation to download APPLICATIChapter-02 -
Upload a presentation to download APPLICATIChapter-02 -Upload a presentation to download APPLICATIChapter-02 -
Upload a presentation to download APPLICATIChapter-02 -sualihmehammednur
 
The Relational Data Model and Relational Database Constraints Ch5 (Navathe 4t...
The Relational Data Model and Relational Database Constraints Ch5 (Navathe 4t...The Relational Data Model and Relational Database Constraints Ch5 (Navathe 4t...
The Relational Data Model and Relational Database Constraints Ch5 (Navathe 4t...Raj vardhan
 
The relational data model part[1]
The relational data model part[1]The relational data model part[1]
The relational data model part[1]Bashir Rezaie
 
The Relational Data Model and Relational Database Constraints
The Relational Data Model and Relational Database ConstraintsThe Relational Data Model and Relational Database Constraints
The Relational Data Model and Relational Database Constraintssontumax
 
Chapter 6 relational data model and relational
Chapter  6  relational data model and relationalChapter  6  relational data model and relational
Chapter 6 relational data model and relationalJafar Nesargi
 
Chapter 6 relational data model and relational
Chapter  6  relational data model and relationalChapter  6  relational data model and relational
Chapter 6 relational data model and relationalJafar Nesargi
 
Chapter 6 relational data model and relational
Chapter  6  relational data model and relationalChapter  6  relational data model and relational
Chapter 6 relational data model and relationalJafar Nesargi
 
2. relational model_150903
2. relational model_1509032. relational model_150903
2. relational model_150903Dika Handika
 
ENCh05.ppt
ENCh05.pptENCh05.ppt
ENCh05.pptBestnegi
 
relational model in Database Management.ppt.ppt
relational model in Database Management.ppt.pptrelational model in Database Management.ppt.ppt
relational model in Database Management.ppt.pptRoshni814224
 
Integrity Constraints in Database Management System.ppt
Integrity Constraints in Database Management System.pptIntegrity Constraints in Database Management System.ppt
Integrity Constraints in Database Management System.pptRoshni814224
 
Module 2 - part i
Module   2 - part iModule   2 - part i
Module 2 - part iParthNavale
 

Similar to DBMS Unit-2.pdf (20)

Fundamentals of database system - Relational data model and relational datab...
Fundamentals of database system  - Relational data model and relational datab...Fundamentals of database system  - Relational data model and relational datab...
Fundamentals of database system - Relational data model and relational datab...
 
Dbms ii mca-ch4-relational model-2013
Dbms ii mca-ch4-relational model-2013Dbms ii mca-ch4-relational model-2013
Dbms ii mca-ch4-relational model-2013
 
4_RelationalDataModelAndRelationalMapping.pdf
4_RelationalDataModelAndRelationalMapping.pdf4_RelationalDataModelAndRelationalMapping.pdf
4_RelationalDataModelAndRelationalMapping.pdf
 
Upload a presentation to download APPLICATIChapter-02 -
Upload a presentation to download APPLICATIChapter-02 -Upload a presentation to download APPLICATIChapter-02 -
Upload a presentation to download APPLICATIChapter-02 -
 
The Relational Data Model and Relational Database Constraints Ch5 (Navathe 4t...
The Relational Data Model and Relational Database Constraints Ch5 (Navathe 4t...The Relational Data Model and Relational Database Constraints Ch5 (Navathe 4t...
The Relational Data Model and Relational Database Constraints Ch5 (Navathe 4t...
 
The relational data model part[1]
The relational data model part[1]The relational data model part[1]
The relational data model part[1]
 
The Relational Data Model and Relational Database Constraints
The Relational Data Model and Relational Database ConstraintsThe Relational Data Model and Relational Database Constraints
The Relational Data Model and Relational Database Constraints
 
Chapter 6 relational data model and relational
Chapter  6  relational data model and relationalChapter  6  relational data model and relational
Chapter 6 relational data model and relational
 
Chapter 6 relational data model and relational
Chapter  6  relational data model and relationalChapter  6  relational data model and relational
Chapter 6 relational data model and relational
 
Chapter 6 relational data model and relational
Chapter  6  relational data model and relationalChapter  6  relational data model and relational
Chapter 6 relational data model and relational
 
Unit04 dbms
Unit04 dbmsUnit04 dbms
Unit04 dbms
 
2. relational model_150903
2. relational model_1509032. relational model_150903
2. relational model_150903
 
Relational model
Relational modelRelational model
Relational model
 
ENCh05.ppt
ENCh05.pptENCh05.ppt
ENCh05.ppt
 
relational model in Database Management.ppt.ppt
relational model in Database Management.ppt.pptrelational model in Database Management.ppt.ppt
relational model in Database Management.ppt.ppt
 
ch2
ch2ch2
ch2
 
RDBMS
RDBMSRDBMS
RDBMS
 
Relational Model
Relational ModelRelational Model
Relational Model
 
Integrity Constraints in Database Management System.ppt
Integrity Constraints in Database Management System.pptIntegrity Constraints in Database Management System.ppt
Integrity Constraints in Database Management System.ppt
 
Module 2 - part i
Module   2 - part iModule   2 - part i
Module 2 - part i
 

Recently uploaded

Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 

Recently uploaded (20)

Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 

DBMS Unit-2.pdf

  • 1. UNIT-2 Course Name: Database Management System
  • 2. 04/18/22 Department of Computer Science & Engineering Course Outcome (CO): At the ends of this course students will have: CO1: Awareness of database management basics and different models that we use for database. CO2: Design and architecture of relational model, relational algebra and SQL queries. CO3: Implement different form of normalization. CO4: Logical representation of internet database. CO5: Analysis and concepts of transaction, concurrency and recovery systems
  • 3. Outline • Relational Model concepts • Integrity Constraints • Relational Algebra Unary Relational Operations Relational Algebra Operations From Set Theory Binary Relational Operations Additional Relational Operations • Relational Calculus Tuple Relational Calculus Domain Relational Calculus • SQL
  • 4. Slide 5- 4 Relational Model Concepts The relational Model of Data is based on the concept of a Relation The strength of the relational approach to data management comes from the formal foundation provided by the theory of relations We review the essentials of the formal relational model in this chapter In practice, there is a standard model based on SQL – this is described in Chapters 8 and 9 Note: There are several important differences between the formal model and the practical model, as we shall see
  • 5. Slide 5- 5 Relational Model Concepts A Relation is a mathematical concept based on the ideas of sets The model was first proposed by Dr. E.F. Codd of IBM Research in 1970 in the following paper: "A Relational Model for Large Shared Data Banks," Communications of the ACM, June 1970 The above paper caused a major revolution in the field of database management and earned Dr. Codd the coveted ACM Turing Award
  • 6. Slide 5- 6 Informal Definitions Informally, a relation looks like a table of values. A relation typically contains a set of rows. The data elements in each row represent certain facts that correspond to a real-world entity or relationship In the formal model, rows are called tuples Each column has a column header that gives an indication of the meaning of the data items in that column In the formal model, the column header is called an attribute name (or just attribute)
  • 7. Slide 5- 7 Example of a Relation
  • 8. Slide 5- 8 Informal Definitions Key of a Relation: Each row has a value of a data item (or set of items) that uniquely identifies that row in the table Called the key In the STUDENT table, SSN is the key Sometimes row-ids or sequential numbers are assigned as keys to identify the rows in a table Called artificial key or surrogate key
  • 9. Slide 5- 9 Formal Definitions - Schema The Schema (or description) of a Relation: Denoted by R(A1, A2, .....An) R is the name of the relation The attributes of the relation are A1, A2, ..., An Example: CUSTOMER (Cust-id, Cust-name, Address, Phone#) CUSTOMER is the relation name Defined over the four attributes: Cust-id, Cust-name, Address, Phone# Each attribute has a domain or a set of valid values. For example, the domain of Cust-id is 6 digit numbers.
  • 10. Slide 5- 10 Formal Definitions - Tuple A tuple is an ordered set of values (enclosed in angled brackets ‘< … >’) Each value is derived from an appropriate domain. A row in the CUSTOMER relation is a 4-tuple and would consist of four values, for example: <632895, "John Smith", "101 Main St. Atlanta, GA 30332", "(404) 894-2000"> This is called a 4-tuple as it has 4 values A tuple (row) in the CUSTOMER relation. A relation is a set of such tuples (rows)
  • 11. Slide 5- 11 Formal Definitions - Domain A domain has a logical definition: Example: “USA_phone_numbers” are the set of 10 digit phone numbers valid in the U.S. A domain also has a data-type or a format defined for it. The USA_phone_numbers may have a format: (ddd)ddd-dddd where each d is a decimal digit. Dates have various formats such as year, month, date formatted as yyyy- mm-dd, or as dd mm,yyyy etc. The attribute name designates the role played by a domain in a relation: Used to interpret the meaning of the data elements corresponding to that attribute Example: The domain Date may be used to define two attributes named “Invoice-date” and “Payment-date” with different meanings
  • 12. Slide 5- 12 Formal Definitions - State The relation state is a subset of the Cartesian product of the domains of its attributes each domain contains the set of all possible values the attribute can take. Example: attribute Cust-name is defined over the domain of character strings of maximum length 25 dom(Cust-name) is varchar(25) The role these strings play in the CUSTOMER relation is that of the name of a customer.
  • 13. Slide 5- 13 Formal Definitions - Summary Formally, Given R(A1, A2, .........., An) r(R)  dom (A1) X dom (A2) X ....X dom(An) R(A1, A2, …, An) is the schema of the relation R is the name of the relation A1, A2, …, An are the attributes of the relation r(R): a specific state (or "value" or “population”) of relation R – this is a set of tuples (rows) r(R) = {t1, t2, …, tn} where each ti is an n-tuple ti = <v1, v2, …, vn> where each vj element-of dom(Aj)
  • 14. Slide 5- 14 Formal Definitions - Example Let R(A1, A2) be a relation schema: Let dom(A1) = {0,1} Let dom(A2) = {a,b,c} Then: dom(A1) X dom(A2) is all possible combinations: {<0,a> , <0,b> , <0,c>, <1,a>, <1,b>, <1,c> } The relation state r(R)  dom(A1) X dom(A2) For example: r(R) could be {<0,a> , <0,b> , <1,c> } this is one possible state (or “population” or “extension”) r of the relation R, defined over A1 and A2. It has three 2-tuples: <0,a> , <0,b> , <1,c>
  • 15. Slide 5- 15 Definition Summary Informal Terms Formal Terms Table Relation Column Header Attribute All possible Column Values Domain Row Tuple Table Definition Schema of a Relation Populated Table State of the Relation
  • 16. Slide 5- 16 Example – A relation STUDENT
  • 17. Slide 5- 17 Characteristics Of Relations Ordering of tuples in a relation r(R): The tuples are not considered to be ordered, even though they appear to be in the tabular form. Ordering of attributes in a relation schema R (and of values within each tuple): We will consider the attributes in R(A1, A2, ..., An) and the values in t=<v1, v2, ..., vn> to be ordered . (However, a more general alternative definition of relation does not require this ordering).
  • 18. Slide 5- 18 Same state as previous Figure (but with different order of tuples)
  • 19. Slide 5- 19 Characteristics Of Relations Values in a tuple: All values are considered atomic (indivisible). Each value in a tuple must be from the domain of the attribute for that column If tuple t = <v1, v2, …, vn> is a tuple (row) in the relation state r of R(A1, A2, …, An) Then each vi must be a value from dom(Ai) A special null value is used to represent values that are unknown or inapplicable to certain tuples.
  • 20. Slide 5- 20 Characteristics Of Relations Notation: We refer to component values of a tuple t by: t[Ai] or t.Ai This is the value vi of attribute Ai for tuple t Similarly, t[Au, Av, ..., Aw] refers to the subtuple of t containing the values of attributes Au, Av, ..., Aw, respectively in t
  • 21. Slide 5- 21 Relational Integrity Constraints Constraints are conditions that must hold on all valid relation states. There are three main types of constraints in the relational model: Key constraints Entity integrity constraints Referential integrity constraints Another implicit constraint is the domain constraint Every value in a tuple must be from the domain of its attribute (or it could be null, if allowed for that attribute)
  • 22. Slide 5- 22 Key Constraints Superkey of R: Is a set of attributes SK of R with the following condition: No two tuples in any valid relation state r(R) will have the same value for SK That is, for any distinct tuples t1 and t2 in r(R), t1[SK]  t2[SK] This condition must hold in any valid state r(R) Key of R: A "minimal" superkey That is, a key is a superkey K such that removal of any attribute from K results in a set of attributes that is not a superkey (does not possess the superkey uniqueness property)
  • 23. Slide 5- 23 Key Constraints (continued) Example: Consider the CAR relation schema: CAR(State, Reg#, SerialNo, Make, Model, Year) CAR has two keys: Key1 = {State, Reg#} Key2 = {SerialNo} Both are also superkeys of CAR {SerialNo, Make} is a superkey but not a key. In general: Any key is a superkey (but not vice versa) Any set of attributes that includes a key is a superkey A minimal superkey is also a key
  • 24. Slide 5- 24 Key Constraints (continued) If a relation has several candidate keys, one is chosen arbitrarily to be the primary key. The primary key attributes are underlined. Example: Consider the CAR relation schema: CAR(State, Reg#, SerialNo, Make, Model, Year) We chose SerialNo as the primary key The primary key value is used to uniquely identify each tuple in a relation Provides the tuple identity Also used to reference the tuple from another tuple General rule: Choose as primary key the smallest of the candidate keys (in terms of size) Not always applicable – choice is sometimes subjective
  • 25. Slide 5- 25 CAR table with two candidate keys – LicenseNumber chosen as Primary Key
  • 26. Slide 5- 26 Relational Database Schema Relational Database Schema: A set S of relation schemas that belong to the same database. S is the name of the whole database schema S = {R1, R2, ..., Rn} R1, R2, …, Rn are the names of the individual relation schemas within the database S Following slide shows a COMPANY database schema with 6 relation schemas
  • 27. Slide 5- 27 COMPANY Database Schema
  • 28. Slide 5- 28 Entity Integrity Entity Integrity: The primary key attributes PK of each relation schema R in S cannot have null values in any tuple of r(R). This is because primary key values are used to identify the individual tuples. t[PK]  null for any tuple t in r(R) If PK has several attributes, null is not allowed in any of these attributes Note: Other attributes of R may be constrained to disallow null values, even though they are not members of the primary key.
  • 29. Slide 5- 29 Referential Integrity A constraint involving two relations The previous constraints involve a single relation. Used to specify a relationship among tuples in two relations: The referencing relation and the referenced relation.
  • 30. Slide 5- 30 Referential Integrity Tuples in the referencing relation R1 have attributes FK (called foreign key attributes) that reference the primary key attributes PK of the referenced relation R2. A tuple t1 in R1 is said to reference a tuple t2 in R2 if t1[FK] = t2[PK]. A referential integrity constraint can be displayed in a relational database schema as a directed arc from R1.FK to R2.
  • 31. Slide 5- 31 Referential Integrity (or foreign key) Constraint Statement of the constraint The value in the foreign key column (or columns) FK of the the referencing relation R1 can be either: (1) a value of an existing primary key value of a corresponding primary key PK in the referenced relation R2, or (2) a null. In case (2), the FK in R1 should not be a part of its own primary key.
  • 32. Slide 5- 32 Displaying a relational database schema and its constraints Each relation schema can be displayed as a row of attribute names The name of the relation is written above the attribute names The primary key attribute (or attributes) will be underlined A foreign key (referential integrity) constraints is displayed as a directed arc (arrow) from the foreign key attributes to the referenced table Can also point the the primary key of the referenced relation for clarity Next slide shows the COMPANY relational schema diagram
  • 33. Slide 5- 33 Referential Integrity Constraints for COMPANY database
  • 34. Slide 5- 34 Other Types of Constraints Semantic Integrity Constraints: based on application semantics and cannot be expressed by the model per se Example: “the max. no. of hours per employee for all projects he or she works on is 56 hrs per week” A constraint specification language may have to be used to express these SQL-99 allows triggers and ASSERTIONS to express for some of these
  • 35. Slide 5- 35 Populated database state Each relation will have many tuples in its current relation state The relational database state is a union of all the individual relation states Whenever the database is changed, a new state arises Basic operations for changing the database: INSERT a new tuple in a relation DELETE an existing tuple from a relation MODIFY an attribute of an existing tuple Next slide shows an example state for the COMPANY database
  • 36. Slide 5- 36 Populated database state for COMPANY
  • 37. Slide 5- 37 Update Operations on Relations INSERT a tuple. DELETE a tuple. MODIFY a tuple. Integrity constraints should not be violated by the update operations. Several update operations may have to be grouped together. Updates may propagate to cause other updates automatically. This may be necessary to
  • 38. Slide 5- 38 Update Operations on Relations In case of integrity violation, several actions can be taken: Cancel the operation that causes the violation (RESTRICT or REJECT option) Perform the operation but inform the user of the violation Trigger additional updates so the violation is corrected (CASCADE option, SET NULL option) Execute a user-specified error-correction routine
  • 39. Slide 5- 39 Possible violations for each operation INSERT may violate any of the constraints: Domain constraint: if one of the attribute values provided for the new tuple is not of the specified attribute domain Key constraint: if the value of a key attribute in the new tuple already exists in another tuple in the relation Referential integrity: if a foreign key value in the new tuple references a primary key value that does not exist in the referenced relation Entity integrity: if the primary key value is null in the new tuple
  • 40. Slide 5- 40 Possible violations for each operation DELETE may violate only referential integrity: If the primary key value of the tuple being deleted is referenced from other tuples in the database Can be remedied by several actions: RESTRICT, CASCADE, SET NULL (see Chapter 8 for more details) RESTRICT option: reject the deletion CASCADE option: propagate the new primary key value into the foreign keys of the referencing tuples SET NULL option: set the foreign keys of the referencing tuples to NULL One of the above options must be specified during database design for each foreign key constraint
  • 41. Slide 5- 41 Possible violations for each operation UPDATE may violate domain constraint and NOT NULL constraint on an attribute being modified Any of the other constraints may also be violated, depending on the attribute being updated: Updating the primary key (PK): Similar to a DELETE followed by an INSERT Need to specify similar options to DELETE Updating a foreign key (FK): May violate referential integrity Updating an ordinary attribute (neither PK nor FK): Can only violate domain constraints
  • 42. Relational Algebra 03/28/22 Department of Computer Science & Engineering
  • 43. Slide 6- 43 Relational Algebra Overview Relational algebra is the basic set of operations for the relational model These operations enable a user to specify basic retrieval requests (or queries) The result of an operation is a new relation, which may have been formed from one or more input relations This property makes the algebra “closed” (all objects in relational algebra are relations)
  • 44. Slide 6- 44 Relational Algebra Overview (continued) The algebra operations thus produce new relations These can be further manipulated using operations of the same algebra A sequence of relational algebra operations forms a relational algebra expression The result of a relational algebra expression is also a relation that represents the result of a database query (or retrieval request)
  • 45. Slide 6- 45 Brief History of Origins of Algebra Muhammad ibn Musa al-Khwarizmi (800-847 CE) wrote a book titled al-jabr about arithmetic of variables Book was translated into Latin. Its title (al-jabr) gave Algebra its name. Al-Khwarizmi called variables “shay” “Shay” is Arabic for “thing”. Spanish transliterated “shay” as “xay” (“x” was “sh” in Spain). In time this word was abbreviated as x. Where does the word Algorithm come from? Algorithm originates from “al-Khwarizmi" Reference: PBS (http://www.pbs.org/empires/islam/innoalgebra.html)
  • 46. Slide 6- 46 Relational Algebra Overview Relational Algebra consists of several groups of operations Unary Relational Operations SELECT (symbol:  (sigma)) PROJECT (symbol:  (pi)) RENAME (symbol:  (rho)) Relational Algebra Operations From Set Theory UNION (  ), INTERSECTION (  ), DIFFERENCE (or MINUS, – ) CARTESIAN PRODUCT ( x ) Binary Relational Operations JOIN (several variations of JOIN exist) DIVISION Additional Relational Operations OUTER JOINS, OUTER UNION AGGREGATE FUNCTIONS (These compute summary of information: for example, SUM, COUNT, AVG, MIN, MAX)
  • 47. Slide 6- 47 Database State for COMPANY All examples discussed below refer to the COMPANY database shown here.
  • 48. Slide 6- 48 Unary Relational Operations: SELECT The SELECT operation (denoted by  (sigma)) is used to select a subset of the tuples from a relation based on a selection condition. The selection condition acts as a filter Keeps only those tuples that satisfy the qualifying condition Tuples satisfying the condition are selected whereas the other tuples are discarded (filtered out) Examples: Select the EMPLOYEE tuples whose department number is 4:  DNO = 4 (EMPLOYEE) Select the employee tuples whose salary is greater than $30,000:  SALARY > 30,000 (EMPLOYEE)
  • 49. Slide 6- 49 Unary Relational Operations: SELECT In general, the select operation is denoted by  <selection condition>(R) where the symbol  (sigma) is used to denote the select operator the selection condition is a Boolean (conditional) expression specified on the attributes of relation R tuples that make the condition true are selected appear in the result of the operation tuples that make the condition false are filtered out discarded from the result of the operation
  • 50. Slide 6- 50 Unary Relational Operations: SELECT (contd.) SELECT Operation Properties The SELECT operation  <selection condition>(R) produces a relation S that has the same schema (same attributes) as R SELECT  is commutative:  <condition1>( < condition2> (R)) =  <condition2> ( < condition1> (R)) Because of commutativity property, a cascade (sequence) of SELECT operations may be applied in any order: <cond1>(<cond2> (<cond3> (R)) = <cond2> (<cond3> (<cond1> ( R))) A cascade of SELECT operations may be replaced by a single selection with a conjunction of all the conditions: <cond1>(< cond2> (<cond3>(R)) =  <cond1> AND < cond2> AND < cond3>(R))) The number of tuples in the result of a SELECT is less than (or equal to) the number of tuples in the input relation R
  • 51. Slide 6- 51 The following query results refer to this database state
  • 52. Slide 6- 52 Unary Relational Operations: PROJECT PROJECT Operation is denoted by  (pi) This operation keeps certain columns (attributes) from a relation and discards the other columns. PROJECT creates a vertical partitioning The list of specified columns (attributes) is kept in each tuple The other attributes in each tuple are discarded Example: To list each employee’s first and last name and salary, the following is used: LNAME, FNAME,SALARY(EMPLOYEE)
  • 53. Slide 6- 53 Unary Relational Operations: PROJECT (cont.) The general form of the project operation is: <attribute list>(R)  (pi) is the symbol used to represent the project operation <attribute list> is the desired list of attributes from relation R. The project operation removes any duplicate tuples This is because the result of the project operation must be a set of tuples Mathematical sets do not allow duplicate elements.
  • 54. Slide 6- 54 Unary Relational Operations: PROJECT (contd.) PROJECT Operation Properties The number of tuples in the result of projection <list>(R) is always less or equal to the number of tuples in R If the list of attributes includes a key of R, then the number of tuples in the result of PROJECT is equal to the number of tuples in R PROJECT is not commutative  <list1> ( <list2> (R) ) =  <list1> (R) as long as <list2> contains the attributes in <list1>
  • 55. Slide 6- 55 Examples of applying SELECT and PROJECT operations
  • 56. Slide 6- 56 Relational Algebra Expressions We may want to apply several relational algebra operations one after the other Either we can write the operations as a single relational algebra expression by nesting the operations, or We can apply one operation at a time and create intermediate result relations. In the latter case, we must give names to the relations that hold the intermediate results.
  • 57. Slide 6- 57 Single expression versus sequence of relational operations (Example) To retrieve the first name, last name, and salary of all employees who work in department number 5, we must apply a select and a project operation We can write a single relational algebra expression as follows: FNAME, LNAME, SALARY( DNO=5(EMPLOYEE)) OR We can explicitly show the sequence of operations, giving a name to each intermediate relation: DEP5_EMPS   DNO=5(EMPLOYEE) RESULT   FNAME, LNAME, SALARY (DEP5_EMPS)
  • 58. Slide 6- 58 Unary Relational Operations: RENAME The RENAME operator is denoted by  (rho) In some cases, we may want to rename the attributes of a relation or the relation name or both Useful when a query requires multiple operations Necessary in some cases (see JOIN operation later)
  • 59. Slide 6- 59 Unary Relational Operations: RENAME (contd.) The general RENAME operation  can be expressed by any of the following forms: S (B1, B2, …, Bn )(R) changes both: the relation name to S, and the column (attribute) names to B1, B1, …..Bn S(R) changes: the relation name only to S (B1, B2, …, Bn )(R) changes: the column (attribute) names only to B1, B1, …..Bn
  • 60. Slide 6- 60 Unary Relational Operations: RENAME (contd.) For convenience, we also use a shorthand for renaming attributes in an intermediate relation: If we write: • RESULT   FNAME, LNAME, SALARY (DEP5_EMPS) • RESULT will have the same attribute names as DEP5_EMPS (same attributes as EMPLOYEE) • If we write: • RESULT (F, M, L, S, B, A, SX, SAL, SU, DNO)  FNAME, LNAME, SALARY (DEP5_EMPS) • The 10 attributes of DEP5_EMPS are renamed to F, M, L, S, B, A, SX, SAL, SU, DNO, respectively
  • 61. Slide 6- 61 Example of applying multiple operations and RENAME
  • 62. Slide 6- 62 Relational Algebra Operations from Set Theory: UNION UNION Operation Binary operation, denoted by  The result of R  S, is a relation that includes all tuples that are either in R or in S or in both R and S Duplicate tuples are eliminated The two operand relations R and S must be “type compatible” (or UNION compatible) R and S must have same number of attributes Each pair of corresponding attributes must be type compatible (have same or compatible domains)
  • 63. Slide 6- 63 Relational Algebra Operations from Set Theory: UNION Example: To retrieve the social security numbers of all employees who either work in department 5 (RESULT1 below) or directly supervise an employee who works in department 5 (RESULT2 below) We can use the UNION operation as follows: DEP5_EMPS  DNO=5 (EMPLOYEE) RESULT1   SSN(DEP5_EMPS) RESULT2(SSN)  SUPERSSN(DEP5_EMPS) RESULT  RESULT1  RESULT2 The union operation produces the tuples that are in either RESULT1 or RESULT2 or both
  • 64. Slide 6- 64 Example of the result of a UNION operation UNION Example
  • 65. Slide 6- 65 Relational Algebra Operations from Set Theory Type Compatibility of operands is required for the binary set operation UNION , (also for INTERSECTION , and SET DIFFERENCE –, see next slides) R1(A1, A2, ..., An) and R2(B1, B2, ..., Bn) are type compatible if: they have the same number of attributes, and the domains of corresponding attributes are type compatible (i.e. dom(Ai)=dom(Bi) for i=1, 2, ..., n). The resulting relation for R1R2 (also for R1R2, or R1–R2, see next slides) has the same attribute names as the first operand relation R1 (by convention)
  • 66. Slide 6- 66 Relational Algebra Operations from Set Theory: INTERSECTION INTERSECTION is denoted by  The result of the operation R  S, is a relation that includes all tuples that are in both R and S The attribute names in the result will be the same as the attribute names in R The two operand relations R and S must be “type compatible”
  • 67. Slide 6- 67 Relational Algebra Operations from Set Theory: SET DIFFERENCE (cont.) SET DIFFERENCE (also called MINUS or EXCEPT) is denoted by – The result of R – S, is a relation that includes all tuples that are in R but not in S The attribute names in the result will be the same as the attribute names in R The two operand relations R and S must be “type compatible”
  • 68. Slide 6- 68 Example to illustrate the result of UNION, INTERSECT, and DIFFERENCE
  • 69. Slide 6- 69 Some properties of UNION, INTERSECT, and DIFFERENCE Notice that both union and intersection are commutative operations; that is R  S = S  R, and R  S = S  R Both union and intersection can be treated as n-ary operations applicable to any number of relations as both are associative operations; that is R  (S  T) = (R  S)  T (R  S)  T = R  (S  T) The minus operation is not commutative; that is, in general R – S ≠ S – R
  • 70. Slide 6- 70 Relational Algebra Operations from Set Theory: CARTESIAN PRODUCT CARTESIAN (or CROSS) PRODUCT Operation This operation is used to combine tuples from two relations in a combinatorial fashion. Denoted by R(A1, A2, . . ., An) x S(B1, B2, . . ., Bm) Result is a relation Q with degree n + m attributes: Q(A1, A2, . . ., An, B1, B2, . . ., Bm), in that order. The resulting relation state has one tuple for each combination of tuples—one from R and one from S. Hence, if R has nR tuples (denoted as |R| = nR ), and S has nS tuples, then R x S will have nR * nS tuples. The two operands do NOT have to be "type compatible”
  • 71. Slide 6- 71 Relational Algebra Operations from Set Theory: CARTESIAN PRODUCT (cont.) Generally, CROSS PRODUCT is not a meaningful operation Can become meaningful when followed by other operations Example (not meaningful): FEMALE_EMPS   SEX=’F’(EMPLOYEE) EMPNAMES   FNAME, LNAME, SSN (FEMALE_EMPS) EMP_DEPENDENTS  EMPNAMES x DEPENDENT EMP_DEPENDENTS will contain every combination of EMPNAMES and DEPENDENT whether or not they are actually related
  • 72. Slide 6- 72 Relational Algebra Operations from Set Theory: CARTESIAN PRODUCT (cont.) To keep only combinations where the DEPENDENT is related to the EMPLOYEE, we add a SELECT operation as follows Example (meaningful): FEMALE_EMPS   SEX=’F’(EMPLOYEE) EMPNAMES   FNAME, LNAME, SSN (FEMALE_EMPS) EMP_DEPENDENTS  EMPNAMES x DEPENDENT ACTUAL_DEPS   SSN=ESSN(EMP_DEPENDENTS) RESULT   FNAME, LNAME, DEPENDENT_NAME (ACTUAL_DEPS) RESULT will now contain the name of female employees and their dependents
  • 73. Slide 6- 73 Example of applying CARTESIAN PRODUCT
  • 74. Slide 6- 74 Binary Relational Operations: JOIN JOIN Operation (denoted by ) The sequence of CARTESIAN PRODECT followed by SELECT is used quite commonly to identify and select related tuples from two relations A special operation, called JOIN combines this sequence into a single operation This operation is very important for any relational database with more than a single relation, because it allows us combine related tuples from various relations The general form of a join operation on two relations R(A1, A2, . . ., An) and S(B1, B2, . . ., Bm) is: R <join condition>S where R and S can be any relations that result from general relational algebra expressions.
  • 75. Slide 6- 75 Binary Relational Operations: JOIN (cont.) Example: Suppose that we want to retrieve the name of the manager of each department. To get the manager’s name, we need to combine each DEPARTMENT tuple with the EMPLOYEE tuple whose SSN value matches the MGRSSN value in the department tuple. We do this by using the join operation. DEPT_MGR  DEPARTMENT MGRSSN=SSN EMPLOYEE MGRSSN=SSN is the join condition Combines each department record with the employee who manages the department The join condition can also be specified as DEPARTMENT.MGRSSN= EMPLOYEE.SSN
  • 76. Slide 6- 76 Example of applying the JOIN operation
  • 77. Slide 6- 77 Some properties of JOIN Consider the following JOIN operation: R(A1, A2, . . ., An) S(B1, B2, . . ., Bm) R.Ai=S.Bj Result is a relation Q with degree n + m attributes: Q(A1, A2, . . ., An, B1, B2, . . ., Bm), in that order. The resulting relation state has one tuple for each combination of tuples—r from R and s from S, but only if they satisfy the join condition r[Ai]=s[Bj] Hence, if R has nR tuples, and S has nS tuples, then the join result will generally have less than nR * nS tuples. Only related tuples (based on the join condition) will appear in the result
  • 78. Slide 6- 78 Some properties of JOIN The general case of JOIN operation is called a Theta-join: R S theta The join condition is called theta Theta can be any general boolean expression on the attributes of R and S; for example: R.Ai<S.Bj AND (R.Ak=S.Bl OR R.Ap<S.Bq) Most join conditions involve one or more equality conditions “AND”ed together; for example: R.Ai=S.Bj AND R.Ak=S.Bl AND R.Ap=S.Bq
  • 79. Slide 6- 79 Binary Relational Operations: EQUIJOIN EQUIJOIN Operation The most common use of join involves join conditions with equality comparisons only Such a join, where the only comparison operator used is =, is called an EQUIJOIN. In the result of an EQUIJOIN we always have one or more pairs of attributes (whose names need not be identical) that have identical values in every tuple. The JOIN seen in the previous example was an EQUIJOIN.
  • 80. Slide 6- 80 Binary Relational Operations: NATURAL JOIN Operation NATURAL JOIN Operation Another variation of JOIN called NATURAL JOIN — denoted by * — was created to get rid of the second (superfluous) attribute in an EQUIJOIN condition. because one of each pair of attributes with identical values is superfluous The standard definition of natural join requires that the two join attributes, or each pair of corresponding join attributes, have the same name in both relations If this is not the case, a renaming operation is applied first.
  • 81. Slide 6- 81 Binary Relational Operations NATURAL JOIN (contd.) Example: To apply a natural join on the DNUMBER attributes of DEPARTMENT and DEPT_LOCATIONS, it is sufficient to write: DEPT_LOCS  DEPARTMENT * DEPT_LOCATIONS Only attribute with the same name is DNUMBER An implicit join condition is created based on this attribute: DEPARTMENT.DNUMBER=DEPT_LOCATIONS.DNUMBER Another example: Q  R(A,B,C,D) * S(C,D,E) The implicit join condition includes each pair of attributes with the same name, “AND”ed together: R.C=S.C AND R.D.S.D Result keeps only one attribute of each such pair: Q(A,B,C,D,E)
  • 82. Slide 6- 82 Example of NATURAL JOIN operation
  • 83. Slide 6- 83 Complete Set of Relational Operations The set of operations including SELECT , PROJECT  , UNION , DIFFERENCE - , RENAME , and CARTESIAN PRODUCT X is called a complete set because any other relational algebra expression can be expressed by a combination of these five operations. For example: R  S = (R  S ) – ((R - S)  (S - R)) R <join condition>S =  <join condition> (R X S)
  • 84. Slide 6- 84 Binary Relational Operations: DIVISION DIVISION Operation The division operation is applied to two relations R(Z)  S(X), where X subset Z. Let Y = Z - X (and hence Z = X  Y); that is, let Y be the set of attributes of R that are not attributes of S. The result of DIVISION is a relation T(Y) that includes a tuple t if tuples tR appear in R with tR [Y] = t, and with tR [X] = ts for every tuple ts in S. For a tuple t to appear in the result T of the DIVISION, the values in t must appear in R in combination with every tuple in S.
  • 85. Slide 6- 85 Example of DIVISION
  • 86. Slide 6- 86 Recap of Relational Algebra Operations
  • 87. Slide 6- 87 Additional Relational Operations: Aggregate Functions and Grouping A type of request that cannot be expressed in the basic relational algebra is to specify mathematical aggregate functions on collections of values from the database. Examples of such functions include retrieving the average or total salary of all employees or the total number of employee tuples. These functions are used in simple statistical queries that summarize information from the database tuples. Common functions applied to collections of numeric values include SUM, AVERAGE, MAXIMUM, and MINIMUM. The COUNT function is used for counting tuples or values.
  • 88. Slide 6- 88 Aggregate Function Operation Use of the Aggregate Functional operation ℱ ℱMAX Salary (EMPLOYEE) retrieves the maximum salary value from the EMPLOYEE relation ℱMIN Salary (EMPLOYEE) retrieves the minimum Salary value from the EMPLOYEE relation ℱSUM Salary (EMPLOYEE) retrieves the sum of the Salary from the EMPLOYEE relation ℱCOUNT SSN, AVERAGE Salary (EMPLOYEE) computes the count (number) of employees and their average salary Note: count just counts the number of rows, without removing duplicates
  • 89. Slide 6- 89 Using Grouping with Aggregation The previous examples all summarized one or more attributes for a set of tuples Maximum Salary or Count (number of) Ssn Grouping can be combined with Aggregate Functions Example: For each department, retrieve the DNO, COUNT SSN, and AVERAGE SALARY A variation of aggregate operation ℱ allows this: Grouping attribute placed to left of symbol Aggregate functions to right of symbol DNO ℱCOUNT SSN, AVERAGE Salary (EMPLOYEE) Above operation groups employees by DNO (department number) and computes the count of employees and average salary per department
  • 90. Slide 6- 90 Examples of applying aggregate functions and grouping
  • 91. Slide 6- 91 Illustrating aggregate functions and grouping
  • 92. Slide 6- 92 Additional Relational Operations (cont.) Recursive Closure Operations Another type of operation that, in general, cannot be specified in the basic original relational algebra is recursive closure. This operation is applied to a recursive relationship. An example of a recursive operation is to retrieve all SUPERVISEES of an EMPLOYEE e at all levels — that is, all EMPLOYEE e’ directly supervised by e; all employees e’’ directly supervised by each employee e’; all employees e’’’ directly supervised by each employee e’’; and so on.
  • 93. Slide 6- 93 Additional Relational Operations (cont.) Although it is possible to retrieve employees at each level and then take their union, we cannot, in general, specify a query such as “retrieve the supervisees of ‘James Borg’ at all levels” without utilizing a looping mechanism. The SQL3 standard includes syntax for recursive closure.
  • 94. Slide 6- 94 Additional Relational Operations (cont.)
  • 95. Slide 6- 95 Additional Relational Operations (cont.) The OUTER JOIN Operation In NATURAL JOIN and EQUIJOIN, tuples without a matching (or related) tuple are eliminated from the join result Tuples with null in the join attributes are also eliminated This amounts to loss of information. A set of operations, called OUTER joins, can be used when we want to keep all the tuples in R, or all those in S, or all those in both relations in the result of the join, regardless of whether or not they have matching tuples in the other relation.
  • 96. Slide 6- 96 Additional Relational Operations (cont.) The left outer join operation keeps every tuple in the first or left relation R in R S; if no matching tuple is found in S, then the attributes of S in the join result are filled or “padded” with null values. A similar operation, right outer join, keeps every tuple in the second or right relation S in the result of R S. A third operation, full outer join, denoted by keeps all tuples in both the left and the right relations when no matching tuples are found,
  • 97. Slide 6- 97 Additional Relational Operations (cont.)
  • 98. Slide 6- 98 Additional Relational Operations (cont.) OUTER UNION Operations The outer union operation was developed to take the union of tuples from two relations if the relations are not type compatible. This operation will take the union of tuples in two relations R(X, Y) and S(X, Z) that are partially compatible, meaning that only some of their attributes, say X, are type compatible. The attributes that are type compatible are represented only once in the result, and those attributes that are not type compatible from either relation are also kept in the result relation T(X, Y, Z).
  • 99. Slide 6- 99 Additional Relational Operations (cont.) Example: An outer union can be applied to two relations whose schemas are STUDENT(Name, SSN, Department, Advisor) and INSTRUCTOR(Name, SSN, Department, Rank). Tuples from the two relations are matched based on having the same combination of values of the shared attributes— Name, SSN, Department. If a student is also an instructor, both Advisor and Rank will have a value; otherwise, one of these two attributes will be null. The result relation STUDENT_OR_INSTRUCTOR will have the following attributes: STUDENT_OR_INSTRUCTOR (Name, SSN, Department, Advisor, Rank)
  • 100. Slide 6- 100 Examples of Queries in Relational Algebra n Q1: Retrieve the name and address of all employees who work for the ‘Research’ department. RESEARCH_DEPT   DNAME=’Research’ (DEPARTMENT) RESEARCH_EMPS  (RESEARCH_DEPT DNUMBER= DNOEMPLOYEEEMPLOYEE) RESULT   FNAME, LNAME, ADDRESS (RESEARCH_EMPS) n Q6: Retrieve the names of employees who have no dependents. ALL_EMPS   SSN(EMPLOYEE) EMPS_WITH_DEPS(SSN)   ESSN(DEPENDENT) EMPS_WITHOUT_DEPS  (ALL_EMPS - EMPS_WITH_DEPS) RESULT   LNAME, FNAME (EMPS_WITHOUT_DEPS * EMPLOYEE)
  • 101. 03/28/22 Department of Computer Science & Engineering Relational Calculus
  • 102. Slide 6- 102 Relational Calculus A relational calculus expression creates a new relation, which is specified in terms of variables that range over rows of the stored database relations (in tuple calculus) or over columns of the stored relations (in domain calculus). In a calculus expression, there is no order of operations to specify how to retrieve the query result—a calculus expression specifies only what information the result should contain. This is the main distinguishing feature between
  • 103. Slide 6- 103 Relational Calculus Relational calculus is considered to be a nonprocedural language. This differs from relational algebra, where we must write a sequence of operations to specify a retrieval request; hence relational algebra can be considered as a procedural way of stating a query.
  • 104. Slide 6- 104 Tuple Relational Calculus The tuple relational calculus is based on specifying a number of tuple variables. Each tuple variable usually ranges over a particular database relation, meaning that the variable may take as its value any individual tuple from that relation. A simple tuple relational calculus query is of the form {t | COND(t)} where t is a tuple variable and COND (t) is a conditional expression involving t. The result of such a query is the set of all tuples t that satisfy COND (t).
  • 105. Slide 6- 105 Tuple Relational Calculus Example: To find the first and last names of all employees whose salary is above $50,000, we can write the following tuple calculus expression: {t.FNAME, t.LNAME | EMPLOYEE(t) AND t.SALARY>50000} The condition EMPLOYEE(t) specifies that the range relation of tuple variable t is EMPLOYEE. The first and last name (PROJECTION FNAME, LNAME) of each EMPLOYEE tuple t that satisfies the condition t.SALARY>50000 (SELECTION  SALARY >50000) will be retrieved.
  • 106. Slide 6- 106 The Existential and Universal Quantifiers Two special symbols called quantifiers can appear in formulas; these are the universal quantifier () and the existential quantifier (). Informally, a tuple variable t is bound if it is quantified, meaning that it appears in an ( t) or ( t) clause; otherwise, it is free. If F is a formula, then so are ( t)(F) and ( t)(F), where t is a tuple variable. The formula ( t)(F) is true if the formula F evaluates to true for some (at least one) tuple assigned to free occurrences of t in F; otherwise ( t)(F) is false. The formula ( t)(F) is true if the formula F evaluates to true for every tuple (in the universe) assigned to free occurrences of t in F; otherwise ( t)(F) is false.
  • 107. Slide 6- 107 The Existential and Universal Quantifiers  is called the universal or “for all” quantifier because every tuple in “the universe of” tuples must make F true to make the quantified formula true.  is called the existential or “there exists” quantifier because any tuple that exists in “the universe of” tuples may make F true to make the quantified formula true.
  • 108. Slide 6- 108 Example Query Using Existential Quantifier Retrieve the name and address of all employees who work for the ‘Research’ department. The query can be expressed as : {t.FNAME, t.LNAME, t.ADDRESS | EMPLOYEE(t) and ( d) (DEPARTMENT(d) and d.DNAME=‘Research’ and d.DNUMBER=t.DNO) } The only free tuple variables in a relational calculus expression should be those that appear to the left of the bar ( | ). In above query, t is the only free variable; it is then bound successively to each tuple. If a tuple satisfies the conditions specified in the query, the attributes FNAME, LNAME, and ADDRESS are retrieved for each such tuple. The conditions EMPLOYEE (t) and DEPARTMENT(d) specify the range relations for t and d. The condition d.DNAME = ‘Research’ is a selection condition and corresponds to a SELECT operation in the relational algebra, whereas the condition d.DNUMBER = t.DNO is a JOIN condition.
  • 109. Slide 6- 109 Example Query Using Universal Quantifier Find the names of employees who work on all the projects controlled by department number 5. The query can be: {e.LNAME, e.FNAME | EMPLOYEE(e) and ( ( x)(not(PROJECT(x)) or not(x.DNUM=5) OR ( ( w)(WORKS_ON(w) and w.ESSN=e.SSN and x.PNUMBER=w.PNO))))} Exclude from the universal quantification all tuples that we are not interested in by making the condition true for all such tuples. The first tuples to exclude (by making them evaluate automatically to true) are those that are not in the relation R of interest. In query above, using the expression not(PROJECT(x)) inside the universally quantified formula evaluates to true all tuples x that are not in the PROJECT relation. Then we exclude the tuples we are not interested in from R itself. The expression not(x.DNUM=5) evaluates to true all tuples x that are in the project relation but are not controlled by department 5. Finally, we specify a condition that must hold on all the remaining tuples in R. ( ( w)(WORKS_ON(w) and w.ESSN=e.SSN and x.PNUMBER=w.PNO)
  • 110. Slide 6- 110 Languages Based on Tuple Relational Calculus The language SQL is based on tuple calculus. It uses the basic block structure to express the queries in tuple calculus: SELECT <list of attributes> FROM <list of relations> WHERE <conditions> SELECT clause mentions the attributes being projected, the FROM clause mentions the relations needed in the query, and the WHERE clause mentions the selection as well as the join conditions. SQL syntax is expanded further to accommodate other operations. (See Chapter 8).
  • 111. Slide 6- 111 Languages Based on Tuple Relational Calculus Another language which is based on tuple calculus is QUEL which actually uses the range variables as in tuple calculus. Its syntax includes: RANGE OF <variable name> IS <relation name> Then it uses RETRIEVE <list of attributes from range variables> WHERE <conditions> This language was proposed in the relational DBMS INGRES.
  • 112. Slide 6- 112 The Domain Relational Calculus Another variation of relational calculus called the domain relational calculus, or simply, domain calculus is equivalent to tuple calculus and to relational algebra. The language called QBE (Query-By-Example) that is related to domain calculus was developed almost concurrently to SQL at IBM Research, Yorktown Heights, New York. Domain calculus was thought of as a way to explain what QBE does. Domain calculus differs from tuple calculus in the type of variables used in formulas: Rather than having variables range over tuples, the variables range over single values from domains of attributes. To form a relation of degree n for a query result, we must have n of these domain variables— one for each attribute.
  • 113. Slide 6- 113 The Domain Relational Calculus An expression of the domain calculus is of the form { x1, x2, . . ., xn | COND(x1, x2, . . ., xn, xn+1, xn+2, . . ., xn+m)} where x1, x2, . . ., xn, xn+1, xn+2, . . ., xn+m are domain variables that range over domains (of attributes) and COND is a condition or formula of the domain relational calculus.
  • 114. • Six basic operators – select:  – project:  – union:  – set difference: – – Cartesian product: x – rename: 
  • 115. 03/28/22 Department of Computer Science & Engineering SQL
  • 116. History • IBM Sequel language developed as part of System R project at the IBM San Jose Research Laboratory • Renamed Structured Query Language (SQL) • ANSI and ISO standard SQL: – SQL-86 – SQL-89 – SQL-92 – SQL:1999 (language name became Y2K compliant!) – SQL:2003 • Commercial systems offer most, if not all, SQL-92 features, plus varying feature sets from later standards and special proprietary features. – Not all examples here may work on your particular system.
  • 117. Data Definition Language • The schema for each relation. • The domain of values associated with each attribute. • Integrity constraints • And as we will see later, also other information such as – The set of indices to be maintained for each relations. – Security and authorization information for each relation. – The physical storage structure of each relation on disk. The SQL data-definition language (DDL) allows the specification of information about relations, including:
  • 118. Domain Types in SQL • char(n). Fixed length character string, with user-specified length n. • varchar(n). Variable length character strings, with user-specified maximum length n. • int. Integer (a finite subset of the integers that is machine-dependent). • smallint. Small integer (a machine-dependent subset of the integer domain type). • numeric(p,d). Fixed point number, with user-specified precision of p digits, with d digits to the right of decimal point. (ex., numeric(3,1), allows 44.5 to be stores exactly, but not 444.5 or 0.32) • real, double precision. Floating point and double-precision floating point numbers, with machine-dependent precision. • float(n). Floating point number, with user-specified precision of at least n digits. • More are covered in Chapter 4.
  • 119. Create Table Construct • An SQL relation is defined using the create table command: create table r (A1 D1, A2 D2, ..., An Dn, (integrity-constraint1), ..., (integrity-constraintk)) – r is the name of the relation – each Ai is an attribute name in the schema of relation r – Di is the data type of values in the domain of attribute Ai • Example: create table instructor ( ID char(5), name varchar(20), dept_name varchar(20), salary numeric(8,2))
  • 120. Integrity Constraints in Create Table • not null • primary key (A1, ..., An ) • foreign key (Am, ..., An ) references r Example: create table instructor ( ID char(5), name varchar(20) not null, dept_name varchar(20), salary numeric(8,2), primary key (ID), foreign key (dept_name) references department); primary key declaration on an attribute automatically ensures not null
  • 121. And a Few More Relation Definitions • create table student ( ID varchar(5), name varchar(20) not null, dept_name varchar(20), tot_cred numeric(3,0), primary key (ID), foreign key (dept_name) references department); • create table takes ( ID varchar(5), course_id varchar(8), sec_id varchar(8), semester varchar(6), year numeric(4,0), grade varchar(2), primary key (ID, course_id, sec_id, semester, year) , foreign key (ID) references student, foreign key (course_id, sec_id, semester, year) references section); – Note: sec_id can be dropped from primary key above, to ensure a student cannot be registered for two sections of the same course in the same semester
  • 122. And more still • create table course ( course_id varchar(8), title varchar(50), dept_name varchar(20), credits numeric(2,0), primary key (course_id), foreign key (dept_name) references department);
  • 123. Updates to tables • Insert – insert into instructor values (‘10211’, ’Smith’, ’Biology’, 66000); • Delete – Remove all tuples from the student relation • delete from student • Drop Table – drop table r • Alter – alter table r add A D • where A is the name of the attribute to be added to relation r and D is the domain of A. • All exiting tuples in the relation are assigned null as the value for the new attribute. – alter table r drop A • where A is the name of an attribute of relation r • Dropping of attributes not supported by many databases.
  • 124. Basic Query Structure • A typical SQL query has the form: select A1, A2, ..., An from r1, r2, ..., rm where P – Ai represents an attribute – Ri represents a relation – P is a predicate. • The result of an SQL query is a relation.
  • 125. The select Clause • The select clause lists the attributes desired in the result of a query – corresponds to the projection operation of the relational algebra • Example: find the names of all instructors: select name from instructor • NOTE: SQL names are case insensitive (i.e., you may use upper- or lower-case letters.) – E.g., Name ≡ NAME ≡ name – Some people use upper case wherever we use bold font.
  • 126. The select Clause (Cont.) • SQL allows duplicates in relations as well as in query results. • To force the elimination of duplicates, insert the keyword distinct after select. • Find the department names of all instructors, and remove duplicates select distinct dept_name from instructor • The keyword all specifies that duplicates should not be removed.
  • 127. The select Clause (Cont.) • An asterisk in the select clause denotes “all attributes” select * from instructor • An attribute can be a literal with no from clause select ‘437’ – Results is a table with one column and a single row with value “437” – Can give the column a name using: select ‘437’ as FOO
  • 128. The select Clause (Cont.) • The select clause can contain arithmetic expressions involving the operation, +, –, , and /, and operating on constants or attributes of tuples. – The query: select ID, name, salary/12 from instructor would return a relation that is the same as the instructor relation, except that the value of the attribute salary is divided by 12. – Can rename “salary/12” using the as clause: select ID, name, salary/12 as monthly_salary
  • 129. The where Clause • The where clause specifies conditions that the result must satisfy – Corresponds to the selection predicate of the relational algebra. • To find all instructors in Comp. Sci. dept select name from instructor where dept_name = ‘Comp. Sci.' • Comparison results can be combined using the logical connectives and, or, and not – To find all instructors in Comp. Sci. dept with salary > 80000 select name from instructor where dept_name = ‘Comp. Sci.' and salary > 80000 • Comparisons can be applied to results of arithmetic expressions.
  • 130. The from Clause • The from clause lists the relations involved in the query – Corresponds to the Cartesian product operation of the relational algebra. • Find the Cartesian product instructor X teaches select  from instructor, teaches – generates every possible instructor – teaches pair, with all attributes from both relations. – For common attributes (e.g., ID), the attributes in the resulting table are renamed using the relation name (e.g., instructor.ID) • Cartesian product not very useful directly, but useful combined with where-clause condition (selection operation in relational algebra).
  • 132. Examples • Find the names of all instructors who have taught some course and the course_id – select name, course_id from instructor , teaches where instructor.ID = teaches.ID • Find the names of all instructors in the Art department who have taught some course and the course_id – select name, course_id from instructor , teaches where instructor.ID = teaches.ID and instructor. dept_name = ‘Art’
  • 133. The Rename Operation • The SQL allows renaming relations and attributes using the as clause: old-name as new-name • Find the names of all instructors who have a higher salary than some instructor in ‘Comp. Sci’. – select distinct T.name from instructor as T, instructor as S where T.salary > S.salary and S.dept_name = ‘Comp. Sci.’
  • 134. Self Join Example n Relation emp-super n Find the supervisor of “Bob” n Find the supervisor of the supervisor of “Bob” n Find ALL the supervisors (direct and indirect) of “Bob person supervisor Bob Alice Mary Susan Alice David David Mary
  • 135. String Operations • SQL includes a string-matching operator for comparisons on character strings. The operator like uses patterns that are described using two special characters: – percent ( % ). The % character matches any substring. – underscore ( _ ). The _ character matches any character. • Find the names of all instructors whose name includes the substring “dar”. select name from instructor where name like '%dar%' • Match the string “100%” like ‘100 %' escape '' in that above we use backslash () as the escape character.
  • 136. String Operations (Cont.) • Patterns are case sensitive. • Pattern matching examples: – ‘Intro%’ matches any string beginning with “Intro”. – ‘%Comp%’ matches any string containing “Comp” as a substring. – ‘_ _ _’ matches any string of exactly three characters. – ‘_ _ _ %’ matches any string of at least three characters. • SQL supports a variety of string operations such as – concatenation (using “||”) – converting from upper to lower case (and vice versa) – finding string length, extracting substrings, etc.
  • 137. Ordering the Display of Tuples • List in alphabetic order the names of all instructors select distinct name from instructor order by name • We may specify desc for descending order or asc for ascending order, for each attribute; ascending order is the default. – Example: order by name desc • Can sort on multiple attributes – Example: order by dept_name, name
  • 138. Where Clause Predicates • SQL includes a between comparison operator • Example: Find the names of all instructors with salary between $90,000 and $100,000 (that is,  $90,000 and  $100,000) – select name from instructor where salary between 90000 and 100000 • Tuple comparison – select name, course_id from instructor, teaches where (instructor.ID, dept_name) = (teaches.ID, ’Biology’);
  • 139. Duplicates • In relations with duplicates, SQL can define how many copies of tuples appear in the result. • Multiset versions of some of the relational algebra operators – given multiset relations r1 and r2: 1.  (r1): If there are c1 copies of tuple t1 in r1, and t1 satisfies selections ,, then there are c1 copies of t1 in  (r1). 2. A (r ): For each copy of tuple t1 in r1, there is a copy of tuple A (t1) in A (r1) where A (t1) denotes the projection of the single tuple t1. 3. r1 x r2: If there are c1 copies of tuple t1 in r1 and c2 copies of tuple t2 in r2, there are c1 x c2 copies of the tuple t1. t2 in r1 x r2
  • 140. Duplicates (Cont.) • Example: Suppose multiset relations r1 (A, B) and r2 (C) are as follows: r1 = {(1, a) (2,a)} r2 = {(2), (3), (3)} • Then B(r1) would be {(a), (a)}, while B(r1) x r2 would be {(a,2), (a,2), (a,3), (a,3), (a,3), (a,3)} • SQL duplicate semantics: select A1,, A2, ..., An from r1, r2, ..., rm where P is equivalent to the multiset version of the expression: )) ( ( 2 1 , , , 2 1 m P A A A r r r n       
  • 141. Set Operations • Find courses that ran in Fall 2009 or in Spring 2010 n Find courses that ran in Fall 2009 but not in Spring 2010 (select course_id from section where sem = ‘Fall’ and year = 2009) union (select course_id from section where sem = ‘Spring’ and year = 2010) n Find courses that ran in Fall 2009 and in Spring 2010 (select course_id from section where sem = ‘Fall’ and year = 2009) intersect (select course_id from section where sem = ‘Spring’ and year = 2010) (select course_id from section where sem = ‘Fall’ and year = 2009) except (select course_id from section where sem = ‘Spring’ and year = 2010)
  • 142. Set Operations (Cont.) • Find the salaries of all instructors that are less than the largest salary. – select distinct T.salary from instructor as T, instructor as S where T.salary < S.salary • Find all the salaries of all instructors – select distinct salary from instructor • Find the largest salary of all instructors. – (select “second query” ) except (select “first query”)
  • 143. Set Operations (Cont.) • Set operations union, intersect, and except – Each of the above operations automatically eliminates duplicates nTo retain all duplicates use the corresponding multiset versions union all, intersect all and except all. nSuppose a tuple occurs m times in r and n times in s, then, it occurs: – m + n times in r union all s – min(m,n) times in r intersect all s
  • 144. Null Values • It is possible for tuples to have a null value, denoted by null, for some of their attributes • null signifies an unknown value or that a value does not exist. • The result of any arithmetic expression involving null is null – Example: 5 + null returns null • The predicate is null can be used to check for null values. – Example: Find all instructors whose salary is null. select name from instructor where salary is null
  • 145. Null Values and Three Valued Logic • Three values – true, false, unknown • Any comparison with null returns unknown – Example: 5 < null or null <> null or null = null • Three-valued logic using the value unknown: – OR: (unknown or true) = true, (unknown or false) = unknown (unknown or unknown) = unknown – AND: (true and unknown) = unknown, (false and unknown) = false, (unknown and unknown) = unknown – NOT: (not unknown) = unknown – “P is unknown” evaluates to true if predicate P evaluates to unknown • Result of where clause predicate is treated as false if it evaluates to unknown
  • 146. Aggregate Functions • These functions operate on the multiset of values of a column of a relation, and return a value avg: average value min: minimum value max: maximum value sum: sum of values count: number of values
  • 147. Aggregate Functions (Cont.) • Find the average salary of instructors in the Computer Science department – select avg (salary) from instructor where dept_name= ’Comp. Sci.’; • Find the total number of instructors who teach a course in the Spring 2010 semester – select count (distinct ID) from teaches where semester = ’Spring’ and year = 2010; • Find the number of tuples in the course relation – select count (*) from course;
  • 148. Aggregate Functions – Group By • Find the average salary of instructors in each department – select dept_name, avg (salary) as avg_salary from instructor group by dept_name; avg_salary
  • 149. Aggregation (Cont.) • Attributes in select clause outside of aggregate functions must appear in group by list – /* erroneous query */ select dept_name, ID, avg (salary) from instructor group by dept_name;
  • 150. Aggregate Functions – Having Clause • Find the names and average salaries of all departments whose average salary is greater than 42000 Note: predicates in the having clause are applied after the formation of groups whereas predicates in the where clause are applied before forming groups select dept_name, avg (salary) from instructor group by dept_name having avg (salary) > 42000;
  • 151. Null Values and Aggregates • Total all salaries select sum (salary ) from instructor – Above statement ignores null amounts – Result is null if there is no non-null amount • All aggregate operations except count(*) ignore tuples with null values on the aggregated attributes • What if collection has only null values? – count returns 0 – all other aggregates return null
  • 152. Nested Subqueries • SQL provides a mechanism for the nesting of subqueries. A subquery is a select-from-where expression that is nested within another query. • The nesting can be done in the following SQL query select A1, A2, ..., An from r1, r2, ..., rm where P as follows: – Ai can be replaced be a subquery that generates a single value. – ri can be replaced by any valid subquery – P can be replaced with an expression of the form: B <operation> (subquery) Where B is an attribute and <operation> to be defined later.
  • 153. Subqueries in the Where Clause
  • 154. Subqueries in the Where Clause • A common use of subqueries is to perform tests: – For set membership – For set comparisons – For set cardinality.
  • 155. Set Membership • Find courses offered in Fall 2009 and in Spring 2010 n Find courses offered in Fall 2009 but not in Spring 2010 select distinct course_id from section where semester = ’Fall’ and year= 2009 and course_id in (select course_id from section where semester = ’Spring’ and year= 2010); select distinct course_id from section where semester = ’Fall’ and year= 2009 and course_id not in (select course_id from section where semester = ’Spring’ and year= 2010);
  • 156. Set Membership (Cont.) • Find the total number of (distinct) students who have taken course sections taught by the instructor with ID 10101 n Note: Above query can be written in a much simpler manner. The formulation above is simply to illustrate SQL features. select count (distinct ID) from takes where (course_id, sec_id, semester, year) in (select course_id, sec_id, semester, year from teaches where teaches.ID= 10101);
  • 157. Set Comparison – “some” Clause • Find names of instructors with salary greater than that of some (at least one) instructor in the Biology department. n Same query using > some clause select name from instructor where salary > some (select salary from instructor where dept name = ’Biology’); select distinct T.name from instructor as T, instructor as S where T.salary > S.salary and S.dept name = ’Biology’;
  • 158. Definition of “some” Clause • F <comp> some r   t  r such that (F <comp> t ) Where <comp> can be:      0 5 6 (5 < some ) = true 0 5 0 ) = false 5 0 5 (5  some ) = true (since 0  5) (read: 5 < some tuple in the relation) (5 < some ) = true (5 = some (= some)  in However, ( some)  not in
  • 159. Set Comparison – “all” Clause • Find the names of all instructors whose salary is greater than the salary of all instructors in the Biology department. select name from instructor where salary > all (select salary from instructor where dept name = ’Biology’);
  • 160. Definition of “all” Clause • F <comp> all r   t  r (F <comp> t) 0 5 6 (5 < all ) = false 6 10 4 ) = true 5 4 6 (5  all ) = true (since 5  4 and 5  6) (5 < all ) = false (5 = all ( all)  not in However, (= all)  in
  • 161. Test for Empty Relations • The exists construct returns the value true if the argument subquery is nonempty. • exists r  r  Ø • not exists r  r = Ø
  • 162. Use of “exists” Clause • Yet another way of specifying the query “Find all courses taught in both the Fall 2009 semester and in the Spring 2010 semester” select course_id from section as S where semester = ’Fall’ and year = 2009 and exists (select * from section as T where semester = ’Spring’ and year= 2010 and S.course_id = T.course_id); • Correlation name – variable S in the outer query • Correlated subquery – the inner query
  • 163. Use of “not exists” Clause • Find all students who have taken all courses offered in the Biology department. select distinct S.ID, S.name from student as S where not exists ( (select course_id from course where dept_name = ’Biology’) except (select T.course_id from takes as T where S.ID = T.ID)); • First nested query lists all courses offered in Biology • Second nested query lists all courses a particular student took n Note that X – Y = Ø  X  Y n Note: Cannot write this query using = all and its variants
  • 164. Test for Absence of Duplicate Tuples • The unique construct tests whether a subquery has any duplicate tuples in its result. • The unique construct evaluates to “true” if a given subquery contains no duplicates . • Find all courses that were offered at most once in 2009 select T.course_id from course as T where unique (select R.course_id from section as R where T.course_id= R.course_id and R.year = 2009);
  • 165. Subqueries in the From Clause
  • 166. Subqueries in the From Clause • SQL allows a subquery expression to be used in the from clause • Find the average instructors’ salaries of those departments where the average salary is greater than $42,000.” select dept_name, avg_salary from (select dept_name, avg (salary) as avg_salary from instructor group by dept_name) where avg_salary > 42000; • Note that we do not need to use the having clause • Another way to write above query select dept_name, avg_salary from (select dept_name, avg (salary) from instructor group by dept_name) as dept_avg (dept_name, avg_salary) where avg_salary > 42000;
  • 167. With Clause • The with clause provides a way of defining a temporary relation whose definition is available only to the query in which the with clause occurs. • Find all departments with the maximum budget with max_budget (value) as (select max(budget) from department) select department.name from department, max_budget where department.budget = max_budget.value;
  • 168. Complex Queries using With Clause • Find all departments where the total salary is greater than the average of the total salary at all departments with dept _total (dept_name, value) as (select dept_name, sum(salary) from instructor 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;
  • 170. Scalar Subquery • Scalar subquery is one which is used where a single value is expected • List all departments along with the number of instructors in each department select dept_name, (select count(*) from instructor where department.dept_name = instructor.dept_name) as num_instructors from department; • Runtime error if subquery returns more than one result tuple
  • 171. Modification of the Database • Deletion of tuples from a given relation. • Insertion of new tuples into a given relation • Updating of values in some tuples in a given relation
  • 172. Deletion • Delete all instructors delete from instructor • Delete all instructors from the Finance department delete from instructor where dept_name= ’Finance’; • Delete all tuples in the instructor relation for those instructors associated with a department located in the Watson building. delete from instructor where dept name in (select dept name from department where building = ’Watson’);
  • 173. Deletion (Cont.) • Delete all instructors whose salary is less than the average salary of instructors delete from instructor where salary < (select avg (salary) from instructor);  Problem: as we delete tuples from deposit, the average salary changes  Solution used in SQL: 1. First, compute avg (salary) and find all tuples to delete 2. Next, delete all tuples found above (without recomputing avg or retesting the tuples)
  • 174. Insertion • Add a new tuple to course insert into course values (’CS-437’, ’Database Systems’, ’Comp. Sci.’, 4); • or equivalently insert into course (course_id, title, dept_name, credits) values (’CS-437’, ’Database Systems’, ’Comp. Sci.’, 4);
  • 175. Insertion (Cont.) • Add all instructors to the student relation with tot_creds set to 0 insert into student select ID, name, dept_name, 0 from instructor • The select from where statement is evaluated fully before any of its results are inserted into the relation. Otherwise queries like insert into table1 select * from table1 would cause problem
  • 176. Updates • Increase salaries of instructors whose salary is over $100,000 by 3%, and all others by a 5% – Write two update statements: update instructor set salary = salary * 1.03 where salary > 100000; update instructor set salary = salary * 1.05 where salary <= 100000; – The order is important – Can be done better using the case statement (next slide)
  • 177. Case Statement for Conditional Updates • Same query as before but with case statement update instructor set salary = case when salary <= 100000 then salary * 1.05 else salary * 1.03 end
  • 178. Updates with Scalar Subqueries • Recompute and update tot_creds value for all students update student S set tot_cred = (select sum(credits) from takes, course where takes.course_id = course.course_id and S.ID= takes.ID.and takes.grade <> ’F’ and takes.grade is not null); • Sets tot_creds to null for students who have not taken any course • Instead of sum(credits), use: case when sum(credits) is not null then sum(credits) else 0 end
  • 179. Department of Computer Science & Engineering A view is nothing more than a SQL statement that is stored in the database with an associated name. A view is actually a composition of a table in the form of a predefined SQL query. A view can contain all rows of a table or select rows from a table. A view can be created from one or many tables which depends on the written SQL query to create a view. Views, which are a type of virtual tables allow users to do the following − Structure data in a way that users or classes of users find natural or intuitive. Restrict access to the data in such a way that a user can see and (sometimes) modify exactly what they need and no more. Summarize data from various tables which can be used to generate reports. Views
  • 180. Department of Computer Science & Engineering Database views are created using the CREATE VIEW statement. Views can be created from a single table, multiple tables or another view. To create a view, a user must have the appropriate system privilege according to the specific implementation. The basic CREATE VIEW syntax is as follows − CREATE VIEW view_name AS SELECT column1, column2..... FROM table_name WHERE [condition]; Consider the CUSTOMERS table having the following records − ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | Following is an example to create a view from the CUSTOMERS table. This view would be used to have customer name and age from the CUSTOMERS table. SQL > CREATE VIEW CUSTOMERS_VIEW AS SELECT name, age FROM CUSTOMERS; Now, you can query CUSTOMERS_VIEW in a similar way as you query an actual table. Following is an example for the same. SQL > SELECT * FROM CUSTOMERS_VIEW;