0% found this document useful (0 votes)
25 views143 pages

Unit2 DrCSYadav

FJF

Uploaded by

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

Unit2 DrCSYadav

FJF

Uploaded by

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

Noida Institute of Engineering and Technology, Greater Noida

Content

RCS 501
Data Base Management System

Unit: 2

Relational data Model and Language


Dr C S Yadav
Prof. & Head, CSE
B.Tech. (CSE) 5th Sem

Dr C S Yadav KCS 501 DBMS Unit 2


1
09/13/2024
Content
Content

• Syllabus of Unit 2
• Relational Data Model- Basic Concepts
• Relational Schema
• Relational Instance
• Keys
– Super key
– Candidate Key
– Primary Key
– Alternate Key
– Foreign Key
• Relational Integrity Constraint
– Entity Integrity Constraint
– Referential Integrity Constraint
– Key Constraint
– Domain Constraint

09/13/2024 Dr C S Yadav KCS 501 DBMS Unit 2 2


Syllabus of Unit 2
Content

Relational data Model and Language: Relational Data Model


Concepts, Integrity Constraints, Entity Integrity, Referential
Integrity, Keys Constraints, Domain Constraints, Relational
Algebra, Relational Calculus, Tuple and Domain Calculus.
Introduction on SQL: Characteristics of SQL, Advantage of SQL.
SQl Data Type and Literals. Types of SQL Commands. SQL
Operators and Their Procedure. Tables, Views and Indexes.
Queries and Sub Queries. Aggregate Functions. Insert, Update
and Delete Operations, Joins, Unions, Intersection, Minus,
Cursors, Triggers, Procedures in SQL/PL SQL

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 3
Relational Data Model- Basic Concepts (CO1, CO2)
Content

 Represents the database as a collection of relations.

 A relation is nothing but a table of values

 Every row in the table represents a collection of related data


values.

 These rows in the table denote a real-world entity or


relationship.

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 4
Relational Data Model- Basic Concepts (CO1, CO2)
Content

Formally, given sets D1, D2, …. Dn a relation r is a subset of


r(R) is subset or equal to D1 x D2 x … x Dn
Thus, a relation is a set of n-tuples (a1, a2, …, an) where each ai  Di

Example: If
customer_name = {Rajeev, Sumit, Amit, Kaml, …}
customer_street = {S1, S2, S3, …}
customer_city = {Delhi, Kanpur, Noida, …}
Then r = {(Rajeev, S1, Delhi), (Sumit, S2, Kanpur),
(Amit, S2, Kanpur), (Kamal, S3 , Noida) }
is a relation over
customer_name x customer_street x customer_city
Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 5
Relational Data Model- Basic Concepts
Content (CO1, CO2)

 Each attribute of a relation has a name


 The set of allowed values for each attribute is called the
domain of the attribute
 Attribute values are (normally) required to be atomic; that is,
indivisible
 E.g. the value of an attribute can be an account number,
but cannot be a set of account numbers
 Domain is said to be atomic if all its members are atomic
 The special value null is a member of every domain
 The null value causes complications in the definition of many
operations
 We shall ignore the effect of null values in our main
presentation and consider their effect later
Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 6
Relational Data Model- Basic Concepts
Content (CO1, CO2)

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 7
Relational Data Model- Basic Concepts
Content (CO1, CO2)

Degree:
 The total number of attributes in the relation is
called the degree of the relation.

 For example,
Student has four attributes, or degree four.

Cardinality:
 Total number of rows(tuples) present in the Table.

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 8
Relation Schema
Content (CO1, CO2)

 A1, A2, …, An are attributes

 R = (A1, A2, …, An ) is a relation schema

Example:
Customer_schema = (customer_name, customer_street,
customer_city)

 r(R) denotes a relation r on the relation schema R


Example:
customer (Customer_schema)

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 9
Relation Instance
Content (CO1, CO2)

 The current values (relation instance) of a relation are


specified by a table

 An element t of r is a tuple, represented by a row in a table


attributes
(or columns)
customer_name customer_street customer_city

Jones Main Harrison


Smith North Rye tuples
Curry North Rye (or rows)
Lindsay Park Pittsfield

customer

Degree = 3, Cardinality =4

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 10
Relational Database
Content schema (CO1, CO2)

 A sets of relation schema.


 The example shows the database schema for COMPANY =
{EMPLOYEE, DEPARTMENT, DEPENDENT, PROJECT}
Relation

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 11
Keys Content(CO1, CO2)

Key is an attribute or more than one attribute of a


relation that determine the unique tuple (row) in a table
(relation).
R AXBXC
Let K  R Student(Rno, Sname, Dob)

K is a superkey of R if values for K are sufficient to


identify a unique tuple of each possible relation r(R)

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 12
Types of Key
Content (CO1, CO2)

 Super Key
 Candidate Key
 Primary Key
 Alternate Key
 Foreign key

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 13
Super Key
Content

 Super Key is an attribute or set of attribute by which


entities are distinguishable among set of entities.

 Key that uniquely identifies each record in the table

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 14
Candidate
Content key

 ¨ A candidate key is a minimal subset of superkey that


uniquely identifies each record in the table. ¨

 There can be more than one candidate keys in a


relation.
 Criteria for the candidate keys:
 It must contain unique values
 It must not contain null values
 It contains the minimum number of fields to ensure
uniqueness
 It must uniquely identify each record in the table

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 15
Primary
ContentKey

 ¨Is an attributes that uniquely identify each rows.


Each table must have primary key. ¨

 Cannot be NULL value to maintain Entity Integrity.


 Primary key is the one that officially declared as
the row identifier inside a specific table.

 ¨ Candidate keys for table Student: ¨


 Eg: studentID for Table Students

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 16
Alternate
Content key

 An alternate key is any candidate key that is not


primary key.

 Alternate keys are sometimes referred as secondary


keys.

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 17
Foreign Key
Content

A relation schema may have an attribute that corresponds to


the primary key of another relation. The attribute is called a
foreign key.
 E.g. customer_name and account_number attributes of
depositor are foreign keys to customer and account
respectively.
 Only values occurring in the primary key attribute of the
referenced relation may occur in the foreign key
attribute of the referencing relation.

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 18
Relational Integrity constraints (CO1, CO2)
Content

 Relational Integrity constraints is referred to conditions


which must be present for a valid relation.

 constraints. Constraints on the Relational database


management system is mostly divided into three main
categories are:
1. Domain constraints
2. Key constraints
3. Referential integrity constraints

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 19
EntityContent
integrity

 All Primary Key entries are unique, and no part of a


primary key may be NULL.
 Guarantee that each entity will have a unique identity
and ensures that for each key value can properly refer
primary key values.
 Examples
 STUDENT’s Roll No., no STUDENT can have a
duplicate Roll number, nor can it be NULL.
 All students are UNIQUELY identified by their
roll number.

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 20
Referential integrity
Content

 Referential integrity constraints is base on the concept


