unit ii introduction to the relational model integrity constraint over relations enforcing integrity...

51
UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data base Design Introduction to Views Destroying /altering Tables and Views. Relational Algebra Selection and projection set operations renaming – Joins – Division Examples of Algebra overviews Relational calculus Tuple relational Calculus Domain relational calculus Expressive Power of Algebra and calculus.

Upload: peregrine-theodore-paul

Post on 11-Jan-2016

236 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

UNIT II

Introduction to the Relational Model

Integrity Constraint Over relations

Enforcing Integrity constraints

Querying relational data

Logical data base Design

Introduction to Views

Destroying /altering Tables and Views.

Relational Algebra

Selection and projection set operations

renaming – Joins – Division

Examples of Algebra overviews

Relational calculus

Tuple relational Calculus

Domain relational calculus

Expressive Power of Algebra and calculus.

Page 2: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

2

Relational Model

•Relations:The main construct for representing the data in the

relational model is a relation.•A relation consists of a relation schema and relation instance.

Relation Schema : specifies name of relation, plus name of each field( or column. or attribute, or property) and the domain of each field.A domain is referred to in a relation schema by the domain name, and has a set of associated values.E.g. Students(sid: string, name: string, login: string, age: integer, gpa: real) #fields = degree / arity

An Instance of a relation is a set tuples, also called records or rows, in which each tuple has the same number of fields as the relation schema.Cardinality=#rows.

Page 3: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

3

sid name login age gpa

53666 Jones jones @cs 18 3.4

53688 Smith smith@eecs 18 3.2

53650 Smith smith @math 19 3.8

• Cardinality = 3, arity = 5 , all rows distinct

A relational database is a collection of relations with distinct relation names. The relational database schema is the collection of schemas for the relations in the databaseAn instance of a relational database is a collection of relation instances, one per relation schema in the database schema

Creating and modifying relations using SQL

1. Create2. Insert3. Update4. Delete

Page 4: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

4

Integrity Constraints• An Integrity Constraint (IC) is a condition that is specified on a

database schema, and restricts the data that can be stored in an instance of the database.

• If a database instance satisfies all the integrity constraints specified on the database, it is a legal instance.

• A DBMS enforces integrity constraints, in that it permits only legal instances to be stored in a database.

• Integrity constraints are specified enforced at different times.

1) When a DBA or end user defines a database, he or she species the ICs that must be hold on any instance of this database.

2) When a database application is run, the DBMS checks for violations.

• 1)Domain Constraints:The values that appears in a column must be drawn from

the domain associated with that column. Domain of field is essentially the type of that field.

Page 5: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

5

2)Key Constraints:

A key constraint is a statement that a certain minimal

subset of the fields of a relation is a unique identifier for a tuple.

A set of fields that uniquely identifies a tuple according to a key

constraint is called a candidate key for the relation.

Key do not permit duplicate values.

No subset of key is a unique identifier for a tuple.

Ex: The set of fields {sid,name} is not a key for stuednts.Ex: The set of fields {sid,name} is not a key for stuednts.

But the set {sid,name} is a super key for students relation.But the set {sid,name} is a super key for students relation.

A relation may have several keys.A relation may have several keys.

Out of the available Out of the available candidate keys candidate keys a database designer can a database designer can

identify a identify a primary keyprimary key..

Name StudentNo Sex Degree

Page 6: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

3)Foreign Key Constraints:3)Foreign Key Constraints:

..

• Key and Entity Integrity constraints are specified on individual relations

• Referential Integrity constraints are specified between two relations

EMP [ Eno, Name, Salary, SuperEno, DeptNo ]

DEPT [ Dnumber, Dname, Dlocation ]

• A set of attributes FK in relation schema R1 is a foreign key if– the attributes of FK have the same domain as the the primary key attributes PK of another schema R2– t1[FK] = t2[PK] or t1[FK] is null

• FK is said to “reference” PK

