CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

66
1 CHAPTER 3 RELATIONAL DATA MODEL Relational Database Concepts A Relational Database is a collection of Tables called Relations. Relation Schema A Relation Schema refers to the structure of a Table. It indicates the Name of the Relation Schema and the Names its Attributes (represented by Columns in the table). For example R (A 1 , A 2 , ……, A n ) represents a Relation Schema named “R” having n columns, representing the Attributes A 1 ,A 2 , …. A n. Domain of an Attribute The Domain of an Attribute A i is the set of permitted (legal) values, that can be assigned to Attribute A i . It is possible for more than one Attributes to have the same Domain or to have overlapping Domains. - The domains of all attributes of a relation should be atomic (indivisible). - One value that is member of all domains is null , which implies that the value is either unknown or non-existent; for example suppose an entity has attribute telephone-number. It may have null value if an entity does not have a telephone number or if the entity has telephone number, but number is not known. Degree of a Relation Schema The Degree of a Relation Schema “R” refers to the number of Attributes (Columns) in the Schema. For example, the Relation Schema R (A 1 , A 2 , ……,A n ) has a Degree of n. Relation or Relation Instance A Relation or relation instance, denoted as r(R), refers to an actual Table named “r” created on the Relation-Schema “R”. A table will comprise a set of rows (called tuples). Let r(R) = {t 1 , t 2 , ……, t m } where t 1 , t 2 , ……, t m are the tuples in the relation. Each tuple t will be an ordered list of n values. Let t = <v 1 , v 2 , …..v n > The n-values in a tuple will represent an entity or a relationship. Thus, all the n values in the tuple will be related to each other. That is why the resulting database is called a “relational database”. Praveen Kumar

Transcript of CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

Page 1: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

1

CHAPTER 3

RELATIONAL DATA MODEL

Relational Database Concepts

A Relational Database is a collection of Tables called Relations.

Relation Schema

A Relation Schema refers to the structure of a Table. It indicates the Name of theRelation Schema and the Names its Attributes (represented by Columns in thetable). For example R (A1, A2, ……, An) represents a Relation Schema named “R”having n columns, representing the Attributes A1,A2, …. An.

Domain of an Attribute The Domain of an Attribute Ai is the set of permitted(legal) values, that can be assigned to Attribute A i. It is possible for more thanone Attributes to have the same Domain or to have overlapping Domains.

- The domains of all attributes of a relation should be atomic (indivisible).

- One value that is member of all domains is null, which implies that thevalue is either unknown or non-existent; for example suppose an entity hasattribute telephone-number. It may have null value if an entity does not have atelephone number or if the entity has telephone number, but number is notknown. Degree of a Relation Schema

The Degree of a Relation Schema “R” refers to the number of Attributes(Columns) in the Schema. For example, the Relation Schema R (A1, A2, ……,An)has a Degree of n.

Relation or Relation Instance A Relation or relation instance, denoted asr(R), refers to an actual Table named “r” created on the Relation-Schema “R”. Atable will comprise a set of rows (called tuples).

Let r(R) = {t1, t2 , ……, tm} where t1, t2 , ……, tm are the tuples in the relation.

Each tuple t will be an ordered list of n values.

Let t = <v1, v2, …..vn>

The n-values in a tuple will represent an entity or a relationship. Thus, all the nvalues in the tuple will be related to each other. That is why the resultingdatabase is called a “relational database”.

Praveen Kumar

Page 2: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

2

Note that a tuple is an Ordered List (not a Set) of n values. That is why theorder of the values in the tuple matters. A value V i (1 < I < n) in the tuple t will befrom the Domain of attribute Ai.i.e. vi ∈ Domain (Ai)

A Relation can also be defined as a subset of the Cartesian Product of all theDomains of its Attributes. i.e. r (R) ⊆ Domain (A1) x Domain (A2) X …… X Domain (An)

Cardinality of a Relation The Cardinality of a Relation r(R) at any moment isdefined as the numbers of rows (tuples) existing in the Relation (Table) at thatmoment of time.

The cardinality of relation r(R)= {t1, t2 , ……, tm} will be m.

There can be more than one Relations (Tables) defined on the same Schema,For example r1(R) and r2(R) are two independent relations defined on the sameSchema R. Both will have same Degree but may have different cardinalities.

The Cardinality of a relation will vary from moment to moment; but degree willchange very rarely.

Some Notations

Since a relation is defined as a set of tuples, the notation t ∈ r implies that tuple tis in relation r

t[Ai] denotes the value of tuple t on attribute Ai.

Consider the following set of Schemas, representing information aboutStudents, Subjects and Results:-

STUDENT (Univ_Roll_No, Class_Roll_No, S_Name, DOB, Year,Branch, Section, Father_Name, Address, Tel_No)

It represents a Relation Schema “STUDENT” with attributesUniv_Roll_No, Class_Roll_No, S_Name, DOB, Year, Branch, Section,Father_Name, Address, Tel_No. Let us assume that each student has aunique Univ_Roll_No. Also, Class_Roll_No of a student is unique in aclass which is defined by the combination of {Year, Branch, Section}

SUBJECT (Sub_Code, Title)

Praveen Kumar

Page 3: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

3

It represents a Relation Schema “SUBJECT” having attributes Sub_Code(like “TCS-402”), Title (like “DBMS”) such that each subject has a uniqueSub_Code.

RESULT (Univ_Roll_No, Sub_Code, Semester, Marks)

It represents relation Schema “RESULT” having attributes Roll_No,Sub_Code, Semester and Marks.

Super Key of a Relation Schema R

The Super Key of a Relation Schema R refers to the set of attributes K (K ⊆ R),which when taken collectively, will uniquely identify each tuple in a relation r(R).The superset of a super-key will also be a super-key. Thus, a super-key mayhave some extraneous attributes, without which the balance set still remains asuper-key. Such extraneous attributes, which need not be there in a super-key,can be eliminated from the key.

For example in the above schemas, {Univ_Roll_No, S_Name} will form asuper-key of Relation Schema “STUDENT”. This super-key has an extraneousattribute “S_Name”, without which the balance set i.e. {Univ_Roll_No} stillremains a super-key, since each student has a unique Univ_Roll_No.

Candidate Key of a Relation Schema R

A Candidate Key is defined as a super-key, whose no proper subset is asuper-key i.e. a Candidate Key is a minimal super key (having no extraneousattributes).

A Relation Schema may have more than one Candidate Keys.

In the above schemas, the relation schema “STUDENT” has the followingCandidate Keys:-

{Univ_Roll_No}{Class_Roll_No, Year, Branch, Section}{S_Name, DOB, Father_Name, Address} Assuming that twins will nothave same name

And Relation Schema “SUBJECT” has {Sub_Code} as its Candidate Key andRelation Schema “RESULT” has {Roll_No, Sub_Code} as its candidate key.

Primary Key of a Relation Schema R

Praveen Kumar

Page 4: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

4

It refers to one of the Candidate Keys of R, which is designated as primarymeans of uniquely identifying tuples in a relation r(R).

For example, {Univ_Roll_No} will be the most appropriate choice ofPrimary Key of Relation Schema “STUDENT”.

Since the other two relation schemas have only one candidate key each,the same will be designated as their respective Primary Keys.

Composite Key A Key, that includes more than one attributes, is called aComposite Key.

For example, the relation schema “RESULT” has Composite PrimaryKey {Univ_Roll_No, Sub_Code}.

Foreign Key A relation schema R may include among its attributes some primarykey of another schema S. This is called a Foreign Key in schema R.

For example, {Univ_Roll_No} forms a Primary Key in STUDENT but itforms Foreign Key in RESULT. Similarly {Sub_Code} forms a Primary Key ofSUBJECT but a Foreign Key in RESULT.

Integrity Constraints of a Relational Database

The following three types of Integrity Constraints are applicable to all RelationalDatabases:-

(i) Domain Constraint(ii) Key Constraint(iii) Foreign Key (FK) Constraint or Referential Integrity Constraint

(i) Domain ConstraintLet there be a Relation Schema R (A1, A2, ……, An). A Relation r (R) would be legal only if for each tuple t ∈ r and for eachvalue t[Ai] in t, it satisfies t[Ai] ∈ Domain (Ai); else the Relation will beillegal (invalid). This means that in a legal relation r(R) , all the values appearing undereach attribute must be from the domain of that attribute.

Specifying Domain Constraints in SQL The domain constraints inSQL are specified by the data types of the attributes or by the CHECKvalue clause or by “NOT NULL” clause. Various data types are NUMBER,CHAR, VARCHAR, DATE etc.

Praveen Kumar

Page 5: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

5

CREATE TABLE STUDENT( Univ_Roll_No CHAR (10),

Class_Roll_No INT,S_Name VARCHAR (20) NOT NULL,DOB DATE NOT NULL,Year INT,Branch CHAR(3),Section INT,Father_Name VARCHAR(20) NOT NULL,Address VARCHAR (30) NOT NULL,Tel_No CHAR (11),

PRIMARY KEY(Univ_Roll_No)CHECK (Year BETWEEN 1 AND 4)CHECK (Section BETWEEN 1 AND 2));

CREATE TABLE SUBJECT( Sub_Code CHAR(7),

Title VARCHAR(20) NOT NULL, PRIMARY KEY (Sub_Code));

For each attribute, the permitted domain is specified in the schema definition;for example the domain of “Year” is the set of Integers.

Additionally, the ‘CHECK’ clause can be used to further specify a sub-domainwithin the specified domain; for example the permitted domain of “Year” in“STUDENT” is set of integers between 1 and 4.

(ii) Key ConstraintLet R (A1, A2,…, An) be a relation schema, then for each key K of R(K⊆R) and for each legal Relation r(R) and for each tuple-pair {t1, t2} ∈r, it must satisfy t1[K] ≠ t2 [K]. Else the Relation will be illegal (invalid).This means that the values of no two in a legal relation must agree onthe Keys of that schema.

In SQL, a CREATE TABLE statement must explicitly specify PRIMARYKEY of each Table.

Suppose a relation r(R) with Key {A,B} has the following state:-

r(R)A B C

Praveen Kumar

Page 6: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

6

A1 b1 c3

A2 b1 c1

A3 b2 c5

A1 b2 c7

A3 b2 c1

This relation state is invalid, since there are two tuples with value of {A,B}equaling {a3, b2}. One of these two tuples must be deleted, only then it will be avalid relation.

(iii) Foreign Key (FK) Constraint OR Referential Integrity Constraint

Let r(R) and s(S) be two relations and let α (α⊆s) be a Foreign Key(FK) in S referencing Primary Key “K” of R. The relation s(S) would belegal (valid) only if for each tuple ts ∈ s, there exists a tuple tr ∈ r suchthat tr [K] = ts [α]. A tuple ts ∈ s that does not satisfy this condition willbe called a “Dangling Tuple”, in the sense, that such tuples do nothave necessary support from relation r. Such Dangling Tuples areinvalid; and DBMS has to ensure that such tuples do not exist in thedatabase.

Specification of Primary Keys and Foreign Keys in SQL

In SQL, the FOREIGN KEY – PRIMARY KEY mapping is explicitlyspecified in a CREATE TABLE statement.

CREATE TABLE RESULT( Roll_No CHAR (10), Sub_Code CHAR (7), Semester INT, Marks INT, PRIMARY KEY (Roll_No, Sub_Code), FOREIGN KEY (Roll_No) REFERENCES STUDENT (Roll_No), FOREIGN KEY (Sub_Code) REFERENCES SUBJECT (Sub_Code), CHECK (Semester BETWEEN 1 AND 8), CHECK (MARKS BETWEEN 0 AND 100));

Praveen Kumar

Page 7: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

7

Example:- Let there be two relations subject (SUBJECT) and result(RESULT). Attribute Sub_Code in RESULT is a Foreign Key referencingprimary key Sub_Code of relation SUBJECT.

subjectSub_Code TitleTCS-401 Comp OrgTCS-402 DBMSTCS-301 Data Structure

resultRoll_No Sub_Code Semester Marks