of Foreign Keys.

 A foreign key is an important attribute of a relation


which should be referred to in other relationships.

 The enforcement of the referential integrity rules


makes it impossible to delete a row in one table whose
primary keys has mandatory matching foreign key
values on another table.

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 21
Referential integrity
Content -Example

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 22
Key constraints
Content

 An attribute that can uniquely identify a tuple in a


relation is called the key of the table.

 The value of the attribute for different tuples in the


relation has to be unique.
Example:
In the given table, CustomerID is a key attribute of Customer Table.
CustomerID =1 is only for the CustomerName =" Google".

CustomerID CustomerName Status


1 Google Active
2 Amazon Active
3 Apple Inactive

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 23
DomainContent
Constraints
 Domain constraints can be violated if an attribute
value is not appearing in the corresponding domain or
it is not of the appropriate data type.

 Domain constraints specify that within each tuple, and


the value of each attribute must be unique.

 This is specified as data types which include standard


data types integers, real numbers, characters,
Booleans, variable length strings, etc.

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 24
Noida Institute of Engineering and Technology, Greater Noida
Content

KCS 501
Data Base Management System

Unit: 2

Relational Algebra
Dr C S Yadav
Prof & Head CSE
B.Tech. (CSE) 5th Sem

Dr C S Yadav KCS 501 DBMS Unit 2


25
09/13/2024
Content
Content

• Relational Algebra – Operations


• Example Query
• Relational Algebra Expression
• Join Operation
• Modification of the Database
• Relational Calculus
– Tuple Relational Calculus
– Domain Relational Calculus
• Safe Expression

09/13/2024 Dr C S Yadav KCS 501 DBMS Unit 2 26


Relational Algebra-
Content (CO1, CO2)

 Procedural language
 Six basic operators
 select: 
 project: 
 union: 
 set difference: –
 Cartesian product: x
 rename: 
 The operators take one or two relations as inputs and
produce a new relation as a result.
Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 27
Select Operation: 
Content (CO1, CO2)

 Relation r
A B C D

  1 7
  5 7
  12 3
  23 10

A=B ^ D > 5 (r)


A B C D

  1 7
  23 10

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 28
Select Operation: 
Content (CO1, CO2)

Notation:  p(r)
p is called the selection predicate

Defined as:

p(r) = {t | t  r and p(t)}


Where p is a formula in propositional calculus
consisting of terms connected by :  (and),  (or),  (not)
Each term is one of:
<attribute> op <attribute> or <constant>
where op is one of: =, , >, ,<, 
Example of selection:

 branch_name=“Noida”(account)

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 29
Project Operation-
Content  (CO1, CO2)

 Relation r: A B C

 10 1
 20 1
 30 1
 40 2

A,C (r) A C A C

 1  1
 1 =  1
 1  2
 2

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 30
Project Operation-
Content  (CO1, CO2)

 Notation:
 A1 , A2 ,, Ak (r )

where A1, A2 are attribute names and r is a relation name.


 The result is defined as the relation of k columns obtained
by erasing the columns that are not listed
 Duplicate rows removed from result, since relations are
sets
 Example: To eliminate the branch_name attribute of
account

account_number, balance (account)

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 31
Union Operation
Content (CO1, CO2)

• Notation: r  s
• Defined as:
r  s = {t | t  r or t  s}
• For r  s to be valid.
1. r, s must have the same arity (same number of
attributes)
2. The attribute domains must be compatible
• Example: to find all customers with either an account or a
loan
customer_name (depositor)  customer_name (borrower)

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 32
Union Operation
Content (CO1, CO2)

• Notation: r  s
• Defined as:
r  s = {t | t  r or t  s}
• For r  s to be valid.
1. r, s must have the same arity (same number of
attributes)
2. The attribute domains must be compatible
• Example: to find all customers with either an account or a
loan
customer_name (depositor)  customer_name (borrower)

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 33
Set DifferenceContent
Operation (CO1, CO2)

• Notation r – s
• Defined as:
r – s = {t | t  r and t  s}

• Set differences must be taken between Union compatible


relations.
– r and s must have the same arity
– attribute domains of r and s must be compatible

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 34
Cartesian-Product Operation(CO1, CO2)
Content

 Relations r, s:
A B C D E

 1  10 a
 10 a
 2  20 b
r  10 b
s
 r x s:
A B C D E Defined as:
Notation  1  10 a
 1  10 a
rxs  1  20 b r x s = {t q | t  r and q  s}
 1  10 b
 2  10 a
 2  10 a
 2  20 b
 2  10 b

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 35
Set-IntersectionContent
Operation (CO1, CO2)

• Notation: rs A B A B
 1  2
• Defined as:  2  3
 1

r s
r  s = { t | t  r and t  s }
• Assume:
– r, s have the same arity A B

– attributes of r and s are compatible  2

• Note: r  s = r – (r – s)

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 36
Composition ofContent
Operations (CO1, CO2)
Can build expressions using multiple operations
Example: A=C(r x s) A B C D E
rxs  1  10 a
 1  10 a
 1  20 b
 1  10 b
 2  10 a
 2  10 a
 2  20 b
 2  10 b

A=C(r x s)
A B C D E
 1  10 a
 2  10 a
 2  20 b

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 37
Rename Operation
Content (CO1, CO2)

• Allows us to name, and therefore to refer to, the results of


relational-algebra expressions.
• Allows us to refer to a relation by more than one name.
• Example:
 x (E)

returns the expression E under the name X


• If a relational-algebra expression E has arity n, then
 x ( A ,A
1 2 ,...,An ) (E )

returns the result of expression E under the name X, and with


the
attributes renamed to A1 , A2 , …., An .
Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 38
Banking Example
Content (CO1, CO2)

branch (branch_name, branch_city, assets)

customer (customer_name, customer_street, customer_city)

account (account_number, branch_name, balance)

loan (loan_number, branch_name, amount)

depositor (customer_name, account_number)

borrower (customer_name, loan_number)

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 39
Example Queries
Content (CO1, CO2)

• Find all loans of over $1200

amount > 1200 (loan)

 Find the loan number for each loan of an amount greater


than $1200

loan_number (amount > 1200 (loan))

 Find the names of all customers who have a loan, an


account, or both, from the bank
customer_name (borrower)  customer_name (depositor)

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 40
Example
Content
(CO1, CO2)

 Find the names of all customers who have a loan at the


Perryridge branch.
customer_name (branch_name=“Perryridge”

(borrower.loan_number = loan.loan_number(borrower x loan)))


 Find the names of all customers who have a loan at the
Perryridge branch but do not have an account at any branch
of the bank.

customer_name (branch_name = “Perryridge”

(borrower.loan_number = loan.loan_number(borrower x loan))) –

customer_name(depositor)

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 41
Relational Algebraic Expression (CO1, CO2)
Content

• A basic expression in the relational algebra consists of either one