Page 7: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

Example Foreign Key

• Every employee is assigned to one department

– DeptNo is a foreign key of EMP referencing DEPT• Every Department has a Manager. The manager is also an

employee

– Manager is a foreign key of DEPT referencing EMP• Every Employee has a supervisor who is also an employee

– SuperEno is a foreign key of EMP referencing EMP

DEPT[Dnumber, Dname, Dlocation, Manager]

EMP[Eno, Name, Salary, SuperEno, DeptNo]

Page 8: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

4)General Constraints4)General Constraints

• General class of constraints that cannot be enforced by the

preceding constraints

• Semantic Constraints

– “The salary of an employee should not exceed

the employee’s supervisor’s salary”

– “The maximum number of hours that an

employee can work on a project is 56”

• Transition Constraints

– “The salary of an employee can only increase”

• Often implemented in a constraint specification language (SQL3)

using triggers and assertions

Page 9: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

Enforcing Integrity Constraints

• Each DBMS should have means to resolve invlaid entries such as:

– What happens if an entry that duplicates a key entry is entered?– What should be done if an entry of a foreign key is deleted?

• A foreign key is a key where at least one field depends on a field from a different table.

– What happens when an invalid entry is entered?

• Associated with each attribute is a set of values, called a domain,

that can be assigned to the entry of a tuple corresponding to the

attribute.• A relation schema is a set of attributes.• Example EMP = { Name, SSN, DeptName, Salary,

Birthdate }• Convention EMP(Name,SSN,DeptName,Salary,Birthdate)

Page 10: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

10

Querying Relational Data

• Query is a question about the data • The answer consists of a new relation containing the result• SQL – the most popular

query language

SELECT *FROM Students SWHERE S.GPA > 3.2

SELECT S.Login, S.GPAFROM Students SWHERE S.GPA > 3.2

Page 11: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

Logical Database DesignLogical Database Design(ER TO RELATIONAL)(ER TO RELATIONAL)

• Entity sets to tables:

CREATE TABLE Employees (ssn CHAR(11), name CHAR(20), lot INTEGER, PRIMARY KEY (ssn))Employees

ssnname

lot

– Each entity is defined as a table. Use the entity name as the

table name. Make the entity identifier as the primary key for

the table. Examine domain constraints for each attribute.

– Include the primary key of one of the tables in the second one.

This becomes the foreign key and enables linkage between the

two tables.

Page 12: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

Relationship Sets to Tables

• In translating a relationship set to a relation, attributes of the

relation must include:

– Keys for each participating entity set (as foreign keys).

• This set of attributes forms a superkey for the relation.

– All descriptive attributes.

CREATE TABLE Works_In(

ssn CHAR(1),

did INTEGER,

since DATE,

PRIMARY KEY (ssn, did),

FOREIGN KEY (ssn) REFERENCES Employees,

FOREIGN KEY (did) REFERENCES Departments)

Page 13: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

• Translation of relationship that relates

entities from the same entity set