0209130010 TCS-301 3 660209130010 TCS-401 4 570209130010 TCS-403 4 78

The relation result has a dangling tuple <”0209130010”, “TCS-403”, 78>,which is attempting to reference a “Sub_Code” value of “TCS-403” whichdoes not exist in the relation subject, where “Sub-Code” is Primary Key.Thus, this tuple is a dangling tuple, which is invalid. This tuple must bedeleted from table result, or a tulpe must be added to relation “subject”with “Sub_Code” value = “TCS-403”.

How to determine the Primary Keys of Relation Schemas?

1. Strong Entity Set. The Primary key of the entity set forms the primarykey of the relation.

2. Weak Entity Set. Primary key of the relation comprises the union of theprimary key of the strong entity set on which the weak entity set isexistence-dependent and the discriminator of the weak entity set.

3. Relationship Set. The union of the primary keys of the related entitysets becomes a super key of the relation. If the relationship is many to many,then this super key is also the primary key of the relation. If the relationship ismany-to-one, then primary key of the “many-side” entity set is the primary key ofthe relation. If the relationship is one-to-one, then primary key of any of therelated entity sets can be the primary key of the relation.

4. Combining of Tables. A many-to-one binary relationship R from A toB can be represented by a table comprising of the attributes, that will be union ofthe Primary Keys of A and B and the descriptive attributes of R. Such a table canbe combined with the table of “Many-Side” Entity Set. The attributes of thecombined table will be a union of the attributes of the two fused tables. So, thePrimary Key of the “One-Side” Entity Set will also form part of the table for

Praveen Kumar

Page 8: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

8

“Many-Side” Entity Set. For example, the table for ACCOUNT also contains thekey of Entity Set BRANCH.

For a one-to-one relationship set, the relationship table can be combined with thetable of any of the participating entity sets.

5. Multi-valued Attributes. A multi-valued attribute M is represented by atable consisting of the primary key of the entity set of which M is an attribute plusa column C holding individual values of attribute M. Entire set of attributes of theresultant relation forms a primary key of the relation.

A SAMPLE DATABASE “ACADEMICS DB”

Let us consider an Academics Database “ACADEMICS DB”, with following EntitySets & Relationship Sets:-

Entity Sets:-

(i) STUDENT with Attributes Roll_No & S_Name. Suppose attributeRoll_No has a unique value for each student.

(ii) SUBJECT with Attributes Sub-Code,Title and Semester(iii) FACULTY with Attributes Fac_Code & Fac_Name(iv) DEPT with Attributes D_Name & HOD

Relationship Sets:-

(i) SUB- OFFERED A many-to-many relationship between entitysets FACULTY & SUBJECT. This implies that a Faculty can offer anynumber of subjects in a semester and a subject can be offered by anynumber of faculty members.

(ii) RESULT A many-to-many relationship between the entity setsSTUDENT and the aggregated relationship SUB_OFFERED withdescriptive attribute MARKS. This relationship represents the Marksobtained by the students in various subjects. Assume that each studentcan take many of the offered subjects and each offered subject can betaken by many students.

(iii) FAC-DEPT A many-to-one relationship between the entity setsFACULTY & DEPT with descriptive attribute DOJ (Date of Joining). Thisimplies that a Dept can have many faculty but a faculty can belong to onlyone Dept.

Praveen Kumar

Page 9: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

9

The above Database can be represented by the following E-R Diagram:-

RESULT

FAC-DEPTRelational Database:-

The above scenario can be represented by the following RelationalSchemas:-

STUDENT (Roll_No, S_Name)SUBJECT(Sub_Code, Title, Semester)DEPT (D_Name, HOD)FACULTY (Fac_Code, Fac_Name, D_Name)SUB_OFFERED (Fac_Code, Sub_Code)RESULT (Roll_No, Fac_Code, Sub_Code, Marks)

No table is required for the “one-to-many” relationship set “FAC-DEPT”; itis combined with the “many-side” entity-set “FACULTY”; that is why the table for“FACULTY” also includes the Primary Key “Dept_Name” of entity set “DEPT”.The attribute “Dept_Name” forms a Foreign Key in table “FACULTY”, referencingthe Primary Key of table “DEPT”.

Praveen Kumar

Aggregated Relationship “SUB-OFFERED”

SUB- OFFERED

SUBJECT

FACULTY

Sub_CodeSemester

Title

Fac_Code

Fac_Name

DEPT

Dept_Name HOD

STUDENT

Marks

Roll_No

S_Name

S_Addr

Page 10: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

10

“SUB_OFFERED” represents a “many-to-many” relationship between theentity sets “FACULTY” and “SUBJECT”; that is why the table “SUB_OFFERED”contains primary keys of both participating entity sets. The attributes “Fac_Code”and “Sub_Code” form foreign keys in this table; “Fac_Code” is referencing theprimary key of “FACULTY” and “Sub_Code” is referencing the primary key of“SUBJECT”.

The relationship set “RESULT” represents a “many-to-many” relationshipbetween aggregated relationship set “SUB_OFFERED” and entity set“STUDENT”. The table “RESULT” includes its descriptive attribute “Marks” andthe primary keys of both “SUB-OFFERED” and “STUDENT”. The attributes“Roll_No”, “Sub_Code” and “Fac_Code” form foreign keys in table “RESULT”.

Schema Diagram The Schema diagram represents diagrammatically the RelationSchemas of a database. A Relation Schema is depicted by a rectangle, divided intotwo parts- the top part depicts key-attributes and the bottom part depicts thenon-key attributes. As compared to E-R Diagram, the Schema Diagram alsodepicts PK-FK relationship between various relation schemas, by a directed edgedrawn from FK to PK. The above E-R Diagram can be represented by a SchemaDiagram, as follows:-

SUBJECT RESULT STUDENT

SUBJECT-OFFERED FACULTY DEPT

Praveen Kumar

Sub_Code

Title

Semester

Roll_No

Sub_Code

Fac_Code

Marks

Roll_NoS_Name

S_Addr

Sub_Code

Fac_Code

Fac_Code

Fac_Name

Dept_Name

Dept_Name

HOD

Page 11: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

11

Exercises

Ex.3.1 Explain mathematically a relation (table) “r” defined on a Schema R (A1,A2, ….., An). Define its degree and cardinality.

EX.3.2 Explain the concepts of Domain Constraint, Key Constraint andReferential Integrity Constraint.

Ex.3.3 Make Schema diagrams for the following set of schemas:-

(a) Student (Roll_No, S_Name, S_Address)Subject (Sub_Code, Title, Credits, Semester)Dept (D_Code, D_Name, HOD)Faculty (F_Code, F_Name, D_Code)Assigned (F_Code, Sub_Code)Result (Roll_No, Sub_Code, Semester, Marks)