of the following:
– A relation in the database
– A constant relation
• Let E1 and E2 be relational-algebra expressions; the following are
all relational-algebra expressions:
– E1  E2
– E1 – E2
– E1 x E2
– p (E1), P is a predicate on attributes in E1
– s(E1), S is a list consisting of some of the attributes in E1
–  x (E1), x is the new name for the result of E1
Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 42
Relational Algebraic Expression (CO1, CO2)
Content

• A basic expression in the relational algebra consists of either one


of the following:
– A relation in the database
– A constant relation
• Let E1 and E2 be relational-algebra expressions; the following are
all relational-algebra expressions:
– E1  E2
– E1 – E2
– E1 x E2
– p (E1), P is a predicate on attributes in E1
– s(E1), S is a list consisting of some of the attributes in E1
–  x (E1), x is the new name for the result of E1
Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 43
Joins
Content
(CO1, CO2)

A Join operation combines related tuples from different


relations, if and only if a given join condition is satisfied.

Dr C S Yadav KCS 501 DBMS


09/13/2024 Unit 2 44
Joins
Content
(CO1, CO2)

A Join operation combines related tuples from different


relations, if and only if a given join condition is satisfied.

Join
Inner Outer
Join Join

Natur Theta Equi Left Outer Right Outer Full Outer


al Join Join Join Join Join Join

Dr C S Yadav KCS 501 DBMS


09/13/2024 Unit 2 45
Natural-Join Operation
Content (CO1, CO2)

 Notation: r s
• Let r and s be relations on schemas R and S respectively.
• A natural join is the set of tuples of all combinations in R
and S that are equal on their common attribute names.
• It is denoted by ⋈.
• Example:
R = (A, B, C, D)
S = (E, B, D)
– Result schema = (A, B, C, D, E)
– r s is defined as:
r.A, r.B, r.C, r.D, s.E (r.B = s.B  r.D = s.D (r x s))

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 46
Natural-Join Operation
Content (CO1, CO2)

 Notation: r s

A B C D B D E

 1   a 1 a 
 2  a 3 a 
 4  b 1 a 
 1  a 2 b 
 2  b 3 b 
r s

 r s
A B C D E
 1  a 
 1  a 
 1  a 
 1  a 
 2  b 
Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 47
Theta (θ) Content
Join (CO1, CO2)

 Theta join combines tuples from different relations


provided they satisfy the theta condition.

R1 ⋈θ R2
 The join condition is denoted by the symbol θ.

STUDENT ⋈Student.Std = Subject.Class


SUBJECT
Student_detail
Student Subjects SID Name Std Class Subject
Class Subject
SID Name Std 101 Alex 10 10 Math
10 Math
101 Alex 10 10 English
101 Alex 10 10 English
102 Maria 11 11 Music
102 Maria 11 11 Music
11 Sports 102 Maria 11 11 Sports

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 48
Equijoin
Content
(CO1, CO2)

When Theta join uses only equality comparison


operator, it is said to be equijoin. The above example
corresponds to equijoin.

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 49
Outer Joins
Content(CO1, CO2)

 Theta Join, Equijoin, and Natural Join are called inner joins

 An inner join includes only those tuples with matching


attributes and the rest are discarded in the resulting relation.
 Therefore, we need to use outer joins to include all the
tuples from the participating relations in the resulting
relation.
 There are three kinds of outer joins
 − left outer join, R S

 right outer join, and R S

 full outer join. R S

Dr C S Yadav KCS 501 DBMS Unit 2

09/13/2024 50
Modification of the Database
Content (CO1, CO2)

• The content of the database may be modified using


the following operations:
– Deletion
– Insertion
– Updating
• All these operations are expressed using the
assignment operator.

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 51
Modification of the Database
Content (CO1, CO2)

• The content of the database may be modified using the following


operations:
– Insertion
– in relational algebra, an insertion is expressed by:
r r  E
where r is a relation and E is a relational algebra expression.
– Deletion
– A deletion is expressed in relational algebra by:
rr–E
where r is a relation and E is a relational algebra query.
– Updating
• Use the generalized projection operator to do this task
r  F ,F ,,F , (r )
1 2 l

• All these operations are expressed using the assignment operator.

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 52
Relational Calculus
Content (CO1, CO2)

 Relational calculus is a non-procedural query


language.
 In the non-procedural query language, the user only
focus on what is required and specify that things and
does not focus on how to obtain this.
 Specify the queries in a declarative way
 It uses the predicate calculus

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 53
Tuple Relational Calculus(TRC)
Content (CO1, CO2)

• The tuple relational calculus is specified to select the


tuples in a relation for which predicate is true.
• Notation
• {t | P (t)} or {t | Condition (t)}
– Where t is tuple Variable and P(t) is predicate
or condition used to fetch t
• The calculus is dependent on the use of tuple variables.
• A tuple variable is a variable that 'ranges over' a named
relation: i.e., a variable whose only permitted values are
tuples of the relation.

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 54
Domain Relational Calculus
Content (DRC) (CO1, CO2)

 In domain relational calculus, filtering variable uses the


domain of attributes.
 Domain relational calculus uses the same operators as tuple
calculus

A domain relational calculus expression has the following


general format:

{d1, d2, . . . , dn | P(d1, d2, . . . , dm)}


m≥n
where d1, d2, . . . , dn, . . . , dm stand for domain
variables and P(d1, d2, . . . , dm) stands for a predicate
formula composed of atoms.
Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 55
TRC and Content
DRC (CO1, CO2)

Consider the Schema:


employee (E-name, street, city)
works _for (E-name, company_name, salary)
company (company-name, city)
manages (E-name, manager-name)
Give TRC and DRC
(a) Find names of employees working for Capgemini.
TRC: { t | ∃ u ∈ works-for ( t[E-name] = u [E-name] ∧
u[company-name] = 'Capgemini' )}

DRC: { < en > | ∃ sal ( < en , “Capgemini” , sal> ∈ works-for) }

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 56
TRC and Content
DRC (CO1, CO2)

(b) Find the names and the cities of residence of


employees working for TCS.

TRC: { t | ∃ u ∈ works-for ( t[E-name] = u [E-name]


∧ u[company-name] = 'TCS'∧ ∃ v ∈ employee ( v[E-
name] = u [E-name] ∧ t[city] = v [city] ))}

DRC: { < en, city > |∃ sal ( < en , 'TCS' , sal>∈ works-
for
∧ ∃ st ( < en , st , city> ∈ employee )) }
Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 57
TRC andContent
DRC (CO1, CO2)

(c) Find name, street and city of residence of


employees working for Infosys and earning more than
40,000.
TRC: { t | ∃ u ∈ works-for ( t[E-name] = u [E-name] ∧
u[company-name] ='infosys' ∧ u[salary] > 40000
∧ ∃ v ∈ employee ( v[E-name] = u [E-name] ∧ t[street] =
v [street] ∧ t[city] = v [city] ))}