CREATE TABLE Reports_To (

supervisor_ssn CHAR(11)

subordinate_ssn CHAR(11)

PRIMARY KEY (supervisor_ssn, subordinate_ssn),

FOREIGN KEY (supervisor_ssn, REFERENCES Employees(ssn),

FOREIGN KEY (subordinate_ssn, REFERENCES Employee(ssn))

• We need to explicityly name the referenced field of Employees because the

field name differs from the name(s) of the referring field(s)

Reports_To

lot

name

Employees

subor-dinate

super-visor

ssn

Page 14: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

Translating ER Diagrams with Key Constraints

• Map relationship to a

table:

– Note that did is the

key now!

– Separate tables for

Employees and

Departments.

• Since each department

has a unique manager,

we could instead

combine Manages and

Departments.

CREATE TABLE Manages( ssn CHAR(11), did INTEGER, since DATE, PRIMARY KEY (did), FOREIGN KEY (ssn) REFERENCES Employees, FOREIGN KEY (did) REFERENCES Departments)

CREATE TABLE Dept_Mgr( did INTEGER, dname CHAR(20), budget REAL, ssn CHAR(11), since DATE, PRIMARY KEY (did), FOREIGN KEY (ssn) REFERENCES Employees)

Page 15: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

Translating Weak Entity Sets

• Weak entity set and identifying relationship set are translated into

a single table.

– When the owner entity is deleted, all owned weak entities must

also be deleted.

CREATE TABLE Dep_Policy ( pname CHAR(20), age INTEGER, cost REAL, ssn CHAR(11) NOT NULL, PRIMARY KEY (pname, ssn), FOREIGN KEY (ssn) REFERENCES Employees, ON DELETE CASCADE)

Page 16: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

• A view is a pseudo or virtual table that is used to retrieve data that exists in the underlying database tables

• The view query must be executed each time the view is used• A view can be used to simplify queries or to restrict access to

sensitive data• A view is created with the CREATE VIEW command• A view cannot be modified; to change a view, it must be dropped

and then re-created, or the CREATE OR REPLACE VIEW command must be used

• Any DML operation can be performed on a simple query if it does not violate a constraint

• A view that contains expressions or functions, or that joins multiple tables, is considered a complex view

• A complex view can be used to update only one table; the table must be a key-preserved table

• Data cannot be added to a view column that contains an expression• DML operations are not permitted on non key-preserved tables

Views

Page 17: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

17

Types of Views

Page 18: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

Oracle 10g: SQL 18

Creating a View

• You use the CREATE VIEW keywords to create a view• Use OR REPLACE if the view already exists• Use FORCE if the underlying table does not exist at the

time of creation• Provide new column names if necessary

Page 19: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

• WITH CHECK OPTION constraint – if used, prevents data changes that will make the data subsequently inaccessible to the view

• WITH READ ONLY – prevents DML operations

Page 20: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

Oracle 10g: SQL 20

Creating a Simple View

• Only references one table – no group functions, GROUP BY clause, or expressions

Page 21: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

Oracle 10g: SQL 21

DML Operations on a Simple View

• Any DML operations are allowed through simple views unless created with WITH READ ONLY option

• DML operations that violate constraints on the underlying table are not allowed

Page 22: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

Oracle 10g: SQL 22

Creating a Complex View

• A complex view may contain data from multiple tables or data created with the GROUP BY clause, functions, or expressions

• Type of DML operations allowed depends on various factors

Page 23: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

Oracle 10g: SQL 23

DML Operations on a Complex View with an Arithmetic Expression

• Values cannot be inserted into columns that are based on arithmetic expressions

Page 24: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

Oracle 10g: SQL 24

DML Operations on a Complex View Containing Data from Multiple Tables

• DML operations can not be performed on non key-preserved tables, but they are permitted on key-preserved tables

Page 25: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

Oracle 10g: SQL 25

DML Operations on a Complex View Containing Data from Multiple Tables

(continued)

Page 26: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

Oracle 10g: SQL 26

DML Operations on a Complex View Containing Functions or Grouped Data

• DML operations are not permitted if the view includes a group function or a GROUP BY clause

Page 27: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

Oracle 10g: SQL 27

DML Operations on a Complex View Containing DISTINCT or ROWNUM

• DML operations on a view that contains the DISTINCT keyword or ROWNUM are not permitted

Page 28: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

Oracle 10g: SQL 28

Dropping a View

• Use DROP VIEW command

Page 29: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

Oracle 10g: SQL 29

Creating an Inline View

• An inline view is a temporary table created by using a subquery in the FROM clause

• It can only be referenced while the command is being executed

• Most common usage – “TOP-N” analysis

Page 30: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

30

Formal Relational Query Languages

Two mathematical Query Languages form the basis for “real” languages (e.g. SQL), and for implementation:

Relational Algebra: More operational, very useful for representing execution plans.

Relational Calculus: Lets users describe what they want, rather than how to compute it. (Non-procedural, declarative.)

Understanding Algebra & Calculus is key to understanding SQL query processing!

• Relational algebra and relational calculus are two query languages associated with the relational model.

• Queries in Relational Algebra are composed using a collection of operators, and each query describes the step-by-step procedure for computing the desired answer.

• In relational calculus the query describes the desired answer without specifying how the answer is to be computed. So this non-procedural style of querying is called declarative.

Relational Algebra & Relational Calculus

Page 31: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

31

Preliminaries• A query is applied to relation instances, and the result of a query is

also a relation instance.– Schemas of input relations for a query are fixed (but query will run

over any legal instance)– The schema for the result of a given query is also fixed. It is

determined by the definitions of the query language constructs.• Positional vs. named-field notation:

– Positional notation easier for formal definitions, named-field notation more readable.

– Both used in SQL• Though positional notation is not encouraged

Relational algebra

• RA is one of the two formal query languages associated with relational model.

• Queries in RA are composed of operators.• A fundamental property is that every operator in algebra accepts (one or

two) relation instances and return a relation instance as result.• A relational algebra expression is recursively defined to be a relation.• Each relational query describes a step-by-step procedure for computing the

desired answer, based on the order in which the operators are applied in the query.

Page 32: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

32

Relational Algebra: 5 Basic Operations

• Selection ( s ) Selects a subset of rows from relation (horizontal).• Projection (p) Retains only wanted columns from relation(vertical).• Cross-product ( ) Allows us to combine two relations.• Set-difference ( — ) Tuples in r1, but not in r2.• Union ( ) Tuples in r1 or in r2.

Projection ()

- Retains only attributes that are - Retains only attributes that are in the “in the “projection list”projection list”.. - Schema- Schema of result: of result:

= exactly the fields in = exactly the fields in the projection list, with the the projection list, with the same names that they had in same names that they had in the input relation.the input relation.

- Projection operator has to - Projection operator has to eliminate duplicateseliminate duplicates

age S( )2

sname rating

S,

( )2

Selection ()

- Selects rows that satisfy - Selects rows that satisfy selection conditionselection condition..- Result is a relation.- Result is a relation.

- Schema- Schema of result is same of result is same as that of the input relation.as that of the input relation.

rating

S8

2( )

Page 33: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

33

Union and Set-Difference• Both of these operations take two input relations, which

must be union-compatible:– Same number of fields.– `Corresponding’ fields have the same type.

sid sname rating age

22 dustin 7 45.031 lubber 8 55.558 rusty 10 35.044 guppy 5 35.028 yuppy 9 35.0

sid sname rating age

22 dustin 7 45.0

31 lubber 8 55.558 rusty 10 35.0

sid sname rating age28 yuppy 9 35.031 lubber 8 55.544 guppy 5 35.058 rusty 10 35.0

S1

S2

S S1 2

Page 34: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

34

Set Difference

sid sname rating age

22 dustin 7 45.0

31 lubber 8 55.558 rusty 10 35.0

sid sname rating age28 yuppy 9 35.031 lubber 8 55.544 guppy 5 35.058 rusty 10 35.0

S1 S2

sid sname rating age

22 dustin 7 45.0

S2 – S1

sid sname rating age28 yuppy 9 35.044 guppy 5 35.0S S1 2

Cross-Product• S1 R1: Each row of S1 paired with each row of R1.• Q: How many rows in the result?• Result schema has one field per field of S1 and R1, with field

names `inherited’ if possible.– May have a naming conflict: Both S1 and R1 have a field with

the same name.– In this case, can use the renaming operator:

Page 35: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

35

Cross Product Example

(sid) sname rating age (sid) bid day

22 dustin 7 45.0 22 101 10/10/96

22 dustin 7 45.0 58 103 11/12/96

31 lubber 8 55.5 22 101 10/10/96

31 lubber 8 55.5 58 103 11/12/96

58 rusty 10 35.0 22 101 10/10/96

58 rusty 10 35.0 58 103 11/12/96

sid sname rating age

22 dustin 7 45.0

31 lubber 8 55.558 rusty 10 35.0

sid bid day

22 101 10/10/9658 103 11/12/96

R1S1

R1 X S1

Page 36: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

36

Compound Operator: Intersection• In addition to the 5 basic operators, there are several additional “Compound

Operators”– These add no computational power to the language, but are useful shorthands.– Can be expressed solely with the basic ops.

• Intersection takes two input relations, which must be union-compatible.• Q: How to express it using basic operators?

R S = R (R S)sid sname rating age

22 dustin 7 45.0

31 lubber 8 55.558 rusty 10 35.0

sid sname rating age28 yuppy 9 35.031 lubber 8 55.544 guppy 5 35.058 rusty 10 35.0

S1

S2

sid sname rating age31 lubber 8 55.558 rusty 10 35.0

S1S2

Page 37: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

37

Compound Operator: Join• Joins are compound operators involving cross product, selection, and

(sometimes) projection.• Most common type of join is a “natural join” (often just called “join”).

R S conceptually is:– Compute R S– Select rows where attributes that appear in both relations have

equal values– Project all unique attributes and one copy of each of the common

ones.

sid sname rating age

22 dustin 7 45.0

31 lubber 8 55.558 rusty 10 35.0

sid bid day

22 101 10/10/9658 103 11/12/96

R1S1

S1 R1 sid sname rating age bid day

22 dustin 7 45.0 101 10/10/9658 rusty 10 35.0 103 11/12/96

Page 38: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

38

Other Types of Joins• Condition Join (or “theta-join”):

• Result schema same as that of cross-product.• May have fewer tuples than cross-product.

R c S c R S ( )

(sid) sname rating age (sid) bid day

22 dustin 7 45.0 58 103 11/12/9631 lubber 8 55.5 58 103 11/12/96

Find names of sailors who’ve reserved boat #103

sname bidserves Sailors(( Re ) )

103

sname bidserves Sailors( (Re ))

103

Find names of sailors who’ve reserved a red boat

sname color redBoats serves Sailors((

' ') Re )

Page 39: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

39

Compound Operator: Division• Useful for expressing “for all” queries like:

Find sids of sailors who have reserved all boats.• For A/B, attributes of B must be subset of attrs of A.

– May need to “project” to make this happen.• E.g., let A have 2 fields, x and y; B have only field y:

A/B contains all tuples (x) such that for every y tuple in B, there is an xy tuple in A.

A B x y B( x,y A)

For For A(x,y)/B(y)A(x,y)/B(y), compute all , compute all xx values that are not `disqualified’ by values that are not `disqualified’ by some some yy value in value in BB..

xx value is value is disqualifieddisqualified if by attaching if by attaching y y value from value from BB, we obtain an , we obtain an xyxy tuple that is not in tuple that is not in AA..

Expressing A/B Using Basic Operators

Disqualified x values: x x A B A(( ( ) ) )

A/B: x A( ) Disqualified x values

Page 40: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

40

Examples of Division A/B

sno pnos1 p1s1 p2s1 p3s1 p4s2 p1s2 p2s3 p2s4 p2s4 p4

pnop2

pnop2p4

pnop1p2p4

snos1s2s3s4

snos1s4

snos1

A

B1B2

B3

A/B1 A/B2 A/B3

A B x y B( x,y A)

Page 41: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

41

Find sailors who’ve reserved a red or a green boat

• Can identify all red or green boats, then find sailors who’ve reserved one of these boats:

( , (' ' ' '

))Tempboatscolor red color green

Boats

sname Tempboats serves Sailors( Re )

Find sailors who’ve reserved a red and a green boat

( , ((' '

) Re ))Tempredsid color red

Boats serves

sname Tempred Tempgreen Sailors(( ) )

( , ((' '

) Re ))Tempgreensid color green

Boats serves

Find the names of sailors who’ve reserved all boats

( , (,

Re ) / ( ))Tempsidssid bid

servesbid

Boats

sname Tempsids Sailors( )

find the names of sailors who’ve reserved all ‘Interlake’ boats:

Page 42: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

42

Relational Calculus

• Relational Calculus is an alternative to relational algebra.• In contrast to Relational Algebra, which is procedural, the calculus

is non-procedural (declarative).• It allows us to describe the set of answers without specifying how

they should be computed.• It has had more influence on SQL.• Calculus has

– variables, constants, comparison ops,logical connectives– quantifiers

• Comes in two flavors: Tuple relational calculus (TRC) and Domain relational calculus (DRC).– TRC: Variables range over (i.e., get bound to) tuples.

• Like SQL.– DRC: Variables range over domain elements (= field values).

• Like Query-By-Example (QBE)• Expressions in the calculus are called formulas.

Page 43: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

43

Tuple Relational Calculus

• Query has the form: {T | p(T)}– p(T) denotes a formula in which tuple variable T appears.

• Result is the set of all tuples t for which the formula p(T) evaluates to true with T=t

• Formula P(T) specified in First Order Logic• A tuple variable is a variable that takes on the tuples of a

particular relation schema as values.

• An Atomic formula is one of the following:R Rel R.a op S.bR.a op constant

op is one of <,>,=,<=,>=,!=

Page 44: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

44

TRC Formulas• An Atomic formula is one of the following:

R Rel R.a op S.bR.a op constant

op is one of • A formula can be:

– an atomic formula– where p and q are formulas– where variable R is a tuple variable– where variable R is a tuple variable

, , , , ,

qpqpqpp ,,,))(( RpR

))(( RpR

• The use of quantifiers and in a formula is said to bind X in the formula.– A variable that is not bound is free.

X X

Free and Bound Variables

• There is an important restriction — the variable T that appears to the left of `|’ must be the only free

variable in the formula p(T).— in other words, all other tuple variables must be bound using a

quantifier.

Page 45: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

45

Examples• Find all sailors with rating above 7

• Find names and ages of sailors with rating above 7.

– Note: S is a tuple variable of 2 fields (i.e. {S} is a projection of Sailors) • only 2 fields are ever mentioned and S is never used to range over

any relations in the query.

{S |S Sailors S.rating > 7}

{S | S1 Sailors(S1.rating > 7 S.sname = S1.sname S.age = S1.age)}

Joins

Find sailors rated > 7 who’ve reserved boat #103

• Note the use of to find a tuple in Reserves that `joins with’ the Sailors tuple under consideration.

{S | SSailors S.rating > 7 R(RReserves R.sid = S.sid R.bid = 103)}

Page 46: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

46

{S | SSailors S.rating > 7 R(RReserves R.sid = S.sid B(BBoats B.bid = R.bid B.color = ‘red’))}

Find sailors rated > 7 who’ve reserved a red boat

Division

Find sailors who’ve reserved all boats (hint, use )

{S | SSailors BBoats (RReserves(S.sid=R.sidB.bid=R.bid))}

{S | SSailors B Boats ( B.color = ‘red’ R(RReserves S.sid = R.sid B.bid = R.bid))}

Find sailors who’ve reserved all Red boats

Page 47: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

47

Domain Relational Calculus

• A domain variable is a variable that ranges over the values in a domain of some attribute.

• Query has the form:

x x xn p x x xn1 2 1 2, ,..., | , ,...,

Answer includes all tuples that make the formula be true.

DRC Formulas• Atomic formula:

– <x1,x2,…,xn> Rel , where Rel is a relation with n variables – X op Y – X op constant– op is one of comparison ops (<,>,=,,.),

• A formula is recursively defined to be one of the following: p, pq, pq, pq , where p, q are formulas X(p(X)), where X is a domain variable X(p(X)), where X is a domain varialbe

Page 48: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

48

Find all sailors with a rating at least 7

7,,,|,,, TSailorsATNIATNI

Find sailors rating > 7 who’ve reserved boat #103I N T A I N T A Sailors T, , , | , , ,

7

Ir Br D Ir Br D serves Ir I Br, , , , Re 103

Find sailors rated > 7 who’ve reserved a red boat

I N T A I N T A Sailors T, , , | , , ,

7

Ir Br D Ir Br D serves Ir I, , , , Re

B BN C B BN C Boats B Br C red, , , , ' '

Find sailors who’ve reserved all boatsI N T A I N T A Sailors, , , | , , ,

B BN C Boats, ,

Ir Br D serves I Ir Br B, , Re

-Find the names of sailors who have reserved at least two boats

Page 49: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

1. (a) Which of the following is procedurali. Relational algebraii. Relational calculusJustify your answer with an example.

(b) Compare the two relational calculi.2. (a) What is a view? Explain the a views in SQL? (b) Discuss the problems encountered in modifying database through views.3. (a) Explain the operations select, project Cartesian product and join with suitable examples. (b) Explain the following terms

i. Atomic formulaii. Well formed formula

4. Consider the following schema given. The primary keys are underlined.Sailors(sailor-id, sailor-rating, sailor-age)Boats(boat-id, boat-name, boat-color)Reserves(sailor-id, boat-id, day)

Write the queries in tuple relational calculus for the following i. Find all sailors with a rating above 10 ii. Find all boats with color blue iii. Find the names of sailors who have reserved all boats iv. Find the names of sailors who have reserved a green boat

Assignment - 2

Page 50: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

5. Consider the following schema for a COMPANY databaseEmployee (Name, SSN, Address, Sex, Salary, Dnumber)Department (Dname, Dnumber, MGRSSN, MGRSTART date)Dept-locations (Dnumber, Dlocations)Project (Pname, Pnumber, Plocation, Dnumber)Works-on (ESSN, Pnumber, Hours)Dependent (ESSN, Dependent-name, Sex, Bdate, Relationship)

Write the queries in Relational Algebra to i. Retrieve all employees who either work in department 4 and make over 25,000 per year or work in department 5 and make over 30,000 ii. Retrieve the Social Security numbers of all employees who either work in department 5 or directly supervise a employee who works in department 5. iii. Retrieve the name and address of all employees who work for the “Re- search” department iv. List all the projects on which employee “Smith” is working.

6. (a) What is the difference between a candidate and the primary key for a given relation? What is a super key? (b) What is a foreign key constraint? Why are such constraints important? What is referential integrity?

Page 51: UNIT II Introduction to the Relational Model Integrity Constraint Over relations Enforcing Integrity constraints Querying relational data Logical data

7 Consider the following relations:AUTHOR (NAME, ADDRESS, AGE)PUBLISHER (NAME, ADDRESS)BOOK (TITLE,AUTHOR,PUBLISHER)

Use relational algebra, Calculus to represent the following queries: (a) What are the authors and titles of all books? (b) What are the titles published by XYZ? (c) What are the names of all authors publishing book with XYZ? (d) What are the names of authors publishing at least one book with XYZ?8Consider the following schema given. The primary keys are underlined.

PROJECT(Projectnum,Project Name, Chief Architect)EMPLOYEE( Empnum, Empname)ASSIGNED TO(Projectnum, Empnum)

Write the following queries in Tuple relational calculus i. Find Empnum of employees working on project COMP454 ii. Find the details of employees(both number and name) working on the

project COMP365 iii. Find the details of employees working on the ”Database” project iv. Find the Empnums of employees who do not work on project COMP464 v. Find the Empnums of employees who work on all projects