(b) Emp (E#, E_Name, Salary, D#)Dept (D#, D_Name, Mgr#, Total_Salary)

Where D# is foreign key in Emp referencing D# of Dept and Mgr# isforeign key in Dept referencing E# of Emp.

(c ) Supplier (S#, S_Name, S_City)Part (P#, P_Name, P_Weight)Project (J#, J_Name, J_City, Manager)Order (S#, P#, J#, Qty)

Ex.3.4 What additional information is conveyed by a Schema Diagram ascompared to an E-R Diagram?

Praveen Kumar

Page 12: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

12

CHAPTER 4RELATIONAL ALGEBRA

The Relational Algebra is a Procedural query language. A query in RelationalAlgebra (RA) has to specify not only ‘what information is required’ but also ‘howto extract this information’. It is capable performing operations pertaining toinformation retrieval and information update. A Query in Relational Algebra willinvolve the following operations:-

Basic Operations

1. Select (σ )2. Project (Π)3. Set Union (∪)4. Set Difference (-)5. Cartesian Product (X)6. Rename (ρ)

Additional Operations

7. Set Intersection (∩)8. Natural Join ( / * )9. Theta Join ( )10. Divide (÷)11. Assignment (←)

Extended RA Operations

12. Generalized Project (∏)13. Aggregate Functions (G)14. Outer Join

(a) Left Outer Join ( )(b) Right Outer Join ( )(c) Full Outer Join ( )

1. Select ( σ ) The Select operation σP (r) selects those tuples from relationr, which satisfy predicate P.

The predicate P will involve:- (a) Attributes from Schema R of r(b) Literals (c) Comparison Operators: <, > , < , >, =, ≠(d) Logical Operator: ∧, ∨, ¬

Praveen Kumar

Page 13: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

13

Degree of the resultant relation will be equal to degree of argumentrelation r = Degree (R).

Cardinality of the resultant relation will be < cardinality (r).

Example: Consider the schema:-EMP (E#, E_Name, E_City, E_Street, Salary, D#)DEPT (D#, D_Name, D_City, Total_Sal)

Where Total-Sal is the total salary of all employees of aDepartment.

And consider the following relations (tables) on the aboveschemas:-

EmpE# E_Name E_City E_Street Salary D#

001 Ajay Noida Sec-25 50000 03003 Vijay G Noida Alpha 15000 03004 Ram Delhi RKP 15000 02005 Shyam Noida Sec-26 45000 03007 Vishal Noida Sec-25 37000 02010 Raju G Noida Beta 32000 01012 Vikash Noida Sec-27 35000 01

DeptD# D_Name D_City Total_Sal

01 Marketing Delhi 6700002 Dispatch G Noida 5200003 Finance Delhi 1100000

Query 1: Get information of those employees of Department Number 03,who are drawing salary more than 25000.

σD# = ‘03’ ∧ Salary > 25000 (emp)

The resultant relation will be:-

E# E_Name E_City E_Street Salary D#

001 Ajay Noida Sec-25 50000 03005 Shyam Noida Sec-26 45000 03

Praveen Kumar

Page 14: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

14

2. Project The Project operation ΠS (r) projects attributes’ list S fromr(R), (Where S ⊆ R). Any duplicate Tuples in the result are automaticallyeliminated.

Degree of the resultant relation will be < degree(R) Cardinality of the resultant relation < cardinality (r). The cardinality of resultantrelation will be equal to the cardinality of r if S includes a key of R.

Query 2: Get E# and E_City of all employees.

ΠE#, E-City (emp)

The result will be:-

E# E_City E_Street

001 Noida Sec-25003 G Noida Alpha004 Delhi RKP005 Noida Sec-26007 Noida Sec-25010 G Noida Beta012 Noida Sec-27

Query 3: Get D_Name of those departments, Which have total salarymore than 1000000.

ΠD-Name (σTotal-Sal > 1000000 (dept))

Result:-

D# D_Name

03 Finance

3. Set Union ( ∪ ) The ‘Set Union’ operation r ∪ s is a binary operationthat takes two argument relations r and s as input and produces a singleresultant relation, which is the union of the set of tupes of the two argumentrelations. Duplicate tuples are automatically eliminated from the result. Thisimplies that a tuple will appear in r ∪ s if t exists in r or in s or in r and s both.For r ∪ s operation to be feasible, the relations r and s must be compatible,which implies that:-

Praveen Kumar

Page 15: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

15

(a) Both r and s must be of same degree i.e. they must have samenumber of attributes.

(b) For all i, the domain of ith attribute of r must be same as the domain ofthe ith attribute of s.

Degree (r ∪ s) = degree(r) = degree(s)Cardinality (r ∪ s) = cardinality (r) + cardinality (s) – cardinality (r∩s)

Example Consider the Schema:-

DEPOSIT (Cust_Name, Account_No)LOAN (Cust_Name, Loan_No)

Let the Tables on the above schemas be:-

DepositCust_Name Account_No

Ajay A-101Vijay A-103Ram A-107

LoanCust_Name Account_No

Vishal L-103Ram L-102

Query 4: Get the names of those customers, who have either accountor loan in the bank.

ΠCust-Name (Deposit) ∪ ΠCust-Name (Loan)

Result:-

Cust_Name

Praveen Kumar

Page 16: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

16

AjayVijayRamVishal

4. Set Difference The ‘Set Difference’ operation r – s, between tworelations ‘r’ and ‘s’, produces a relation with tuples which are there in ‘r’ but notthere in ‘s’. For the operation r - s to be feasible, the relations r and s must becompatible as in the case of Set Union.

Degree (r - s) = degree(r) = degree(s)Cardinality (r - s) = cardinality (r) – cardinality (r∩s)

Query 5: Get the names of those customers who have account in the bank,but do not have a loan.

ΠCust-Name (Deposit) - ΠCust-Name (Loan)

Result:-

Cust_Name

AjayVijay

5. Cartesian Product The Cartesian Product of two relations r and s isexpressed as r x s .

The resultant relation will be on schema, that will be concatenation of the twoschemas R and S, expressed as (R,S).

For each tuple tr ∈ r and each tuple ts∈s, there will be a tuple t in r x s, such that t[R] = tr and t [S] = ts.

Degree (r x s) = degree (R) + degree (S)And Cardinality (r x s) = cardinality (r) * cardinality (s)

Since, same attribute names may appear in R and S, notation r.attribute-name ors.attribute-name is used to distinguish such attributes. For those attributes, whichappear in one of the schemas, the relation prefix is not required.

Query 6:Deposit X Loan

Praveen Kumar

Page 17: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

17

This will produce a resultant relation having 04 attributes, 02 fromDEPOSIT and 02 from LOAN i.e. Deposit.Cust_Name, Account_No,Loan.Cust_Name and loan_No. The resultant Table will have 6 tuples, asshown below:-

Result:- Deposit X Loan

Deposit.Cust_Name

Account_No Loan.Cust_Name

Loan_No

Ajay A-101 Vishal L-103Ajay A-101 Ram L-102Vijay A-103 Vishal L-103Vijay A-103 Ram L-102Ram A-107 Vishal L-103Ram A-107 Ram L-102

If the names of the argument relations are not distinct (which is the case whenCartesian Product of a relation with itself is specified), rename operation, asexplained below, is used to rename one of the arguments.

6. Rename The rename operation, denoted by Greek letter rho ( ρ )enables to rename a relation.

Example ρx (A1,A2,…..,An) (E) The result of relational-algebra expression E is returned under the name x. The nattributes of the resultant relation are named as A1, A2,…..,An respectively.

Query 7:

Loan ×ρk (CN, LN)(Loan)

Result:-

Cust_Name Account_No CN LN

Vishal L-103 Vishal L-103Vishal L-103 Ram L-102Ram L-102 Vishal L-103Ram L-102 Ram L-102

Praveen Kumar

Page 18: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

18

Query 8: Determine the largest salary amongst all employees.

∏Salary (emp) - ∏emp.Salary (σemp.Salary < k.Salary (emp ×ρk(emp)))

Result:-

Salary

50000

Formal definition of Basic Relational Algebra

A basic expression in relational algebra consists of either of the following:-

(a) A relation in the database(b) A constant relation

The expression is constructed out of small sub-expressions. Let E1 and E2 berelational-algebra expressions. Then, the following are also expressions:-

(a) E1 ∪ E2

(b) E1 – E2

(c) E1 × E2

(d) σP (E1) where P is a predicate on the attributes in E1.(e) ∏S (E1) where S is a list consisting of some of the attributes in E1.(f) ρx (E1) where x is the new name for the result of E1.

Additional Operations of Relational Algebra

The following are additional operations, which do not add any power to therelational algebra, but simplify common queries.

7. Set Intersection The ‘Set Intersection’ operation r ∩ s, between tworelations ‘r’ and ‘s’, produces a relation with tuples which are there in ‘r’ as well asin ‘s’. For the operation r ∩ s to be feasible, the relations r and s must becompatible as in the case of Set Union and Set Difference.

This operation is called additional, since it can be expressed in terms of the basicoperations, as shown below:-

r ∩ s = r – (r-s) i.e. eliminate those tuples from r, which exist in r but not in s. ORr ∩ s = s – (s-r) i.e. eliminate those tuples from s, which exist in s but not in r.

Praveen Kumar

Page 19: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

19

Query 9: Get the names of those customers who have account as well asloan in the bank.

ΠCust-Name (Deposit) ∩ ΠCust-Name (Loan)

Result:-

Cust_Name

Ram

8. Natural Join Natural Join is equivalent to the following sequence ofoperations on two argument relations:-

(a) A Cartesian product of the two argument relations.

(b) A Selection forcing equality on common attributes of the twoargument relations.

(c) Removing duplicate attributes from the resultant relation.

It is denoted by the symbol *.

Consider two relation schemas R and S, which can be treated as sets ofattributes. Then R ∩ S denotes the set of attributes, which are common to bothR and S. And R ∪ S denotes the set of attributes, which are there either in R or inS or in both. R-S denotes the set of attributes, which are there in R but not in S.Then, natural join of relations ‘r’ and ‘s’, denoted by r * s, is a relation on schemaR ∪ S and is formally defined as:-

r * s = ΠR ∪ S(σr.A1 = s.A1 ∧ r.A2 = s.A2 ∧…….∧ r.An = s.An ( r × s ))Where R∩ S = { A1, A2 , ………, An}

Query 10: Get Cust_Name, Account_No and Loan_No of the customers havingaccount as well as loan.

Deposit * Loan

The above query is equivalent to:-Π Deposit.Cust-Name, Account_No, Loan_No (σ Deposit.Cust_Name = Loan.Cust_Name (Deposit × Loan))

Just note, the expression has become extremely user friendly with the use of“Natural Join” operation.

Praveen Kumar

Page 20: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

20

9. Assignment Sometimes, it is convenient to write a relational algebraexpression, by dividing it into sub-expressions and assigning the intermediateresults to temporary relation-variables. The assignment operation, denoted by ←, assigns result of a relation-algebra sub-expression to a temporary relation-variable. The relation-variable may be used in subsequent expressions, just likeany permanent relation. Assignment to a permanent relation would cause itsmodification.

Ex. The Divide (÷) can be divided into parts as follows:-

temp1 ← ΠR-S (r)

temp2 ← ΠR-S ((temp1 × s) - ΠR-S,S (r) )

result = temp1 – temp2

The result, of the expression on the right, is assigned to the variable on the left.

Division ( ÷ ) Let r(R) and s(S) be two relations and let S ⊆ R, that is everyattribute in schema S is also there in schema R. The relation obtained by dividingrelation ‘r’ by relation ‘s’ i.e. r ÷ s is a relation on schema R-S (i.e. schemacontaining those attributes of R which are not there in S.

A tuple t will appear in r ÷ s , if and only if the following two conditions aresatisfied.

1. t ∈ ΠR-S(r)

2. For every tuple ts ∈ s, there must be a tuple tr ∈ r such that:-

(a) tr[S] = ts

(b) tr[R-S] = t

Let r( R ) and s (S) be two relations such that schema S ⊆ R. Then, the DIVIDEoperation r ÷ s is defined as:-

r ÷ s = ΠR-S (r) -ΠR-S (( ΠR-S (r) x s ) -ΠR-S,S (r))

Let temp1 ← ΠR-S (r)temp2 ← (( temp1 x s) -ΠR-S,S (r) )r ÷ s = temp1 - ΠR-S (temp2)

Let r (R) =

Praveen Kumar

Page 21: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

21

A B C Da1a2a1

b1b2b2

c1c2c1

d1d2d2

And s (S) =B Db1b2

d1d2

temp1 = ΠR-S (r)

A Ca1a2

c1c2

(temp1 x s) A C B Da1a1a2a2

c1c1c2c2

b1b2b1b2

d1d2d1d2

ΠR-S,S (r) A C B Da1a2a1

c1c2c1

b1b2b2

d1d2d2

Temp2 = ( temp1 x s) -ΠR-S,S (r)

A C B D

a2 c2 b1 d1

ΠR-S (temp2)

A C

a2 c2

Praveen Kumar

Page 22: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

22

r ÷ s = temp1 - ΠR-S (temp2)

A C

a1 c1

Example: Find the Names of all customers, who have accounts in allbranches of Delhi.

r1 ← Π Branch-Name ( σ Branch-City = “Delhi” ( Branch))r2 ← ∏ Customer-Name , Branch-name ( Depositor Χ Account)result = r2 ÷ r1

EXTENDED RELATIONAL-ALGEBRA EXPRESSIONS

Generalized ProjectionIt permits arithmetic functions to be used in the projection list.Ex. customer-name, limit – credit (credit-info) where credit-info is a relation

on the schema(customer-name, limit, credit)

Outer Join In Natural Join, the resultant output relation contains tuplescorresponding to only those tuples of input relations which satisfy the equalitycriteria on the values of their common attributes. The information pertaining tothe other tuples of input relation does not appear in the output relation. The OuterJoin operation enables to join such tuples also. There are three types of OuterJoin- Left Outer Join, Right Outer Join and Full Outer Join. The attributes withmissing values in some attributes would contain NULL values in those attributes.The symbols for the three outer joins are- Left Outer join: × ,Right outer join: ×and Full Outer Join: ×Ex.

Name Sector CityAjay Sec-26 NoidaVijay Sec-24 G-NoidaRam Sec-24 Faridabad

Relation customer_residence

Name Account branchAjay A-100 NoidaSharma A-200 G-Noid

aVijay A-300 Delhi

Praveen Kumar

Page 23: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

23

Relation bank_account

Natural Join

Name Sector City account branchAjay Sec-26 Noida A-100 NoidaVijay Sec-24 G-Noida A-300 Delhi

Left Outer Join

Name Sector City account branchAjay Sec-26 Noida A-100 NoidaVijay Sec-24 G-Noida A-300 DelhiRam Sec-24 Faridabad null null

customer_residence × bank_account

Right Outer Join

Name sector City account branchAjay Sec-26 Noida A-100 NoidaVijay Sec-24 G-Noida A-300 DelhiSharma null null A-200 G-Noida

Customer_residence × bank_account

Full Outer Join

Name sector city account BranchAjay Sec-26 Noida A-100 NoidaVijay Sec-24 G-Noida A-300 DelhiRam Sec-24 Faridabad Null NullSharma null null A-200 G-Noida

customer_residence × bank_account

Aggregate Functions

Aggregate Functions are the functions which take a collection of values as inputand return a single value as result; like sum, count, avg, min, max.

Ex. G SUM (amount) (loan) – computes the total of all loan amountsG MAX (amount) (loan) - determines the max amongst loan amounts

Praveen Kumar

Page 24: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

24

G MIN (amount) (loan) - determines the min amongst loan amountsG AVG (amount) (loan) - computes the average of all loan amountsG COUNT (amount) (loan) - determines the number of loans held G COUNT DISTINCT (amount) (loan) - determines the no. of distinct loan amounts

Grouping

The following query will compute the total and max of loan amounts ateach branch and list the results branch-wise.

branch-name G sum (amount), max (amount) (loan)

The result of this query is a relation on schema(branch-name, sum ofamount, max of amount). G indicates that relation loan must be dividedinto Groups, based on value of Branch-name.

DATABASE MODIFICATION

DeletionIn relational algebra, it is expressed as r ⇐ r – E where r is a relation and E isrelational-algebra expression.

Ex. account ← account - σ customer-name=”Ajay” (account)loan ← loan - σ amount > 0 and amount < 500 (loan)

Delete all accounts at branches located in Delhi.

r1 ← σ branch-city = “Delhi” (account × branch) r2 ← Πbranch-name, account-number, balance (r1)

account ← account – r2 InsertionIt is expressed as r ← r U E

Ex. account ← account U {“Noida”, A-500, 5000}

Insert a new account for all loan holders of Noida branch, withaccount-number same as loan- number and an initial balance of 1000.

r1 ← ( σ branch-name = “Noida” (borrower × loan))

r2 ← Π branch-name, loan-number (r1)

Praveen Kumar

Page 25: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

25

account ← account ∪ (r2 × {(1000)}) depositor ← depositor ∪ Πcustomer-name, loan-number (r1)

Update it is expressed as r ← ΠF1,F2,……Fn (r) where Fi is either ith attributeof r if it is not updated or an expression involving constants and attributes of r,which gives new value to the ith attribute.

Ex. account ← Π branch-name, account-number, balance ←balance*1.06(σ balance > 10000 (account)) ∪ Π branch-name, account-number, balance ←balance*1.05(σ balance < 10000 (account))

If we want to update only selected tuples from r, we use the following operations:-r ←Π F1,F2,…….Fn ( σp(r)) ∪ (r- σp(r))

Referential Integrity Constraints in Database Modification

Let r1 and r2 be two relations with K as primary key of R1 and α as such thatForeign Key in R2 referencing K1 in R1.

Insert If a tuple t2 is inserted in r2, the system must ensure that there exists atuple t1 ∈ r1 such that t1 [K] = t1 [α] that is, t2 [α] ∈ ∏K1(r1).

Delete If a tuple t1 is deleted from r1, the system must compute a set oftuples in r1 that reference t1, that is set S = σα=K1(r2)

If set S is not empty an empty set, then either the Delete Command should berejected as an error or all tuples that reference t1 (directly or indirectly) must alsobe deleted. As obvious, this would result in a cascading delete, since the tuplesrelations may reference tuples in r2, that further reference t1 ∈ r1.

Update

Case I If a tuple t2 is updated in r2 such that the update effects the attribute set αand t2’ is the modified tuple, the system must ensure that there is a tuple t 1 ∈ r1

such that t1[K] = t2 [K] i.e. t2 [α] ∈ ∏K1(r1) must be satisfied.

Case II If a tuple t1 is modified in r1 such that the update effects the primarykey attributes K, the system must compute a set of tuple in r2 that reference t1,that is set S = σα=K1(r2).

If this set S is not empty, then either the update command should be rejected asan error or all tuples that reference t1 (directly or indirectly) must also be

Praveen Kumar

Page 26: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

26

updated. As obvious, this would result in a cascading update since the tuplesmay reference tuples that reference t1.

VIEWS

The entire logical schema of a database is not visible to each and every user ofthe database. Security considerations may dictate that certain data be hiddenfrom certain users. Beside the security reasons, the designers may wish tocreate user-friendly set of relations, customized to the specific requirements ofdifferent categories of users.

Any relation, that does not form part of the logical schema, but is made visible toa set of users, as a virtual relation, is called a view. The view is not stored as aphysical table in the database. Only a definition of the view is stored in the datadictionary.

The syntax for creation of a view is:-

create view v as <query expression>

Ex. create view all-customer as Π branch-name, customer-name (depositor * account)∪ Πbranch-name, customer-name (borrower * loan)

Once a view has been defined, it can be referenced in queries just like aphysical table.

Create view noida-customer as Πcustomer-name ( σ branch-name= “Noida”

(all-customer)) Whenever a view is defined, the definition is stored in the data dictionary.Whenever a reference is made to the view in a query, a table is created on theview schema, the query is answered. Thereafter, the view table is deleted. Sincea view table needs to be created every time a reference is made to a view, it hasits associated overheads.

Materialized Views To obviate these overheads, some database systemssupport storing of view tables like physical relations. In this case, the view tablesneed to be updated as and when the parent physical relation is updated. Suchviews are called materialized views. The applications that involve frequent use ofa view or the applications requiring fast response to view based queries, wouldprefer materialized views. But the materialized views suffer from the updateoverheads.

Praveen Kumar

Page 27: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

27

Dependency of Views Consider the following View Dependency Graph.

noida-customer

all-customer

borrower loan

One View may be used in the expression defining another View. A View relationv1 is said to depend directly on a View relation v2 if v2 is used directly in theexpression defining v1. As shown in the above View Dependency graph,all-customer is directly dependent on borrower and loan. A View relation v1 issaid to depend on other View relation v2, if a path exists in the View DependencyGraph from v2 to v1. A View relation v is said to be recursive if it depends onitself.

View Expansion View Expansion is used to define the meaning of Views interms of other views. Let View v1 be defined by an expression e1 that may itselfcontain uses of View Relations. A View relations in e1is replaced by theexpressions defining it. The definition itself may contain reference to ViewRelations, which are further replaced by their definitions. This process isrepeated till there are no more uses of View Relations in e1. This process iscalled View Expansion.

Praveen Kumar

Page 28: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

28

Exercises

Ex.4.1 Consider the following schema:-

Student (Roll_No, S_Name, S_Address, S_DOB)Subject (Sub_Code, Title, Credits, Semester)Dept (D_Code, D_Name, HOD)Faculty (F_Code, F_Name, D_Code, Designation)Assigned (F_Code, Sub_Code)Result (Roll_No, Sub_Code, Semester, Marks)

Write the following queries in Relational Algebra:-

(i) Get the Titles of the subjects offered in “Even” Semester.

(ii) Get the names of the students born after “17-APR-1980”.

(iii) Get the Names of “CSE” department faculty.

(iv) Get the Titles of the subjects assigned to “ECE” departmentfaculty.

(v) Get Average Marks, Max Marks, Min Marks and Total Marks inthe Result.

(vi) Get Average Marks scored by each student.

(vii) Get Average Marks scored in each subject.

(viii) Get the name(s) of the students scoring highest Average Marks.

(ix) Get the title(s) of the subjects in which students have scoredhighest average marks.

(x) Get the number of subjects assigned to each faculty.

(xi) Delete the tuples of result having marks less than 30.

(xii) Delete the tuple of Faculty “Ajay”.

(xiii) Change the Designation of Faculty “Vijay” to “Asst Prof”.

(xiv) Add a new faculty with F_Code =”AKG”, F_Name= “Ajay KrGarg”, D_Code =”CSE” and Designation = “Lecturer”.

Praveen Kumar

Page 29: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

29

Ex.4.2 Consider the following schema:-

Emp (E#, E_Name, Salary, D#)Dept (D#, D_Name, Mgr#)

Where D# is foreign key in Emp referencing D# of Dept and Mgr# isforeign key in Dept referencing E# of Emp.

Write the following queries in Relational Algebra:-

(i) Get the names of the employees working in “Manufacturing”Department.

(ii) Get the names of the employees drawing salary between 20000 and50000.

(iii) Get Min Salary, Max Salary and Average Salary of eachdepartment.

(iv) Get the name(s) of the department(s) having highest Averagesalary.

(v) Get the name of each employee along with its manager.

(vi) Get the number of employees working in each department.

(vii) Get the name(s) of the department with total salary of employeesmore than 50000000.

(viii) Get the name(s) of the department(s) having least number ofemployees.

(ix) Get the names of the employees getting salary more than theaverage salary of all the employees.

(x) Increase the salary of all employees by 20%.

(xi) Increase the salary of all managers by 50%.

(xii) Department Name “Scrap” has been closed down. Transfer allemployees of this department to “Absorb” department and deletethe information of “Scrap”.

Praveen Kumar

Page 30: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

30

Ex4.3 Consider the following schema:-

Supplier (S#, S_Name, S_City)Part (P#, P_Name, P_Weight)Project (J#, J_Name, J_City, Manager)Order (S#, P#, J#, Qty)

Write the following queries in Relational Algebra

(i) Get the Names of suppliers located in “Noida” or “Delhi”.

(ii) What is the weight of Part Number “P110”?

(iii) Who are the suppliers, supplying Part “Clutch Assembly” to Project Name“Vehicle R&D”?

(iv) Get the names of the suppliers supplying parts to all projects in“Mumbai”.

(v) Get the names of the suppliers, supplying all the parts, listed in table Part.

(vi) What is the total quantity of each part being supplied?

(vii) What are the parts, whose total quantity being supplied is larger than theaverage quantity being supplied of part name “Ignition Switch”?

Ex.4.4 Consider the following current state of table Result:-

Roll_No Sub_Code Marks

101 TCS-401 70102 TCS-401 80105 TCS-401 64110 TCS-401 70102 TCS-402 92103 TCS-402 70105 TCS-402 70110 TCS-402 68101 TCS-403 82102 TCS-403 64103 TCS-403 72110 TCS-403 80

What will be the results of the following queries:-

(a) G MAX(Marks), MIN (Marks), SUM(Marks), AVG(Marks) (Result)

Praveen Kumar

Page 31: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

31

(b) Roll_No G AVG (Marks), MAX(Marks), MIN(Marks), COUNT(Sub_Code) (Result)(c) Sub_Code G AVG (Marks), MAX(Marks), MIN(Marks), COUNT(Roll_No) (Result)(d) Result ÷ ∏Sub_Code (Result)

Ex.4.5Consider the following state of tables Depositor and Borrower

Depositor

Cust_Name Account_NumberAjay A102Vijay A110Ram A111Vikram A112

Borrower

Cust_Name Loan_NumberVijay L102Shyam L111Ram L110Ajeet L103

Determine the results of the following operations

(a) Depositor X Borrower(b) Depositor * Borrower(c) Left Outer Join of Depositor and Borrower(d) Right Outer Join of Depositor and Borrower(e) Full Outer Join of Depositor and Borrower

Praveen Kumar

Page 32: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

32

CHAPTER5TUPLE RELATIONAL CALCULUS

Tuple Relational Calculus is a non-procedural query language. It describes thedesired information, without giving a specific procedure for obtaining thatinformation.

A query in the tuple relational calculus is expressed as { t | P(t) } which means‘ a set of all tuples t such that predicate P is true for t.’

We use t[A] to denote the value of tuple t on attribute A and t ∈ r to denote that tuple t is in relation r.

Examples

Get information of the loans having loan amount more than 100000.

{ t | t ∈ loan ∧ t[amount] > 1000}

Find the loan numbers of the loans having amount more than 100000.

{t |∃ s∈loan (t[loan-number] = s [loan-number] ∧ s[amount] >100000)}

Find names of the customers who have a loan from Noida branch.

{t | ∃ s ∈borrower (t[customer-name] = s[customer-name] ∧ ∃ u∈loan (u[loan-number] = s[loan-number] ∧

u[branch-name]= “Noida”))}

Find the names of customers having loan or account or both.

{t | ∃ s ∈ borrower (t[customer-name] = s[customer-name] ∨ ∃ u ∈ depositor (t[customer-name = u[customer-name])}

Find names of the customers having both loan and account.

{t | ∃ s ∈ borrower (t[customer-name] = s[customer-name]) ∧∃ u ∈depositor (t[customer-name] = u [customer-name]) }

Find the names of the customers who have account but not loan.

{t | ∃ u ∈ depositor (t[customer-name] = u[customer-name]) ∧ ¬ ∃ s ∈ borrower (t[customer-name] = s [customer-name]) }

Praveen Kumar

Page 33: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

33

Find names of all customers who have accounts at all branches located in Delhi.

{t | ∧∃ x ∈ customer (x[customer-name] = t [customer-name]) ∧ (∀u ∈ branch (u[branch-city] = “Delhi” ⇒

∃ v ∈ account (v[branch-name] = u[branch-name] ∧ ∃ w ∈ depositor (w[account-number] = v [account-number] ∧ t[customer-name] = w [customer-name]))))}

Formal definition of Tuple Relational Calculus

A Tuple-Relational-Calculus expression is of the form {t | P(t) } where P is aformula. A formula in Tuple-relational-calculus is made out of atoms. An atomhas one of the following forms:-

(a) s ∈ r , where s is a tuple variable and r is a relation.

(b) s[x] θ u[y], where s and u are tuple variables , x is an attribute on which sis defined, y is an attribute on which u is defined, and θ is a comparisonoperator (<, <, >, >, =, ≠). The attributes x and y should have domains thatcan be compared by θ.

(c) s[x] θ c, where s is a tuple variable, x is an attribute on which s is defined,θ is a comparison operator and c is a constant from the domain ofattribute x.

A formula is built from atoms using the following rules:-

(a) An atom is a formula.

(b) If P1 is a formula then ¬ P1 and (P1) are also formulae.

(c) If P1 and P2 are formulae, then P1 ∧ P2, P1 ∨ P2 and P1 ⇒ P2 are alsoformulae.

(d) If P1(s) is a formula containing free tuple variable s, and r is relation, then ∃ s∈r (P1(s)) and ∀ s∈r (P1(s)) are also formulae.

The following formulae are equivalent:-(a) P1 ∧ P2 is equivalent to ¬(¬P1∨ ¬ P2).(b) ∀ t∈r (P1(t)) is equivalent to ¬∃ t∈r (¬ P1(t)).(c) P1 ⇒ P2 is equivalent to ¬P1∨ P2.

Praveen Kumar

Page 34: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

34

Safety of Expressions.

There is a possibility that an unsafe tuple-relational-calculus expression maygenerate an infinite expression; like {t |¬ (t∈loan)}. There are infinitely manytuples which are not there in loan. Thus, we define domain of a tuple relationalformula. The domain of P i.e dom(P) is the set of all values referenced by P.These include the values that appear in P and the values that appear in atuple of a relation referenced in P. For example dom( t∈ loan ^ t[amount] > 1200) is the set of values appearing inloan and value 1200. And the dom( ¬ (t ∈loan)) is the set of values appearing inloan.An expression { t | P(t) } is safe if all values that appear in its result are from itsdomain dom(P). Thus the expression {t | ¬(t∈loan)} is not safe, since its resultcan have values outside the domain of the expression (the domain of theexpression being the values appearing in relation loan).

Praveen Kumar

Page 35: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

35

Exercises

Ex.5.1 Let there be schemas:-Account (AN, BN, Bal)Branch (BN, BC)

Write the following queries in Tuple Relational Calculus:-

(a) ∏AN (Account)

(b) σ Bal >= 50000 (Account)

(c) ∏AN (σBC=”Noida”∧ Bal >=100000 (Account * Branch))

(d) ∏BN (Branch) - ∏BN (Account)

Also, state the above queries in plain English.

Ex.5.2 Consider the following schema:-

Student (Roll_No, S_Name, S_Address, S_DOB)Subject (Sub_Code, Title, Credits, Semester)Dept (D_Code, D_Name, HOD)Faculty (F_Code, F_Name, D_Code, Designation)Assigned (F_Code, Sub_Code)Result (Roll_No, Sub_Code, Semester, Marks)

Write the following queries in Tuple Relational Calculus:-

(i) Get the Titles of the subjects offered in “Odd” Semester.

(ii) Get the names of the students born after “10-DEC-1978”.

(iii) Who is the HOD of faculty “Ajay”?

(iii) Get the Names of “ME” department faculty.

(iv)Get the Titles of the subjects assigned to “IC” department faculty.

(v) Get names of the students scoring more than 80 marks in “DBMS”.

Praveen Kumar

Page 36: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

36

Ex5.3 Consider the following schema:-

Supplier (S#, S_Name, S_City)Part (P#, P_Name, P_Weight)Project (J#, J_Name, J_City, Manager)Order (S#, P#, J#, Qty)

Write the following queries in Tuple Relational Calculus:-

(i) Get the Names of suppliers located in “Noida”.

(ii) What is the weight of Part Number “P333”?

(iii) Who are the suppliers, supplying Part “Ignition Switch” to ProjectName “Small Car”?

(iv) Get the names of the suppliers who are supplying parts to theprojects located in the same city as the city of the supplier.

(v) Get the names of the suppliers supplying parts to all projects in“Mumbai”.

Ex.5.4 Consider the following schema:-

Emp (E#, E_Name, Salary, D#)Dept (D#, D_Name, Mgr#)

Where D# is foreign key in Emp referencing D# of Dept and Mgr# isforeign key in Dept referencing E# of Emp.

Write the following queries in Tuple Relational Calculus:-

(i) Get the names of the employees working in “Sales” Department.

(ii) Get the names of the employees drawing salary more than20000.

(iii) Get the name of each employee along with its manager.

Praveen Kumar

Page 37: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

37

CHAPTER 6DOMAIN RELATIONAL CALCULUS

An expression in the Domain Relational Calculus is of the form:-{ <x1,x2,….xn> | P(x,x2,…..,xn) }where x1,x2,…….xn represent domain variables.

P represents a formula, which is composed of atoms, as in the case oftuple-relational-calculus.

An atom in the domain relational calculus has one of the following forms:-

(a) <x1,x2,…..xn> ∈ r, where r is a relation on n attributes; and x1,x2,…..xn aredomain variables or domain constants corresponding to the respective domainsof n attributes of relation r.

(b) x θ y, where x and y are domain variables and θ is a comparison operator(<, <, >, >, =, =/=). x and y should have domains which can be compared by .

(c) x θ c, where x is a domain variable, θ is a comparison operator, and c is aconstant in the domain of x.

A formula is built from atoms using the following rules:-

(a) An atom is a formula.

(b) If P1 is a formula, then so are ¬P1 and (P1).

(c) If P1 and P2 are formulae, so are P1 ∧ P2, P1 ∨ P2 and P1 ⇒ P2.

(d) If P1 (t) is a formula in t, where t is a free domain variable then ∃ t (P1(t)) and ∀ t (P1(t)) are also formulae.

Examples.

Get information of those loans that have amount >100000.

{<l, b, a> | <l , b, a> ∈ loan ^ a > 100000}

Find the loan-numbers of those loans that for which amount is more than100000.

Praveen Kumar

Page 38: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

38

{<l> | ∃ b, a ( <l, b, a> ∈ loan ∧ a > 100000) }

Find names of the customers who have a loan from Noida branch & find loanamount.

{<c, a> | ∃ l (<c, l>∈ borrower ∧ ∃ b (<l, b, a>∈ loan ^b=”Noida” ))}

Find the names of the customers who having loan or account or both at Noidabranch.

{<c> | ∃ l(<c,l> ∈ borrower ^ ∃b,a (<l, b, a> ∈ loan ^ b=”Noida”)) ∨∃ a (<c,a> ∈ depositor ^ ∃ b,n (<a, b, n> ∈ account ^ b=”Noida”)) }

Find names of all customers who have accounts at all branches located in Delhi.

{<c>| ∀x,y,z ((<x,y,z> ∈ branch ∧ y = “Delhi”) ⇒∃ a,b (<a, x, b> ∈account ∧ <c,a> ∈ depositor))}

Safety of Domain-relational-calculus expressions

An expression like {<l, b, a> | ¬ (<l ,b ,a> ∈ loan)} is unsafe, since it allowsvalues in the result which are not there in the domain of the expression. Anexpression in domain-relational calculus {<x1,x2,….xn>| P(x1,x2,…xn)} is safe if allof the following hold:-

(a) All values that appear in the result are from dom(P).(b) For every “there exists” sub-formula of the form ∃ x (P1(x)), the

sub-formula is true if and only if there is a value x in dom(P1) such thatP1(x) is true.

(c) For every “for all” sub-formula of the form ∀x (P1(x)), the sub-formulais true if and only if P1(x) is true for all values from dom(P1).

Equivalent expressions are feasible in the following:-

(a) Relational Algebra (without the extended operations like Aggregate,Outer Join etc)

(b) Tuple Relational Calculus restricted to safe expressions.(c) Domain Relational Calculus restricted to safe expressions.

Praveen Kumar

Page 39: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

39

Some Equivalent Queries in RELATIONAL ALGEBRA(RA), TUPLERELATIONAL CALCULUS (TRC) & DOMAIN RELATIONAL CLACULUS(DRC):-

1. RA: σ A = C (R (A,B,C))TRC: { t t ∈R ∧ t[A] = t[C] }DRC: {< A, B, C> < A, B, C> ∈R ∧ A = C }

2. RA: ∏<A , B> (R (A,B,C))TRC: { t ∃u∈R ( t[A] = u[A] ∧ t[B] = u[B] ) }DRC: {< A, B> ∃ C (< A, B, C> ∈R ) }

3. RA: R (A,B,C) Χ S (C,D,E)TRC: { t ∃u∈R ( t[A]=u[A] ∧ t[B]=u[B] ∧ t[C]=u[C] ∧

∃ v ∈S (v[C]=u[C] ∧ t[D]=v[D] ∧ t[E]=v[E] )) }DRC: {< A, B, C1, D, E> < A, B, C1> ∈R ∧

∃C2 (<C2,D,E>∈S ∧ C2 = C1) }4. RA: R (A,B,C) ∪ S (A,B,C)

TRC: { t t∈R ∨ t∈S }DRC: {< A,B,C> < A,B,C> ∈R ∨ <A,B,C>∈S }

5. RA: R (A,B,C) ∩ S (A,B,C)TRC: { t t∈R ∧ t∈S }DRC: {< A,B,C> < A,B,C> ∈R ∧ <A,B,C>∈S }

6. RA: R (A,B,C) - S (A,B,C)TRC: { t t∈R ∧¬ t∈S }DRC: {< A,B,C> < A,B,C> ∈R ∧¬ <A,B,C>∈S }

7. RA: R (A,B,C) Χ S (D,E,F)TRC: { t ∃u∈R ( t[A]=u[A] ∧ t[B]=u[B] ∧ t[C]=u[C] ∧

∃ v ∈S (t[D]=v[D] ∧ t[E]=v[E] ∧ t[F]=v[F] )) }DRC: {< A, B, C, D, E, F> < A, B, C> ∈R ∧ (D,E,F>∈S}

Praveen Kumar

Page 40: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

40

CHAPTER 7

STRUCTURED QUERY LANGUAGE

Structured Query Language (SQL) is a Language used for interaction with a RelationalDatabase Management System (RDBMS). It is not only a query language; but also usedfor creation, update and maintenance of a database.

Characteristics of SQL

1. It is a non-procedural Language; wherein a Query has to only specify “what”information is to be retrieved from the database, without specifying “how” theinformation is to be retrieved.

2. Its syntax is “English-like”, which makes it very simple and user-friendly.

3. It is highly flexible. A Query in SQL may be written in a number of ways,without affecting the end results. Also, there are no restrictions of starting aQuery at a particular column or to finish a Query in one line only.

4. SQL has a very small set of Commands, which makes it easy to learn.

5. Each SQL Query is parsed by RDBMS to check its syntax.

6. Each SQL Query is optimized, prior to execution.

Advantages of SQL

1. SQL, being a non-procedural language, provides a great degree of abstraction;the user does not have to specify “how” the required information is to beextracted from the database; this is taken care by the RDBMS.

2. Applications written in SQL can be easily ported from one system to another.Such a need would arise when a system needs upgrade or change.

3. Since a query specifies only “what” information is to be extracted, not “how”to extract it, a query in SQL would return same results, irrespective of the factwhether is was optimized prior to its execution or not;

4. The expected results of a query are unambiguously defined.

Praveen Kumar

Page 41: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

41

5. It is not merely a query language used to retrieve information from database;but also it is used to define schema, update database, insert new data, deletedefunct data, to define data integrity constraints and to define user accessrights etc.

6. The language, while being very simple, flexible and easy to learn, it has verypowerful features, which enable it to perform very complex operations in aDBMS.

SQL Data Types & Literals

SQL supports the following Data Types:-

1. CHARACTER (n) Represents a fixed-length string of size n characters;where “n” is an integer > 0. CHAR (n) is its abbreviation and CHAR is anabbreviation for CHAR (1).

2. CHARACTER VARYING (n) Represents a varying-length string ofmax size n characters; where “n” is an integer > 0. VARCHAR (n) is itsabbreviation.

3. BIT (n) Represents a fixed-length string of size n bits; where “n” isan integer > 0.

4. BIT VARYING (n) Represents a varying-length string of max size nbits; where “n” is an integer > 0.

5. NUMERIC (p, q) Represents a Decimal Number; having a totalnumber of “p” digits and sign, with “q” digits to the right of decimal point;“q” must be <= “p”. NUMERIC (p) is abbreviation for NUMERIC (p,0).NUMERIC is abbreviation for NUMERIC (p) where “p” isimplementation-defined.

6. DECIMAL (p, q) It is similar to NUMERIC (p, q). It represents aDecimal Number; having a total number of “p” digits and sign, with “q” digitsto the right of decimal point; “q” must be <= “p”. DEC (p, q) is anabbreviation for DECIMAL (p, q). DEC (p) is an abbreviation for DECIMAL(p, 0). DEC is an abbreviation for DEC (p) where “p” isimplementation-defined.

7. INTEGER Represents a signed integer. INT is its abbreviation.

8. SMALLINT Represents a signed integer. INT is its abbreviation; itsprecision will not increase that of INT.

Praveen Kumar

Page 42: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

42

9. FLOAT (p) Represents floating point number. FLOAT is anabbreviation for FLOAT (p) where “p” is implementation defined. REAL isalternative representation for FLOAT (s) where “s” is implementation-defined.DOUBLE PRECISION is another representation for FLOAT (d) where “d” isimplementation-defined; but “d” > “s”.

10. BOOLEAN It can assume values TRUE or FALSE.

11. DATE This data type has ten positions embedded in single quotesi.e. ‘DD-MM-YYYY’; for example ‘31-05-1950’ implies 31st May 1950.

12. TIME This data type has at least 8 positions embedded in single quotes‘HH:MM:SS’; For example ’11:07:05’ implies 11.07.05 AM and ’23:07:05’implies 11.07.05 PM.

13. TIMESTAMP It includes both DATE and TIME along withminimum 6 digits representing decimal fraction of seconds‘DD-MM-YYYY HH:MM:SS mmmmmm’;for example ‘31-05-195001:02:05 567892’.

14. INTERVAL It specifies a time interval, a relative value that can be usedto increment or decrement an absolute value of DATE, TIME orTIMESTAMP. The intervals are qualified either as YEAR/MONTHintervals or DAY/TIME intervals.

The formats of DATE, TIME and TIMESTAMP are considered as specialtype of String. So, string operators (say LIKE) can be applied to thesedata types.

SQL supports the following Literal Types:-

1. Character String This is written as a sequence of characters enclosedin single quotes; for example:-

‘DBMS’ ‘Structured Query Language’

2. Bit String A bit string is written either as a sequence of 0s and 1senclosed in a single bracket and preceded by letter “B” or as a sequence ofHexadecimal digits preceded by letter “X”; for example:-

B’1001001’B’1’B’0’ X’CA8’

Praveen Kumar

Page 43: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

43

3. Exact Numeric Written as signed or unsigned decimal number, maybe with a decimal point embedded in it. For example:-

77.00+77.77-699000.9

4. Approximate Numeric Written as exact numeric, followed by letter“E” and followed by signed/ unsigned integer; where mEn implies (m)n.

77.00E9-7.7E8+76.7E-4+76.8E5

TYPES OF SQL COMMANDS

SQL Commands can be classified into the following categories:-

1. Data Definition Language (DDL)2. Data Manipulation Language (DML)3. Data Query Language (DQL)4. Data Control Language (DCL)5. Data Administrative Statements (DAS)6. Transaction Control Statements (TCS)

1. Data Definition Language (DDL) It is used for defining the database schemai.e. to CREATE, ALATER & DROP Tables, Views and Indexes; like CREATETABLE, ALTER TABLE, DROP TABLE, CREATE VIEW, DROP VIEW,CREATE INDEX, DROP INDEX.

2. Data Manipulation Language (DML) The DML commands are used tomanipulate the information in the tables; like INSERT, UPDATE or DELETEcommands.

3. Data Query Language (DQL) This refers to SELECT command, which isused to extract information from Tables.Syntax:-

SELECT < list of attributes and/or aggregate of attributes of tables listedbelow>

FROM <list of tables>WHERE <predicate involving attributes of tables listed above and literals>GROUP BY <list of attributes>

Praveen Kumar

Page 44: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

44

HAVING <predicate involving aggregated values>ORDER BY ASC/DESC < list of attributes of tables listed above>

4. Data Control Language (DCL) These are security-related commands, whichcontrol user access to the database. Database administrator grants or revokes userprivileges by using GRANT and REVOKE commands.

5. Data Administrative Statement (DAS) These are basically Audit commandsused to analyze the system performance. There are two commands STARTAUDIT and STOP AUDIT.

6. Transaction Control Statements (TCS) These commands are used to controltransactions; like SET TRANSACTION, SAVEPOINT, COMMIT andROLLBACK.

SQL Operators

1. Arithmetic Operators:- Unary operators like positive or negative expression(+, -) and binary operators like multiplication ( * ), division ( / ) , addition ( + ) andsubtraction ( - ) .

2. Comparison Operators:- =, > , < , >=, <=, ( != , <> , ¬= ) , IN, NOT IN, ISNULL, IS NOT NULL, LIKE, ALL, (ANY , SOME), EXISTS, NOT EXISTS,BETWEEN x AND y .

3. Logical Operators:- AND, OR, NOT.

4. Set Operators:- UNION, UNION ALL, INTERSECT, MINUS.

Operator Precedence

( ) Enclosing Sub Queries ‘ ‘ Enclosing Literals( ) Overrides normal operator precedence+, - Unary Operators*, / Multiplication and division+, - Addition and Subtraction

NOT |AND | Logical OperatorsOR |

UNION |INTERSECT | Set OperatorsMINUS |

Praveen Kumar

Page 45: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

45

Tables, Views & Indexes

Creating a Table

The following DDL Statement will add a new Table STUDENT to the DBMS Catalog,with the attributes and data types as explicitly clear from the statement. It indicates thatattribute REG_NO is primary key and attribute ROLL_NO is Unique, which implies thatROLL_NO is a candidate key of STUDENT.

CREATE TABLE STUDENT ( REG_NO CHAR(10), ROLL_NO CHAR (10), S-NAME VARCHAR (25), FATHERS_NAME VARCHAR (25), BRANCH VARCHAR (05), S_ADDRESS VARCHAR (50), S_TELNO INT, UNIQUE (ROLL_NO), PRIMARY KEY (REG_NO));

Similarly, the following DDL Statements will add new Tables RESULT, EMPLOYEEand DEPT to the DBMS Catalog.

CREATE TABLE RESULT(ROLL_NO CHAR (10), SUB_CODE CHAR (06), MARKS INT,

CHECK (MARKS BETWEEN 0 AND 100), PRIMARY KEY (ROLL_NO, SUB-CODE), FOREIGN KEY (ROLL_NO) REFERENCES STUDENT (ROLL_NO));

CREATE TABLE DEPT( DEPT_NO INT NOT NULL DEFAULT 1, DEPT_NAME VARCHAR (30) NOT NULL, DEPT_HEAD CHAR (8), TOTAL_SAL INT, PRIMARY KEY (DEPT_NO), FOREIGN KEY (DEPT_HEAD) REFERENCES EMPLOYEE (EID));

CREATE TABLE EMPLOYEE(EID CHAR (8) PRIMARY KEY, ENAME VARCHAR (25), DNO INT REFERENCES DEPT (DEPT_NO), SALARY INT,CHECK (SALARY BETWEEN 10000 AND 300000);

Praveen Kumar

Page 46: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

46

Altering an existing Table

The following DDL statement will add a new attribute STATUS of type INT to theexisting Table EMPLOYEE.

ALTER TABLE EMPLOYEE ADD STATUS INT;

Dropping an Existing Table

The following DDL statement will remove the existing Table RESULT from the DBMSCatalog.

DROP TABLE RESULT; Creating a View

The following statement will create a VIEW named DEPT_TOTAL_SAL with twoattributes D_NO and T_SAL by selecting DEPT_NO and TOTAL_SAL of existing TableDEPT.

CREATE VIEW DEPT_TOTAL_SAL (D_NO, T_SAL)AS SELECT DEPT_NO, TOTAL_SAL

FROM DEPT;

There will not be any table named DEPT_TOTAL_SAL; only its definition will be storedin the DBMS Catalog. Whenever, a reference is made to DEPT_TOTAL_SAL in anySQL Query, a table will be created with the help of the definition and the table will bedeleted after answering the query. For Example:-

SELECT DEPT_NOFROM DEPT_TOTAL_SALWHERE T-SAL > 10000000;

The following SQL Statement will create VIEW named DEPT_AVG_SAL with attributesD_NO and AVG_SAL from existing table EMPLOYEE. The attribute AVG_SAL iscomputed by taking average of the salary of the employees of each department. CREATE VIEW DEPT_AVG_SAL (D_NO, AVG_SAL)AS SELECT DNO, AVG (SAL)

FROM EMPLOYEEGROUP BY DNO;

Dropping an existing View

Praveen Kumar

Page 47: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

47

The following statement will remove definition of VIEW named DEPT_TOTAL_SALfrom the DBMS CATALOG.

DROP VIEW DEPT_TOTAL_SAL;

Creating Indexes

Creating a Composite Index

The following statement will create a unique Index on the primary key EID of TableEMPLOYEE.

CREATE INDEX E_INDX1ON EMPLOYEE (EID, DNO);

Creating a Unique Index

The following statement will create a unique Index on the primary key EID of TableEMPLOYEE.

CREATE UNIQUE INDEX E_INDX2ON EMPLOYEE (EID);

Dropping an Index

DROP INDEX E-INDX1;

Queries & Sub-queries

A Query refers to a SELECT Statement used to extract information from the Tables.

Query Get Department Number and Average Salary of the employees of Dept Number 3or more and having more than 10 employees; and order the information in descendingorder of Average Salary.

SELECT DNO, AVG (SALARY) AS AVG_SALFROM EMPLOYEEWHERE DNO > 3GROUP BY DNOHAVING COUNT (*) > 10ORDER BY AVG_SAL DESC;

Query List Employee Names along with the Names of their respective Dept Heads.

SELECT E.ENAME AS EMP_NAME, K.E_NAME AS MGR_NAME

Praveen Kumar

Page 48: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

48

FROM EMPLOYEE E, DEPT D, EMPLOYEE K WHERE E.DNO = D.DEPT_NO AND D.DEPT_HEAD = K.EID;

A Sub-query refers to a nested SELECT Statement as shown below:-

Query Get the name of Employee having highest salary.

SELECT DISTINCT ENAMEFROM EMPLOYEEWHERE SALARY = ( SELECT MAX (SALARY)

FROM EMPLOYEE);

In the above query ( SELECT MAX (SALARY) FROM EMPLOYEE) is a nested sub-query.

Aggregate Functions

Query Find Minimum, Maximum and Average Salary of the Employees.

SELECT MIN (SALARY), MAX (SALARY), AVG (SALARY)FROM EMPLOYEE;

Query Find Average Salary of the Departments having at least 50 employees.

SELECT DNO, AVG (SALARY)FROM EMPLOYEEGROUP BY DNOHAVING COUNT (*) >= 50;

Query Find Average Marks and Total Marks obtained by each Student

SELECT ROLL_NO, AVG (MARKS), SUM (MARKS)FROM RESULTGROUP BY ROLL_NO;

Query Find Minimum, Maximum and Average Marks obtained in each Subject.

SELECT MIN (MARKS), MAX (MARKS), AVG (MARKS)FROM RESULTGROUP BY SUB_CODE;

Insert, Update & Delete Operations

Praveen Kumar

Page 49: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

49

Insert information of a new employee with EID: ‘0013325K’, NAME: ‘VIJAYKUMAR SHARMA’, DNO: 10 and SALARY: 50000 in the EMPLOYEE Table.

INSERT INTO EMPLOYEEVALUES (‘0013325K’, ‘VIJAY KUMAR SHARMA’, 10, 50000);

Update the Salary of employee with EID ‘0012240L’ to 55000

UPDATE EMPLOYEESET SALARY = 55000WHERE EID = ‘0012240L’;

Increase the Salary of each employee by 10%.

UPDATE EMPLOYEESET SALARY = SALARY * 1.1;

Delete Employee with EID ‘0022343C’ from the EMPLOYEE Table.

DELETE FROM EMPLOYEEWHERE EID = ‘0022343C’;

JOINS

Query Get the Names of Students, who have appeared for Subject ‘TCS501’

SELECT DISTINCT S_NAMEFROM STUDENT, RESULTWHERE STUDENT.ROLL_NO = RESULT.ROLL_NO

AND SUB_CODE = ‘TCS501’;

This Query involves a Natural Join of STUDENT and RESULT and in RelationalAlgebra it can be written as:-

∏S_NAME (σSUB_CODE = ‘TCS501’ (STUDENT * RESULT))

UNION, INTERSECT & MINUS

UNION

Query Get the Names of the Students, who have appeared for subject‘TCS501’ or for ‘TCS503’ or for both.

Praveen Kumar

Page 50: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

50

(SELECT DISTINCT S_NAME FROM STUDENT, RESULT

WHERE STUDENT.ROLL_NO = RESULT.ROLL_NO AND SUB_CODE = ‘TCS501’)

UNION

(SELECT DISTINCT S_NAME FROM STUDENT, RESULT WHERE STUDENT.ROLL_NO = RESULT.ROLL_NO

AND SUB_CODE = ‘TCS503’);

This Query is equivalent to Relational Algebra query:-

T1 ← STUDENT * RESULT∏S_NAME (σSUB_CODE= “TCS501” (T1)) ∪ ∏S_NAME (σSUB_CODE = “TCS503” (T1))

INTERSECT

Query Get the Names of the Students, who have appeared both for‘TCS501’ and ‘TCS503’.

(SELECT DISTINCT S_NAME FROM STUDENT, RESULT

WHERE STUDENT.ROLL_NO = RESULT.ROLL_NO AND SUB_CODE = ‘TCS501’)

INTERSECT

(SELECT DISTINCT S_NAME FROM STUDENT, RESULT WHERE STUDENT.ROLL_NO = RESULT.ROLL_NO

AND SUB_CODE = ‘TCS503’);

This Query is equivalent to Relational Algebra query:-

T1 ← STUDENT * RESULT∏S_NAME (σSUB_CODE= “TCS501” (T1)) ∩ ∏S_NAME (σSUB_CODE = “TCS503” (T1))

MINUS (SET DIFFERENCE)

Praveen Kumar

Page 51: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

51

Query Get the Names of the Students, who have appeared for subject‘TCS501’ but not for ‘TCS503’.

(SELECT DISTINCT S_NAME FROM STUDENT, RESULT

WHERE STUDENT.ROLL_NO = RESULT.ROLL_NO AND SUB_CODE = ‘TCS501’)

MINUS

(SELECT DISTINCT S_NAME FROM STUDENT, RESULT WHERE STUDENT.ROLL_NO = RESULT.ROLL_NO

AND SUB_CODE = ‘TCS503’);

This Query is equivalent to Relational Algebra query:-

T1 ← STUDENT * RESULT∏S_NAME (σSUB_CODE= “TCS501” (T1)) - ∏S_NAME (σSUB_CODE = “TCS503” (T1))

Cursors in SQL

Cursor is a Construct in PL/SQL that enables a user to earmark a private memory area tohold an SQL Statement for accessing later on.

Example

Suppose Total Marks Scored by a Student are to be extracted from RESULT and to beentered into Table TOTAL_MARKS (ROLL_NO, T_MARKS).

DECLARECURSOR C_Student IS

SELECT ROLL_NO, SUM (MARKS) FROM RESULT GROUP BY ROLL_NO;

C_NO CHAR (10);C_TOTAL INT;

BEGINOPEN C_Student;LOOP

FETCH C_Student INTO C_NO, C_TOTAL;EXIT WHEN C_Student%NOTFOUND;INSERT INTO TOTAL_MARKS

Praveen Kumar

Page 52: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

52

VALUES (C_NO, C_TOTAL);END LOOP;CLOSE C_Student;COMMIT;

END;

Navigating through SQL

DDL

Creation and Alteration of Tables

1. Create Tables to generate the following schema:-

Customer (C_Id, C_Name, C_Street, C_City)Branch (B_Id, B_Name, B_City)Account (AN, B_Id, Bal)Loan (LN, B_Id, Amount)Depositor (C_Id, AN)Borrower (C_Id, LN)

CREATE TABLE Customer (C_Id Char(10) PRIMARY KEY,C_Name Varchar (15) NOT NULL,C_Street Varchar (15) NOT NULL,C_City Varchar (15) NOT NULL);

CREATE TABLE Branch ( B_Id Char(10) PRIMARY KEY,B_Name Varchar (15) NOT NULL,B_City Varchar (15) NOT NULL);

CREATE TABLE Account ( AN Char(10) PRIMARY KEY,B_Id Char (10) REFERENCES Branch (B_id),Bal Number (10,2));

CREATE TABLE Loan ( LN Char(10) PRIMARY KEY,B_Id Char (10) REFERENCES Branch (B_id),Amount Number (10,2));

CREATE TABLE Depositor (C_Id Char(10) REFERENCES Customer (C_Id),AN Char (10) REFERENCES Account (AN),Primary Key (C_Id, AN));

CREATE TABLE Borrower ( C_Id Char(10) REFERENCES Customer (C_Id),LN Char (10) REFERENCES Loan (LN),Primary Key (C_Id, LN));

Praveen Kumar

Page 53: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

53

Suppose there is a constraint that account balance should not be less than 1000,it can be added to the table Account as follows:-

ALTER TABLE Account ADD CONSTRAINT Check_Bal CHECK (Bal >= 1000);

2. Create Tables on the following schema:-

Supplier (S#, S_Name, S_City)Part (P#, P_Name)Project (J#, J_Name, J_City)Order (S#, P#, J#, Qty)

CREATE TABLE Supplier ( S# Char (10) PRIMARY KEY,S_Name Varchar (30) NOT NULL,S_City Varchar (30) NOT NULL);

CREATE TABLE Part ( P# Char (12) PRIMARY KEY,P_Name Varchar (30) NOT NULL);

CREATE TABLE Project ( J# Char (10) PRIMARY KEY,J_Name Varchar (30) NOT NULL,J_City Varchar (30) NOT NULL);

CREATE TABLE Supply_Order ( S# Char (10) REFERENCES Supplier (S#),P# Char (12) REFERENCES Part (P#),J# Char (10) REFERENCES Project (J#),Qty INT NOT NULL,PRIMARY KEY (S#, P#, J#));

3. Create Tables on the following schema:-

Student (Roll_No, S_Name, S_DOB, S_Address)Course (C_Code, Title, Credits)Teacher (T_Code, T_Name, Desig, D_Code)Department (D_Code, D_Name, HOD)Offers (T_Code, C_Code, Semester)Result (Roll_No, C_Code, T_Code, Semester, Marks)

CREATE TABLE Student ( Roll_No Char (10) PRIMARY KEY,S_Name Varchar (20) NOT NULL,S_DOB DATE,S_Address Varchar(30));

CREATE TABLE Course ( C_Code Char(7) PRIMARY KEY,

Praveen Kumar

Page 54: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

54

Title Varchar (20) NOT NULL,Credits INT NOT NULL);

CREATE TABLE Department ( D_Code Char (3) PRIMARY KEY,D_Name Varchar (20) NOT NULL,

CHECK (D_Code IN (‘CSE’,’IT’,’ECE’,’IC’,’EE’,’ME’,’MT’)),HOD Varchar (30));

CREATE TABLE Teacher ( T_Code Char(3) PRIMARY KEY,T_Name Varchar (30) NOT NULL,Desig Char (10),D_Code Char (3) REFERENCES Department (D_Code),CHECK (Desig IN (‘Lect’, ‘Sr Lect’, ‘Asst Prof’, ‘Prof’)));

CREATE TABLE Offers ( T_Code Char(3) REFERENCES Teacher (T_CoDE),C_Code Char (7) REFERENCES Course (C_Code),Semester Char(5),PRIMARY KEY (T_Code, C_Code, Semester),CHECK (Semester IN (‘Odd’,’Even’)));

CREATE TABLE Result ( Roll_No Char (10) REFERENCES Student (Roll_No),C_Code Char(7),T_Code Char(3),Semester Char (5),FOREIGN KEY (C_Code, T_Code, Semester)REFERENCES Offers (C_Code, T_Code, Semester),MARKS INT,CHECK (MARKS BETWEEN 0 AND 100));

4. Create Tables on the following schema:-

Emp (E#, E_Name, Salary, D#)Dept (D#, D_Name, Total_Sal, Mgr#)

Here D# in Emp is a foreign key referencing D# of Dept, Mgr# in Dept is a foreign keyreferencing E# of Emp and Total_Sal in Dept is total salary of all the employees workingin a department. The situation is little tricky here:-

(i) Both the tables are referencing each other. If we create the Emp table first anddeclare D# as foreign key referencing Dept (D#), the system will generateexception “table or view does not exist” since the table Dept is non-existent.Similar situation will occur if we attempt to create Dept first and declareMgr# as foreign key referencing Emp (E#).

(j) Insertion of data into the tables will also face problem. If we attempt intoEmp first, it will attempt to reference a non-existent tuple in table Dept for

Praveen Kumar

Page 55: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

55

D# and if we first insert a tuple in Dept, it will attempt to reference anon-existent tuple in Emp for Mgr#.

The above two problem situations can be handled as follows:-

Step 1: Create the tables without foreign key constraints:-

CREATE TABLE Emp ( E# Char(12) PRIMARY KEY,E_Name Varchar (30) NOT NULL,Salary NUMBER (10,2),D# Char (12));

CREATE TABLE Dept ( D# Char(12) PRIMARY KEY,D_Name Varchar (30) NOT NULL,Total_Sal NUMBER (15,2),Mgr# Char (12));

Step 2: Add foreign key constraints to the above tables:-

ALTER TABLE Emp ADD CONSTRAINT Emp_FK FOREIGN KEY (D#)REFERENCES Dept (D#) INITIALLY DEFERRED DEFERRABLE;

ALTER TABLE Dept ADD CONSTRAINT Dept_FK FOREIGN KEY (Mgr#)REFERENCES Emp (E#) INITIALLY DEFERRED DEFERRABLE;

Note that the foreign key constraints added to the above tables are of type“Initially deferred deferrable”. This implies that while inserting data, the check forcompliance of foreign key constraints will be deferred till the next COMMIT statement isexecuted. This will enable data entry into the two tables in any sequence, as long as theinformation in the two tables is compatible at the time of execution of next COMMITstatement.

5. Create tables on the following schema:-

Class (Year, Branch, Section, Strength)

Subject (Sub_Code, Title, Credits)

Faculty (Fac_Code, Fac_Name, Dept_Code)

Class_Room (Bldg_No, Room_No, Floor, Capacity)

Time_Slot ( Day, Period)

Praveen Kumar

Page 56: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

56

Time_Table (Year, Branch, Section, Day, Period, Sub_Code, Fac_Code, Bldg_No, Room_No)

The table Time_Table has following candidate keys:-

(Year, Branch, Section, Day, Period) Designated as Primary Key(Fac_Code, Day, Period)(Bldg_No, Room_No, Day, Period)

CREATE TABLE Class ( Year INT, Branch Char(3), Section INT, Strength INT,PRIMARY KEY (Year, Branch, Section),CHECK (Branch IN

(‘CSE’,’IT’,’ECE’,’IC’,’ME’,’EE’, ’MT’)),CHECK (Year BETWEEN 1 AND 4),CHECK (Section BETWEEN 1 AND 2));

CREATE TABLE Subject ( Sub_Code Char (7) PRIMARY KEY,Title Varchar (20) NOT NULL,Credits Int);

CREATE TABLE Faculty ( Fac_Code Char(3) PRIMARY KEY,Fac_Name Varchar (3) NOT NULL,Dept Char (4));

CREATE TABLE Class_Room ( Bldg_No Char(4), Room_No INT, Capacity INT,PRIMARY KEY (Bldg_No, Room_No ));

CREATE TABLE Time_Slot ( Day Char (4), Period INT,PRIMARY KEY (Day, Period),

CHECK (Day IN (‘Mon’, ’Tue’, ’Wed’, ’Thurs’, ‘Fri’, ‘Sat’)));

CREATE TABLE Time_Table ( Year INT, Branch Char(3), Section INT, Day Char(4), Period INT, PRIMARY KEY (Day, Period, Year, Branch, Section),

Bldg_No Char(4) NOT NULL, Room_No INT NOT NULL, Sub_Code Char (7) NOT NULL, Fac_Code Char(3) NOT NULL, UNIQUE (Day, Period, Bldg_No, Room_No), FOREIGN KEY (Year, Branch, Section)

REFERENCES Class (Year, Branch, Section),FOREIGN KEY (Sub_Code) REFERENCES Subject (Sub_Code),FOREIGN KEY (Fac_Code) REFERENCES Faculty (Fac_Code),FOREIGN KEY (Bldg_No, Room_No)

REFERENCES Class_Room (Bldg_No, Room_No),FOREIGN KEY (Day, Period) REFERENCES Time_Slot (Day, Period));

Praveen Kumar

Page 57: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

57

Creation of Indices

Since (Day, Period, Fac_Code) is a candidate key of Time_Table, we can create on this combination of the columns.

CREATE INDEX Fac_Indx ON Time_Table (Day, Period, Fac_Code);

Dropping of Tables

DROP TABLE Student;

Dropping of Constraints

Drop Constraint Emp_FK;

Dropping of Columns

ALTER TABLE Student DROP Column S_Name;

Dropping of Indices

DROP INDEX Fac_Indx;

How to drop the tables that reference each other?

Take the case of tables Emp and Dept. Suppose table Emp is to be dropped, the systemwould not permit this, since the dropping of Emp would violate the foreign key constraintDept_FK of table Dept. Dropping of Emp and Dept is achieved as follows:-

Step 1: First drop the constraints Emp_FK and Dept_FK.

DROP CONSTRAINT Emp_FK;DROP CONSTRAINT Dept_FK;

Step 2:Now drop the tables.

DROP TABLE Emp;DROP Table Dept;

Praveen Kumar

Page 58: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

58

DML

INSERTING INFORMATION INTO TABLES

1. Add a new customer to table Customer with C_Id = ‘C101’, C_Name = ‘Ajay’,C_Street =’S-26’ and C_City = ‘Noida’.

INSERT INTO Customer VALUES (‘C101’,’Ajay’, ‘S-26’, ‘Noida’);

Entering a NULL value

2. Add a new student to the Student Table with Roll_No = ‘091010120’, S_Name = ‘Vijay’, S_Address = ‘S-27 Noida’. (Note that information about S_DOB is missing. It is not a NOT NULL attribute, so it can be assigned a NULL value).

INSERT INTO Student VALUES (‘091010120’, ‘Vijay’, NULL, ‘S-27 Noida’);

The above NULL can also be inserted as follows (the attribute name S_DOB is omitted from the attribute list specified with the table name):-

INSERT INTO Student (S_Name, Roll_No, S_Address) VALUES (‘Vijay’,(‘091010120’, ‘S-27 Noida’);

Since attribute name S_DOB is not listed in the list of attributes listed with the tableStudent, NULL value will be assigned to this attribute. As indicated, the attributes can belisted in any order. Then the values have to specified in the same order.

RETRIEVING INFORMATION FROM TABLES

3. Get all rows of table Student.

SELECT *FROM Student;

Restricting rows with a WHERE Clause

4. Get the information of those students who are born in 1995.This query can be expressed in any of the following three forms:-

Praveen Kumar

Page 59: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

59

SELECT *FROM StudentWHERE S_DOB >= ’01-JAN-1995’ AND DOB <= ’31-DEC-1995’;

SELECT *FROM StudentWHERE S_DOB BETWEEN ’01-JAN-1995’ AND ’31-DEC-1995’;

SELECT *FROM StudentWHERE S_DOB LIKE ‘%95’;

Restricting Attributes List

5. Get Roll_No and DOB of all students born before 01st Jan 1995.

SELECT Roll_No, S_DOBFROM StudentWHERE S_DOB < ’01-JAN-1995’;

Use of Substitution Variables

Previous query can be recalled and re-executed by typing /. Suppose a query is to bereused with different parameters then parameters can be specified by substitutionvariables as follows:-

6. SELECT *FROM AccountWHERE AN = &numb;

Here numb is a substitution variable, whose value will be accepted by the system bydisplaying prompt ‘Enter Value for numb:’. Each time the query is executed, a differentvalue for numb can be entered like A101, A105 etc.

Retrieving information from more than one tables

7. Get the names of students who got more than 90 marks in any subject.

Here, we perform natural join of Result and Student and pick up names of those students who have scored more than 90 marks in any subject.

SELECT DISTINCT S_NameFROM Result, StudentWHERE Result.Roll_No = Student.Roll_No AND Marks > 90;

Praveen Kumar

Page 60: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

60

Since attribute name Roll_No appears in both the tables specified in the FROMclause, we need to qualify by the table name, while using this attribute name insubsequent clauses. However, this is not the problem with attribute Marks, since itappears only in table Result.

The qualifier DISTINCT has been used in the SELECT clause to avoid duplicates names from appearing in the result in the case of those students who have scored more than 90 marks in more than one subjects.

The above query can be expressed more elegantly by declaring a tuple variablesay R on the table Result and another tuple variable S on the table Student, asshown below:-

SELECT DISTINCT S_NameFROM Result R, Student SWHERE R.Roll_No = S.Roll_No AND Marks > 90;

8. Get the customer and account number of those customers, who are living in Noidabut having account in Delhi and have Balance more than 100000.

SELECT C_Name, D.ANFROM Customer C, Depositor D, Account A, Branch BWHERE C.C_Id = D.C_Id AND D.AN = A.AN AND A.B_Id = B.B_Id AND

C_City = ‘Noida’ AND B_City = ‘Delhi’ AND Bal > 100000;

9. Get the Roll_No of those students whose DOB is not specified in the Studenttable.

SELECT Roll_NoFROM StudentWHERE S_DOB IS NULL;

Using Aliases

10. SELECT C_Name AS Customer_Name, D.AN AS Account_NumberFROM Customer C, Depositor DWHERE C.C_Id = D.C_Id;

Here, the Attributes in the resulting table will be named as Customer_Name and Account_Number.

Using Concatenation in SELECT clause

11. SELECT C_Name|| ‘ has an account number ’ || D.ANFROM Customer C, Depositor DWHERE C.C_Id = D.C_Id;

Praveen Kumar

Page 61: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

61

Here each tuple output will be as follows:-

Ajay has an account number A101Vijay has an account number A310

Arithmetic Operations

12. Suppose there is a schema Emp (E_Id, E_Name, Basic_Pay, DA, HRA, Deduction). We can have query to determine gross salary of each employee:-

SELECT E_Id, Basic_Pay+ DA + HRA – Deduction AS Gross_SalaryFROM EMP;

Sorting the results

13. Get information in Result, ordered by Marks in Ascending Order.

SELECT *FROM ResultORDER BY Marks;

By default Order By clause will order in Ascending Order.

14. Get information in Result, ordered by Marks in Descending Order.

SELECT *FROM ResultORDER BY Marks DESC;

Use of special Attribute ROWNUM

15. Get information of top five employees Salary-wise.

SELECT ROWNUM, E#, E_Name, SalaryFROM ( SELECT E#, E_Name, Salary

FROM EmpORDER BY Salary DESC)

WHERE ROWNUM <= 5;

16. Get information of three accounts with highest balance.

SELECT ROWNUM, AN, BalFROM ( SELECT AN, Bal

FROM Account

Praveen Kumar

Page 62: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

62

ORDER BY Bal DESC)WHERE ROWNUM <=3;

Performing Aggregate Functions on the data

17. Get Min, Max, Total and Avg Marks in Result.

SELECT MIN (Marks), Max (Marks), SUM (Marks), AVG (Marks)FROM Result;

Performing Aggregate Functions on grouped rows

18. Get Min Balance, Max Balance and Total Balance at each branch.

SELECT B.B_Id, MIN (Bal), MAX(Bal), SUM(Bal)FROM Account A, Branch BWHERE A.B_Id = B.B_IdGROUP BY B.B_Id;

Restricting the Grouped Information using HAVING clause

19. Get the names and Total Marks of those students who have scored Average Marksmore than 80%.

SELECT S_Name, SUM (Marks)FROM Student S, Result RWhere S.Roll_No = R.Roll_NoGROUP BY S.Roll_NoHAVING AVG (Marks) > 80;

This will display total marks of each student having average score > 80%.

Outer Join of Tables

20. Perform Left Outer join of tables Depositor & Borrower

SELECT D.C_ID, AN, LNFROM Depositor D, Borrower BWHERE D.C_Id = B.C_Id (+);

All tuples of Depositor will appear in the result. Wherever, LN is not defined, itwill be indicated by NULL.

21. Perform Right Outer join of tables Depositor & Borrower

Praveen Kumar

Page 63: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

63

SELECT B.C_ID, AN, LNFROM Depositor D, Borrower BWHERE D.C_Id (+) = B.C_Id;

All tuples of Borrower will appear in the result. Wherever, AN is not defined, itwill be indicated by NULL.

Nested Queries with Independent sub-queries

22. Get the Customer Id and name of those customers who have both account andloan from the bank.

SELECT C.C_Id, C_NameFROM Custmer C, Depositor DWHERE C.C_Id = D.C_Id AND C_Id IN ( SELECT C_Id

FROM Borrower);

Here (SELECT C_Id FROM Borrower) is called inner sub-query and the main querySELECT C.C_Id, C_Name FROM Custmer C, Depositor D WHERE C.C_Id = D.C_IdAND C_Id IN ( ) is called outer query. The inner query can be evaluated independent ofthe outer query. Such a query is evaluated in two steps:-

(i) First evaluate the inner sub query and save its output.(j) Now evaluate the outer sub query wrt the result produced by inner

sub-query.

Evaluation of inner sub-query will produce a set of C_Id of those customers who have aloan from the bank. For each C_Id existing in the depositor table, the outer sub-query willexamine whether that C-Id exists in the set produced by inner sub-query. If the answer is“Yes” then that C_Id belongs to a customer having both account and loan and thecustomer’s name appears in the final output table.

23. Get names of the customers having joint account with customer Ajay.

SELECT CNFROM Customer C, Depositor DWHERE C.C_Id = D.C_Id AND CN <>’Ajay’

AND AN IN ( SELECT ANFROM Customer K, Depositor PWHERE K.C_Id = P.C_Id AND CN =’Ajay’);

The inner sub-query will produce set of Account Numbers held by custmer ‘Ajay’. Theouter sub-query will determine the other customers who are having an account held by‘Ajay’.

Praveen Kumar

Page 64: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

64

24. Get Branch Id and Name of the branch having highest average balance amongst all branches.

SELECT B.B_Id, B_Name FROM Account A, Branch BWHERE A.B_Id = B.B_IdGROUP BY B.B_IdHAVING AVG (Bal) = ( SELECT MAX(AVG(Bal))

FROM AccountGROUP BY B_Id);

Nested Queries with Correlated Sub-queries

Here, the inner sub-query is not independent of the outer sub-query. So, inner sub-query is evaluated for each tuple of the outer sub-query.

25. Get the names of the customers who have account in each branch located in Noida.

SELECT C_NameFROM Customer CWHERE NOT EXISTS (( SELECT B_Id

FROM Branch WHERE B_City = ‘Noida’)

MINUS ( SELECT B_Id FROM Account A, Depositor D

WHERE A.AN = D.AN AND D.C_Id = C.C_Id));Here the inner query is evaluated for each tuple C of table Customer being processed inthe outer query. The inner sub query produces the set difference of the set of B_Id ofbranches in Noida and the set of B_Id where customer C.C_Id has accounts. If this setproduced by the inner sub query is an empty set then the predicate NOT EXISTS of theouter sub query will be true and the customer name will appear in the result.

Updating of tables

26. UPDATE AccountSET Bal = &newbalWHERE AN = &an;

Praveen Kumar

Page 65: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

65

Deletion of tuples from Tables

26. DELETE Account WHERE AN = &an;

Creation of Views

27. CREATE VIEW AN_BNAS SELECT AN, B.B_Name

FROM Account A, Branch BWHERE A.B_Id = B.B_Id;

Retrieving information from Views

28. SELECT B_Name FROM AN_BN;

Dropping of Views

29. DROP VIEW AN_BN;

Praveen Kumar

Page 66: CHAPTER 3 RELATIONAL DATA MODEL Relational Database …

66

Praveen Kumar