DRC: { < en, st, city > |< en , st , city> ∈ employee


∧ ∃ salary ( < en , 'Infosys' , salary> ∈ works-for ∧ salary
> 40000 )}
Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 58
TRC andContent
DRC (CO1, CO2)

(d) Find names of employees working in the same


city where they live.
TRC: { t | ∃ u ∈ employee ( t[E-name] = u [E-name]
∧ ∃ v ∈ works-for ( v[E-name] = u [E-name]
∧ ∃ w ∈ company ( w[company-name] = v [company-
name] ∧ w[city] = u [city] ))) }

DRC: { < en > |∃ st, city ( < en , st , city> ∈ employee


∧ ∃ cn, salary ( < en , cn , salary> ∈ works-for
∧ < cn, city > ∈ company ))}
Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 59
TRC and Content
DRC (CO1, CO2)

(e) Find the names of employees, who are not


working for WIPRO
TRC: { t | ∃ u ∈ employee ( t[E-name] = u [E-
name])
∧ ¬ ∃ v ∈ works-for ( t[E-name] = v [E-name]
∧ v[company-name] = “WIPRO” )}

DRC: { < en > | ∃ st, city ( < en , st , city> ∈


employee )
∧ ¬ ∃ sal ( <en, “WIPRO”, sal> ∈ works-for )}
Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 60
TRC and Content
DRC (CO1, CO2)

Problem: Let there be schemas R(A,B,C) and


S(D,E,F) and relations r(R) and s(S). Give
expressions in TRC equivalent to the following
expression in RA.
(i) RA: (r)

TRC:

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 61
TRC and Content
DRC (CO1, CO2)

Problem: Let there be schemas R(A,B,C) and


S(D,E,F) and relations r(R) and s(S). Give
expressions in TRC equivalent to the following
expression in RA.
(i) RA: (r)

TRC:

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 62
TRC and Content
DRC (CO1, CO2)

Problem: Let there be schemas R(A,B,C) and


S(D,E,F) and relations r(R) and s(S). Give
expressions in TRC equivalent to the following
expression in RA.
(i) RA:

TRC:

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 63
TRC and Content
DRC (CO1, CO2)

Problem: Let there be schemas R(A,B,C) and


S(D,E,F) and relations r(R) and s(S). Give
expressions in TRC equivalent to the following
expression in RA.
(i) RA: ((r

TRC:

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 64
TRC and Content
DRC (CO1, CO2)

Problem: Let there be schemas R(A,B,C)


relations (R) and (R). Give expressions in DRC
equivalent to the following expression in RA.
(i) RA: ()

DRC:

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 65
TRC and Content
DRC (CO1, CO2)

Problem: Let there be schemas R(A,B,C)


relations (R) and (R). Give expressions in DRC
equivalent to the following expression in RA.

(i) RA: ()

DRC:

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 66
TRC and Content
DRC (CO1, CO2)

Problem: Let there be schemas R(A,B,C)


relations (R) and (R). Give expressions in DRC
equivalent to the following expression in RA.

(i) RA:

DRC:

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 67
TRC and Content
DRC (CO1, CO2)

Problem: Let there be schemas R(A,B,C)


relations (R) and (R). Give expressions in DRC
equivalent to the following expression in RA.

(i) RA:

DRC:

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 68
TRC and Content
DRC (CO1, CO2)

Problem: Let there be schemas R(A,B,C)


relations (R) and (R). Give expressions in DRC
equivalent to the following expression in RA.

(i) RA:

DRC:

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 69
TRC and Content
DRC (CO1, CO2)

Problem: Let there be schemas R(A,B,C)


relations (R) and (R). Give expressions in DRC
equivalent to the following expression in RA.

(i) RA: ()*()

DRC:

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 70
Tuple Relational Calculus-
Content Example (CO1, CO2)

• Let Employee(EID, ENAME, Gender, Age, Salary, Dno) is a


relational schema
• Q. write the tuple relational calculus to find the all
employee whose salary is greater than Rs 10000.
– {t | Employee(t) and t.salary > 10000}

Q. write the tuple relational calculus to find the name ,id


and gender of employee whose salary is greater than Rs
10000.
• {t.Ename, t.eid, t.gender | Employee(t) and t.salary >
10000}

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 71
AN ATOM in TRC
Content (CO1, CO2)

 R(t) is an atom in TRC where R is a relation and t is a tuple


variable ranges in R
 t.A op t.B is an atom where op ={>,<,>=,<=,=,<> } and A is
an attribute of a relation R on which t ranges while B is an
attribute of relation R on which t ranges
 c op t.A or t.B op c is an atom in TRC where op
={>,<,>=,<=,=,<> } and c is constant

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 72
The Existential and Universal Quantifiers
Content
(CO1, CO2)

 is called the universal or “for all” quantifier


 is called the existential or “there exists” quantifier

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 73
Database State for COMPANY
Content (CO1, CO2)

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 74
QueryContent
(CO1, CO2)

• Write the TRC to retrieve the name and address of all


employees who work for the ‘Research’ department.

{t.FNAME, t.LNAME, t.ADDRESS | EMPLOYEE(t) and (


d) (DEPARTMENT(d) and d.DNAME=‘Research’ and
d.DNUMBER=t.DNO) }
• Write the TRC to Find the names of employees who
work on all the projects controlled by department
number 5. The query can be:

{e.LNAME, e.FNAME | EMPLOYEE(e) and ( ( x)


(not(PROJECT(x)) or not(x.DNUM=5)OR ( ( w)
(WORKS_ON(w) and w.ESSN=e.SSN and
x.PNUMBER=w.PNO))))}
Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 75
QueryContent
(CO1, CO2)

• Write DRC to retrieve the birthdate and address of the


employee whose name is ‘John B. Smith’.
• Query :

{uv | ( q) ( r) ( s) ( t) ( w) ( x) ( y) ( z)
(EMPLOYEE(qrstuvwxyz) and q=’John’ and r=’B’ and
s=’Smith’)} }

• Write DRC to select TCHR_ID and TCHR_NAME of


teachers who work for department 10,

{<tchr_id, tchr_name> | Teacher(tchr_id, tchr_name,


dept_id, age address) Λ DEPT_ID = 10}
Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 76
Safety of Expression
Content (CO1, CO2)

A SAFE EXPRESSION is one that is guaranteed to yield a


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

{ t | (tEMPLOYEE) }
This is UNSAFE expression in tuple relational calculus!

{<l, b, a> | }

This is unsafe expression in domain relational calculus

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 77
Noida Institute of Engineering and Technology, Greater Noida
Content

KCS 501
Data Base Management System

Unit: 2

Introduction to SQL
Dr C S Yadav
Prof & Head CSE
B.Tech. (CSE) 5th Sem

Dr C S Yadav KCS 501 DBMS Unit 2


78
09/13/2024
Contents
Content

• Introduction to SQL
• Data Definition
• Basic Query Structure
• Set Operations
• Aggregate Functions
• Null Values
• Nested Subqueries
• Complex Queries
• Views
• Modification of the Database
• Joined Relations

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 79
Introduction on SQL:
Content (CO3)

• IBM Sequel language developed as part of System R


project at the IBM San Jose Research Laboratory
• Renamed Structured Query Language (SQL)
• ANSI and ISO standard SQL:
– SQL-86
– SQL-89
– SQL-92
– SQL:1999 (language name became Y2K compliant!)
– SQL:2003
• Commercial systems offer most, if not all, SQL-92 features,
plus varying feature sets from later standards and special
proprietary features.
– Not all examples here may work on your particular system.

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 80
Data Definition Language
Content (CO3)

Allows the specification of not only a set of relations but also


information about each relation, including:

• The schema for each relation.


• The domain of values associated with each attribute.
• Integrity constraints
• The set of indices to be maintained for each relations.
• Security and authorization information for each
relation.
• The physical storage structure of each relation on disk

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 81
Domain Types in SQL
Content (CO3)

• char(n). Fixed length character string, with user-specified


length n.
• varchar(n). Variable length character strings, with user-
specified maximum length n.
• int. Integer (a finite subset of the integers that is machine-
dependent).
• smallint. Small integer (a machine-dependent subset of the
integer domain type).
• numeric(p,d). Fixed point number, with user-specified precision
of p digits, with n digits to the right of decimal point.
• real, double precision. Floating point and double-precision
floating point numbers, with machine-dependent precision.
• float(n). Floating point number, with user-specified precision of
at least n digits.

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 82
Create TableContent
Construct (CO3)

• An SQL relation is defined using the create table command:


create table r (A1 D1, A2 D2, ..., An Dn,
(integrity-constraint1),
...,
(integrity-constraintk))
– r is the name of the relation
– each Ai is an attribute name in the schema of relation r
– Di is the data type of values in the domain of attribute Ai

• Example:
create table branch
(branch_name char(15) not null,
branch_city char(30),
assets integer)

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 83
Integrity Constraints in Create Table (CO3)
Content

• not null
• primary key (A1, ..., An )

Example: Declare branch_name as the primary key for branch


.
create table branch
(branch_name char(15),
branch_city char(30),
assets integer,
primary key (branch_name))

primary key declaration on an attribute automatically ensures


not null in SQL-92 onwards, needs to be explicitly stated in
SQL-89

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 84
Drop and Alter Table
ContentConstructs (CO3)

• The drop table command deletes all information about the


dropped relation from the database.
• The alter table command is used to add attributes to an
existing relation:
alter table r add A D
where A is the name of the attribute to be added to
relation r and D is the domain of A.
– All tuples in the relation are assigned null as the value for the
new attribute.
• The alter table command can also be used to drop
attributes of a relation:
alter table r drop A
where A is the name of an attribute of relation r
– Dropping of attributes not supported by many databases
Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 85
Basic Query Structure
Content (CO3)

• SQL is based on set and relational operations with certain


modifications and enhancements
• A typical SQL query has the form:

select A1, A2, ..., An


from r1, r2, ..., rm
where P

– Ai represents an attribute
– ri represents a relation
– P is a predicate.
• This query is equivalent to the relational algebra expression.

• The result of an SQL query is a relation.


Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 86
The select Clause (CO3)
Content

• The select clause list the attributes desired in the result of a


query
– corresponds to the projection operation of the relational
algebra
• Example: find the names of all branches in the loan relation:
select branch_name
from loan
• In the relational algebra, the query would be:
branch_name (loan)
• NOTE: SQL names are case insensitive (i.e., you may use
upper- or lower-case letters.)
– E.g. Branch_Name ≡ BRANCH_NAME ≡ branch_name
– Some people use upper case wherever we use bold font.
Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 87
The select Clause
Content(Cont.) (CO3)

• SQL allows duplicates in relations as well as in query results.


• To force the elimination of duplicates, insert the keyword
distinct after select.
• Find the names of all branches in the loan relations, and
remove duplicates
select distinct branch_name
from loan

• The keyword all specifies that duplicates not be removed.

select all branch_name


from loan

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 88
The select Clause
Content(Cont.) (CO3)

• An asterisk in the select clause denotes “all attributes”


select *
from loan
• The select clause can contain arithmetic expressions
involving the operation, +, –, , and /, and operating on
constants or attributes of tuples.
• The query:
select loan_number, branch_name, amount  100
from loan
would return a relation that is the same as the loan
relation, except that the value of the attribute amount is
multiplied by 100.

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 89
The where Clause (CO3)
Content

• The where clause specifies conditions that the result must


satisfy
– Corresponds to the selection predicate of the relational
algebra.
• To find all loan number for loans made at the Perryridge
branch with loan amounts greater than $1200.
select loan_number
from loan
where branch_name = 'Perryridge' and amount > 1200
• Comparison results can be combined using the logical
connectives and, or, and not.
• Comparisons can be applied to results of arithmetic
expressions.
Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 90
The where Clause (CO3)
Content

• SQL includes a between comparison operator


• Example: Find the loan number of those loans with loan
amounts between $90,000 and $100,000 (that is, $90,000 and
$100,000)

• Select loan_number from loan where amount between 90000


and 100000;

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 91
The from Clause (CO3)
Content

• The from clause lists the relations involved in the query


– Corresponds to the Cartesian product operation of the
relational algebra.
• Find the Cartesian product borrower X loan
select 
from borrower, loan
 Find the name, loan number and loan amount of all
customers having a loan at the Perryridge branch.
select customer_name, borrower.loan_number, amount
from borrower, loan
where borrower.loan_number = loan.loan_number and
branch_name = 'Perryridge'

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 92
Set Operations
Content (CO3)

• The set operations union, intersect, and except operate


on relations and correspond to the relational algebra
operations 
• Each of the above operations automatically eliminates
duplicates; to retain all duplicates use the corresponding
multiset versions union all, intersect all and except all.

Suppose a tuple occurs m times in r and n times in s,


then, it occurs:
– m + n times in r union all s
– min(m,n) times in r intersect all s
– max(0, m – n) times in r except all s

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 93
Set Operations
Content (CO3)

• Find all customers who have a loan, an account, or both:


(select customer_name from depositor)
union
(select customer_name from borrower)
 Find all customers who have both a loan and an account.
(select customer_name from depositor)
intersect
(select customer_name from borrower)
 Find all customers who have an account but no loan.
(select customer_name from depositor)
except
(select customer_name from borrower)

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 94
AggregateContent
Functions (CO3)

• These functions operate on the multiset of values of a


column of a relation, and return a value
avg: average value
min: minimum value
max: maximum value
sum: sum of values
count: number of values

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 95
AggregateContent
Functions (CO3)

• Find the average account balance at the Perryridge branch.

select avg (balance)


from account
where branch_name = 'Perryridge'
 Find the number of tuples in the customer relation.

select count (*)


from customer
 Find the number of depositors in the bank.

select count (distinct customer_name)


from depositor

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 96
Aggregate Functions – Having Clause(CO3)
Content

• Find the names of all branches where the average account


balance is more than $1,200.
select branch_name, avg (balance)
from account
group by branch_name
having avg (balance) > 1200

Note: predicates in the having clause are applied after the


formation of groups whereas predicates in the
where clause are applied before forming groups

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 97
Null Values
Content (CO3)

• It is possible for tuples to have a null value, denoted by null,


for some of their attributes
• null signifies an unknown value or that a value does not exist.
• The predicate is null can be used to check for null values.
– Example: Find all loan number which appear in the loan
relation with null values for amount.
select loan_number
from loan
where amount is null
• The result of any arithmetic expression involving null is null
– Example: 5 + null returns null
• However, aggregate functions simply ignore nulls
– More on next slide
Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 98
Null Values
Content (CO3)

• Any comparison with null returns unknown


– Example: 5 < null or null <> null or null = null
• Three-valued logic using the truth value unknown:
– OR: (unknown or true) = true,
(unknown or false) = unknown
(unknown or unknown) = unknown
– AND: (true and unknown) = unknown,
(false and unknown) = false,
(unknown and unknown) = unknown
– NOT: (not unknown) = unknown
– “P is unknown” evaluates to true if predicate P
evaluates to unknown

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 99
Example Query (CO3)
Content

• Find all customers who have both an account and a loan


at the bank.
select distinct customer_name
from borrower
where customer_name in (select customer_name
from depositor )
 Find all customers who have a loan at the bank but do
not have an account at the bank

select distinct customer_name


from borrower
where customer_name not in (select customer_name
from depositor )
Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 100
ExampleContent
Query (CO3)

• Find all customers who have both an account and a loan at


the Perryridge branch

select distinct customer_name


from borrower, loan
where borrower.loan_number = loan.loan_number and
branch_name = 'Perryridge' and
(branch_name, customer_name ) in
(select branch_name, customer_name
from depositor, account
where depositor.account_number =
account.account_number )

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 101
Views
Content
(CO3)

• A view provides a mechanism to hide certain data from the


view of certain users.
• Any relation that is not of the conceptual model but is
made visible to a user as a “virtual relation” is called a
view.

• A view is defined using the create view statement which


has the form
create view v as < query expression >
where <query expression> is any legal SQL expression. The
view name is represented by v.
• Once a view is defined, the view name can be used to refer
to the virtual relation that the view generates.
Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 102
Types of Views (CO3)
Content

• Updatable view
• Non-updatable View

• Simple views are generally updatable views. We can


perform DML operations over base table through this view.
• Complex views are generally non-updatable views. We can
not perform DML operations on base tables through these
types of views.

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 103
ExampleContent
Queries (CO3)

• A view consisting of branches and their customers


create view all_customer as
(select branch_name, customer_name
from depositor, account
where depositor.account_number =
account.account_number )
union
(select branch_name, customer_name
from borrower, loan
where borrower.loan_number = loan.loan_number )
 Find all customers of the Perryridge branch
select customer_name
from all_customer
where branch_name = 'Perryridge'
Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 104
Modification of the Content
Database – Deletion (CO3)

• Delete all account tuples at the Perryridge branch


delete from account
where branch_name = 'Perryridge'

• Delete all accounts at every branch located in the


city ‘Needham’.
delete from account
where branch_name in (select branch_name
from branch
where branch_city = 'Needham')

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 105
Modification of the Content
Database – Insertion (CO3)

• Add a new tuple to account


insert into account
values ('A-9732', 'Perryridge', 1200)

or equivalently

insert into account (branch_name, balance, account_number)


values ('Perryridge', 1200, 'A-9732')

• Add a new tuple to account with balance set to null


insert into account
values ('A-777','Perryridge', null )

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 106
Modification of theContent
Database – Updates(CO3)

• Increase all accounts with balances over $10,000 by 6%, all


other accounts receive 5%.
– Write two update statements:
update account
set balance = balance  1.06
where balance > 10000

update account
set balance = balance  1.05
where balance  10000
– The order is important
– Can be done better using the case statement

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 107
Update of a View
Content (CO3)

• Create a view of all loan data in the loan relation, hiding


the amount attribute
create view loan_branch as
select loan_number, branch_name
from loan
• Add a new tuple to branch_loan
insert into branch_loan
values ('L-37‘, 'Perryridge‘)
This insertion must be represented by the insertion of
the tuple
('L-37', 'Perryridge', null )
into the loan relation

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 108
Join
Content
(CO3)

• Join operations take two relations and return as a result


another relation.
• These additional operations are typically used as subquery
expressions in the from clause
• Join condition – defines which tuples in the two relations
match, and what attributes are present in the result of the
join.
• Join type – defines how tuples in each relation that do not
match any tuple in the other are treated.

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 109
IndexContent
in SQL (CO3)
Indexes (Indices) are optional structures associated with
tables.
We can create indexes explicitly to speed up SQL statement
execution on a table.
Index points directly to the location of the rows containing
the value.
Syntax of creating index is create index ind_emp on
emp(salary);

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 110
Types ofContent
Indexes (CO3)
 Simple index: Index on single column
 Composite index: Index on multiple column
 Unique Index: Index on unique column
 Reverse Index: Index on column which values are arranged
in descending order
 Function Index: Index on the function which we apply on
column
 Bitmap Index: Column values are mapped in 0 or 1.

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 111
Advantages and Disadvantages
Content using Indexes(CO3)

Advantages:
Their use in queries usually results in much better performance.
They make it possible to quickly retrieve (fetch) data.
They can be used for sorting
Disadvantages:
There is some overhead to an index.
The index itself occupies space on disk and memory.
Too many indexes could be a problem.
The index needs to be maintained after performing DML
operations
Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 112
PL/SQL Introduction
Content (CO3)

PL/SQL stands for "Procedural Language extensions to the


Structured Query Language.“

PL/SQL is a block structured language that enables


developers to combine the power of SQL with procedural
statements.

All the statements of a block are passed to oracle engine


all at once which increases processing speed and decreases
the traffic.

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 113
Disadvantages of SQL:
Content (CO3)

 SQL doesn’t provide the programmers with a technique of


condition checking, looping and branching.
 SQL statements are passed to Oracle engine one at a time
which increases traffic and decreases speed.
 SQL has no facility of error checking during manipulation of
data.

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 114
Features of PL/SQL:
Content (CO3)

 PL/SQL is basically a procedural language, which provides the


functionality of decision making, iteration and many more features of
procedural programming languages.
 PL/SQL can execute a number of queries in one block using single
command.
 One can create a PL/SQL unit such as procedures, functions,
packages, triggers, and types, which are stored in the database for
reuse by applications.
 PL/SQL provides a feature to handle the exception which occurs in
PL/SQL block known as exception handling block.
 Applications written in PL/SQL are portable to computer hardware or
operating system where Oracle is operational.
 PL/SQL Offers extensive error checking.
Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 115
Differences between SQL and PL/SQL (CO3)
Content

SQL PL/SQL

SQL is a single query that is used PL/SQL is a block of codes that


to perform DML and DDL used to write the entire program
operations. blocks/ procedure/ function etc.
it is declarative, that defines what PL/SQL is procedural that defines
needs to be done, rather than how the things needs to be done.
how things need to be done.
Execute as a single statement. Execute as a whole block.
Mainly used to manipulate data. Mainly used to create an
application.
Cannot contain PL/SQL code in it. It is an extension of SQL, so it can
contain SQL inside it.

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 116
Structure of PL/SQL
Content Block: (CO3)

 The basic unit in PL/SQL is a block.


 All PL/SQL programs are made up of blocks, which can be nested
within each other.

DECLARE
declaration statements;
BEGIN
executable statements
EXCEPTIONS
exception handling statements
END;

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 117
PL/SQL identifiers
Content (CO3)

• There are several PL/SQL identifiers such as variables,


constants, procedures, cursors, triggers etc.
Variables:

Like several other programming languages, variables


in PL/SQL must be declared prior to its use.
They should have a valid name and data type as well.

Syntax for declaration of variables:


variable_name datatype [NOT NULL := value
];

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 118
PL/SQL
Content (CO3)

SQL> SET SERVEROUTPUT ON; /*SET SERVEROUTPUT ON: It is used to


display the buffer used by the
dbms_output. */
SQL> DECLARE
var1 INTEGER; --declaration of variable, named var1 which is of integer type.
var2 REAL;
var3 varchar2(20) ;

BEGIN
SQL statement;
END;
/

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 119
PL/SQL Example
Content (CO3)

SQL> SET SERVEROUTPUT ON;


SQL> DECLARE

-- I am a comment, so i will be ignored.


var varchar2(40) := 'I love INDIA' ;
dbms_output.put_line : This command is used
BEGIN to direct the PL/SQL output to a screen.
dbms_output.put_line(var);

END;
/
Output:
I love INDIA
PL/SQL procedure successfully
completed.

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 120
PL/SQL Example
Content (CO3)

SQL> SET SERVEROUTPUT ON;

SQL> DECLARE

-- taking input for variable a


a number := &a;
Output:
Enter value for a: 24
old 2: a number := &a;
-- taking input for variable b new 2: a number := 24;
b varchar2(30) := &b; Enter value for b: ‘NIET'
old 3: b varchar2(30) := &b;
BEGIN new 3: b varchar2(30) := ‘NIET';
null; PL/SQL procedure successfully
completed.

END;
/

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 121
PL/SQL Example
Content (CO3)

PL/SQL code to print sum of two numbers taken from the user.

--PL/SQL code to print sum of two numbers taken from the


user.
SQL> SET SERVEROUTPUT ON;

SQL> DECLARE

-- taking input for variable a


a integer := &a ; Enter value for a:
-- taking input for variable b 2 Enter value for
b integer := &b ; b: 3 Sum of 2 and 3
c integer ;
is = 5
PL/SQL procedure successfully
BEGIN
completed.
c := a + b ;
dbms_output.put_line('Sum of '||a||' and '||b||' is = '||c);

END;
/

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 122
PL/SQL –Content
Cursors (CO3)

Oracle creates a memory area, known as the context area, for


processing an SQL statement, which contains all the information
needed for processing the statement

 cursor is a pointer to this context area.


 PL/SQL controls the context area through a cursor.
 A cursor holds the rows (one or more) returned by a SQL
statement.
 The set of rows the cursor holds is referred to as the active set.

There are two types of cursors −


 Implicit cursors
 Explicit cursors

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 123
Implicit Content
Cursors (CO3)

 Implicit cursors are automatically created by Oracle whenever


an SQL statement is executed
 Programmers cannot control the implicit cursors and the
information in it.
 Whenever a DML statement (INSERT, UPDATE and DELETE)
is issued, an implicit cursor is associated with this
statement.
 For INSERT operations, the cursor holds the data that
needs to be inserted.
 For UPDATE and DELETE operations, the cursor identifies
the rows that would be affected.

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 124
Attributes of Content
SQL CURSOR (CO3)

%FOUND
 Returns TRUE if an INSERT, UPDATE, or DELETE statement affected
one or more rows or a SELECT INTO statement returned one or more
rows. Otherwise, it returns FALSE.
%NOTFOUND
 The logical opposite of %FOUND.
 It returns TRUE if an INSERT, UPDATE, or DELETE statement
affected no rows, or a SELECT INTO statement returned no rows.
Otherwise, it returns FALSE.

%ISOPEN
 Always returns FALSE for implicit cursors, because Oracle closes the
SQL cursor automatically after executing its associated SQL
statement.
%ROWCOUNT
 Returns the number of rows affected by an INSERT, UPDATE, or
DELETE statement, or returned by a SELECT INTO statement.

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 125
PL/SQL –Cursor Example
Content (CO3)

update the table and increase the salary of each employee by


500 and use the SQL%ROWCOUNT attribute to determine the
number of rows affected
DECLARE
total_rows number(2);
BEGIN
UPDATE employee1
SET salary = salary + 500
Where age<=25;
IF sql%notfound
THEN
dbms_output.put_line('no customers selected’);
ELSIF sql%found
THEN total_rows := sql%rowcount;
dbms_output.put_line( total_rows||'customers selected’);
END IF;
END;
/
Dr C S Yadav KCS 501 DBMS Unit 2
09/13/2024 126
Explicit Cursors
Content (CO3)

 Explicit cursors are programmer-defined cursors for gaining more


control over the context area.
 An explicit cursor should be defined in the declaration section of
the PL/SQL Block.
 It is created on a SELECT Statement which returns more than one
row.

CURSOR cursor_name IS select_statement;

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 127
Steps involved with explicit cursor
Content (CO3)

 Declaring the cursor for initializing the memory


CURSOR cursor_name IS select_statement;

 Opening the cursor for allocating the memory


OPEN cursor_name;
 Fetching the cursor for retrieving the data
FETCH cursor_name INTO PL/SQL variable;
Or
FETCH cursor_name INTO PL/SQL record;

 Closing the cursor to release the allocated memory


CLOSE cursor_name;

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 128
Triggers
Content(CO3)

• An SQL trigger is a mechanism that automatically


executes a specified PL/SQL block when a triggering
event occurs on a table.
• The triggering event may be one of insert, delete, or

update.
• The trigger is associated with a database table and is
fired when the triggering event takes place on the table.

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 129
Triggers Content
Syntax (CO3)

create [or replace] trigger trigger-name


{before | after}
{delete | insert | update [of column [, column] …]}
[or
{delete | insert | update [of column [, column …]}
]…
ON table-name
[ [referencing {old [as] <old> [new [as] <new>]
| new [as] <new> [old [as] <old> }]
for each row
[when (condition)] ]
pl/sql_block

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 130
Syntax for creating
Contenttriggers in SQL
(CO3)

• Trigger name - unique within one database schema


• Timing - depends on the order of controlled events (before or
after or instead of)
• Triggering event - event which fires the trigger (E)
• Filtering condition - checked when the triggering event
occurs (C)
• Target - table (or view) against which the trigger is fired; they
should be both created within the same schema
• Trigger Parameters - parameters used to denote the record
columns; preceded by colon
• :new, :old for new and old versions of the values
respectively
• Trigger action - SQL statements, executed when the trigger
fires; surrounded by Begin ... End (A)

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 131
Triggers Example:
Content (CO3)

SQL>
SQL> CREATE
CREATE TRIGGER
TRIGGER increase_salary_trg
increase_salary_trg
22 BEFORE
BEFORE UPDATE
UPDATE OF
OF sal
sal
33 ON
ON emp
emp
44 BEGIN
BEGIN
55 INSERT
INSERT INTO
INTO sal_hist(increased,
sal_hist(increased, changedOn)
changedOn)
66 VALUES
VALUES (‘YES’,
(‘YES’, SYSDATE);
SYSDATE);
77 END;
END;
88 //

Trigger name: increase_salary_trg


Timing: BEFORE executing the statement
Triggering event: UPDATE of sal column
Target: emp table
Trigger action: INSERT values INTO sal_hist table

Dr C S Yadav KCS 501 DBMS Unit 2


09/13/2024 132
Quiz Content
(CO 2, CO3)

1. Information about pets is kept in two separate tables:


TABLE dogs
id INTEGER NOT NULL PRIMARY KEY,
name VARCHAR(50) NOT NULL
TABLE cats
id INTEGER NOT NULL PRIMARY KEY,
name VARCHAR(50) NOT NULL
Write a query that select all distinct pet names.
2. An employee is a manager if any other employee has their managerId
set to the first employees id. An employee who is a manager may or may
not also have a manager.
TABLE employees
id INTEGER NOT NULL PRIMARY KEY
managerId INTEGER REFERENCES employees(id)
name VARCHAR(30) NOT NULL
Write a query that selects the names of employees who are not
managers.

09/13/2024 Dr C S Yadav KCS 501 DBMS Unit 2 133


Quiz Content
(CO 2, CO3) cont..

3. Given the following data definition, write a query that returns the number
of students whose first name is John. String comparisons should be case
sensitive.
TABLE students
id INTEGER PRIMARY KEY,
firstName VARCHAR(30) NOT NULL,
lastName VARCHAR(30) NOT NULL

4.A table containing the students enrolled in a yearly course has incorrect
data in records with ids between 20 and 100 (inclusive).
TABLE enrollments
id INTEGER NOT NULL PRIMARY KEY
year INTEGER NOT NULL
studentId INTEGER NOT NULL
Write a query that updates the field 'year' of every faulty record to 2015.

09/13/2024 Dr C S Yadav KCS 501 DBMS Unit 2 134


Assignment 2.1 (CO1, CO 2)
Content

1. What is entity type and entity set? CO1, CO2


2. What is domain constraint? CO1, CO2

3. Differentiate between a weak entity sets and strong entity sets. CO1,
CO2
4. Define with examples – CO1,CO2
Specialization
Generalization
Aggregation
5. We can convert weak entity set to strong entity set by simply adding
attributes. Then why do we need weak entity sets. CO1,CO2

09/13/2024 Dr C S Yadav KCS 501 DBMS Unit 2 135


Assignment 2.2 (CO1, CO 2)
Content

1) Given
Project (projectno, projectname, chief_architect),
employee(empno, empname),
assigned_to(projectno,empno) CO2
Use the above database schema for following questions:

a) Get empno of employees working on project comp353?


b) Get details {empname & empno} of employees working on project comp353?
c) Get empname & empno of employees working on database project?
d) Get empname & empno of employees working on both comp353 & comp354?
e) Find employee number of employees who do not work on project comp453.
f) Get employee number of employees who work on all projects.

09/13/2024 Dr C S Yadav KCS 501 DBMS Unit 2 136


Assignment 2.3 (CO1, CO 2)
Content

Q: 1 Given relational schemas


Supplier(sid, sname, scity)
Part(pid, pname, pcolor)
Shipment(sid, pid qty)

(i) Get supplier names who supply all parts.

09/13/2024 Dr C S Yadav KCS 501 DBMS Unit 2 137


Assignment 2.4 (CO1, CO 2)
Content

Q 2: Given relational schema

EMP(eno, ename, salary)

PROJECT(pid, eno, pname)

(i) Find out the maximum salary of the employee.

(ii) Find out the second highest salary of the employee.

(iii) Find out the nth highest salary of the employee.

(iv) Find out the name of employees who have involved in at least one

project.

09/13/2024 Dr C S Yadav KCS 501 DBMS Unit 2 138


Assignment 2.4 (CO1, CO 2)
Content

Question: Create the following tables using the specified constraints:

Table : itemmaster

Itemid char(4) not null

Itemdesc char(20)

Rate number(8,2)

Table: itemtran

Ordid char(4) not null

Itemid char(4) not null

Quantity number(2)
09/13/2024 Dr C S Yadav KCS 501 DBMS Unit 2 139
Assignment 2.4 (CO1, CO 2)
Content

(i) itemid must be the primary key in the table itemmaster

(ii) Itemid and ordid must be the primary key in the table itemtran

(iii) Itemid must be the foreign key in the table itemtran

(iv) Itemid of itemtran table must reference itemid of itemmaster table

09/13/2024 Dr C S Yadav KCS 501 DBMS Unit 2 140


Faculty Video Links, Youtube & NPTEL Video Links
Content
and Online Courses Details

• Self Made Video Link:

• You tube /other Video Link


• https://nptel.ac.in/courses/106105175/
• https://www.youtube.com/watch?v=Wv1c9K4788A&list=PLEb
nTDJUr_Ic_9b4PcKmlae41cyxEefot&index=3

09/13/2024 Dr C S Yadav KCS 501 DBMS Unit 2 141


Old Question
Content Papers

• https://drive.google.com/drive/u/0/folders/1g
WUEwo7Ztpxs4smy34fl9jWQrx4AKpkC

09/13/2024 Dr C S Yadav KCS 501 DBMS Unit 2 142


References
Content

1. Korth, Silbertz, Sudarshan,” Database Concepts”, McGraw Hill


2. Date C J, “An Introduction to Database Systems”, Addision
Wesley
3. Elmasri, Navathe, “ Fundamentals of Database Systems”,
Addision Wesley

Thank You
09/13/2024 Dr C S Yadav KCS 501 DBMS Unit 2 143

You might also like