0% found this document useful (0 votes)
6 views276 pages

DBMS Unit 2

The document outlines the objectives and outcomes of a Database Management System course, focusing on database design, implementation of DDL, DML, and DCL statements, and transaction concepts. It provides informal guidelines for relational database design, including handling functional dependencies, normalization, and avoiding update anomalies. Key concepts such as multivalued dependencies and join dependencies are also discussed, emphasizing the importance of proper schema design to ensure data integrity.

Uploaded by

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

DBMS Unit 2

The document outlines the objectives and outcomes of a Database Management System course, focusing on database design, implementation of DDL, DML, and DCL statements, and transaction concepts. It provides informal guidelines for relational database design, including handling functional dependencies, normalization, and avoiding update anomalies. Key concepts such as multivalued dependencies and join dependencies are also discussed, emphasizing the importance of proper schema design to ensure data integrity.

Uploaded by

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

APEX INSTITUTE OF TECHNOLOGY

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Database Management System (22CSH-243)


Faculty: Ms. Shaveta Jain (13464)

Lecture – 2.1 DISCOVER . LEARN . EMPOWER


1
Informal Database Design Guidelines
DBMS: Course Objectives
COURSE OBJECTIVES
The Course aims to:
• Understand database system concepts and design databases for different applications
and to acquire the knowledge on DBMS and RDBMS.
• Implement and understand different types of DDL, DML and DCL statements.
• Understand transaction concepts related to databases and recovery/backup techniques
required for the proper storage of data.

2
COURSE OUTCOMES
On completion of this course, the students shall be able to:-
Understand the database concept, system architecture and role of database
CO1
administrator
CO2 Design database for an organization using relational model

CO3 Apply relational algebra and relational calculus to query the database of organization

CO4 Implement the package, procedures and triggers


CO5 Understand the concept of transaction processing and concurrency control

3
Unit-II Syllabus
Unit-2
FUNCTIONAL DEPENDENCIES AND NORMALIZATION
Functional Functional dependencies, Decomposition, Full Functional
dependencies and Dependency (FFD), Transitive Dependency (TD), Join Dependency
Normalization: (JD), Multi-valued Dependency (MVD), Normal Forms (1NF, 2NF,
3NF, BCNF), De-normalization.

Database Introduction, Threats, Counter Measures.


Security:

Control Introduction to conditional control, Iterative control and sequential


Structures: control statements, Cursors, Views.

4
Lecture Outline
• Informal Design Guidelines for Relational Databases
• Semantics of the Relation Attributes
• Redundant Information in Tuples and Update Anomalies
• Null Values in Tuples
• Spurious Tuples

Chapter 10-5
Informal Design Guidelines for Relational Databases
• What is relational database design?
The grouping of attributes to form "good" relation schemas
• Two levels of relation schemas
• The logical "user view" level
• The storage "base relation" level
• Design is concerned mainly with base relations
• What are the criteria for "good" base relations?

Chapter 10-6
Informal Design Guidelines for Relational Databases (2)
• We first discuss informal guidelines for good relational design
• Then we discuss formal concepts of functional dependencies and normal
forms
- 1NF (First Normal Form)
- 2NF (Second Normal Form)
- 3NF (Third Normal Form)
- BCNF (Boyce-Codd Normal Form)

Chapter 10-7
Semantics of the Relation Attributes
GUIDELINE 1: Informally, each tuple in a relation should represent one entity or
relationship instance. (Applies to individual relations and their attributes).
• Attributes of different entities (EMPLOYEEs, DEPARTMENTs, PROJECTs) should not be mixed in the same
relation
• Only foreign keys should be used to refer to other entities
• Entity and relationship attributes should be kept apart as much as possible.

Bottom Line: Design a schema that can be explained easily relation by relation. The
semantics of attributes should be easy to interpret.

Chapter 10-8
Figure: A simplified COMPANY relational database schema

Note: The above figure is now called Figure 10.1 in Edition 4


Chapter 10-9
Redundant Information in Tuples and Update Anomalies
• Mixing attributes of multiple entities may cause problems
• Information is stored redundantly wasting storage
• Problems with update anomalies
• Insertion anomalies
• Deletion anomalies
• Modification anomalies

Chapter 10-10
EXAMPLE OF AN UPDATE ANOMALY
Consider the relation:
EMP_PROJ ( Emp#, Proj#, Ename, Pname, No_hours)

• Update Anomaly: Changing the name of project number P1 from “Billing” to


“Customer-Accounting” may cause this update to be made for all 100 employees
working on project P1.

Chapter 10-11
EXAMPLE OF AN UPDATE ANOMALY (2)
• Insert Anomaly: Cannot insert a project unless an employee is assigned to .
Inversely - Cannot insert an employee unless an he/she is assigned to a project.
• Delete Anomaly: When a project is deleted, it will result in deleting all the
employees who work on that project. Alternately, if an employee is the sole employee
on a project, deleting that employee would result in deleting the corresponding
project.

Chapter 10-12
Figure: Two relation schemas suffering from update anomalies

Note: The above figure is now called Figure 10.3 in Edition 4


Chapter 10-13
Figure: Example States for EMP_DEPT and EMP_PROJ

Note: The above figure is now called Figure 10.4 in Edition 4


Chapter 10-14
Guideline to Redundant Information in Tuples and Update
Anomalies
• GUIDELINE 2:
• Design a schema that does not suffer from the insertion, deletion and update
anomalies. If there are any present, then note them so that applications can be made
to take them into account

Chapter 10-15
Null Values in Tuples
GUIDELINE 3: Relations should be designed such that their tuples will have as few NULL
values as possible
• Attributes that are NULL frequently could be placed in separate relations (with the
primary key)
• Reasons for nulls:
• attribute not applicable or invalid
• attribute value unknown (may exist)
• value known to exist, but unavailable

Chapter 10-16
Spurious Tuples
• Bad designs for a relational database may result in erroneous results for certain JOIN
operations
• The "lossless join" property is used to guarantee meaningful results for join operations

GUIDELINE 4: The relations should be designed to satisfy the lossless join condition. No
spurious tuples should be generated by doing a natural-join of any relations.

Chapter 10-17
Spurious Tuples
There are two important properties of decompositions:
(a) non-additive or losslessness of the corresponding join
(b) preservation of the functional dependencies.

Note that property (a) is extremely important and cannot be sacrificed.


Property (b) is less stringent and may be sacrificed.

Chapter 10-18
References
• RamezElmasri and Shamkant B. Navathe, “Fundamentals of Database System”, The
Benjamin / Cummings Publishing Co.
• Korth and Silberschatz Abraham, “Database System Concepts”, McGraw Hall.
• C.J.Date, “An Introduction to Database Systems”, Addison Wesley.
• Thomas M. Connolly, Carolyn & E. Begg, “Database Systems: A Practical Approach to
Design, Implementation and Management”, 5/E, University of Paisley, Addison-
Wesley.

19
THANK YOU

For queries
Email: [email protected]
20
APEX INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Database Management System (22CSH-243)


Faculty: Ms. Shaveta Jain (13464)

Lecture – 2.2 DISCOVER . LEARN . EMPOWER


1
Functional Dependencies
DBMS: Course Objectives
COURSE OBJECTIVES
The Course aims to:
• Understand database system concepts and design databases for different applications
and to acquire the knowledge on DBMS and RDBMS.
• Implement and understand different types of DDL, DML and DCL statements.
• Understand transaction concepts related to databases and recovery/backup techniques
required for the proper storage of data.

2
COURSE OUTCOMES
On completion of this course, the students shall be able to:-

CO3 Apply relational algebra and relational calculus to query the database of organization

3
Lecture Outline
• Functional Dependencies
• Fully Functional Dependence (FFD)
• Partial Dependency
• Transitive Dependency
• Join Dependency

Chapter 10-4
Functional Dependencies (1)
• Functional dependencies (FDs) are used to specify formal measures of the
"goodness" of relational designs
• FDs and keys are used to define normal forms for relations
• FDs are constraints that are derived from the meaning and interrelationships of the
data attributes
• A set of attributes X functionally determines a set of attributes Y if the value of X
determines a unique value for Y

Chapter 10-5
Functional Dependencies (2)
• X -> Y holds if whenever two tuples have the same value for X, they must have the
same value for Y
• For any two tuples t1 and t2 in any relation instance r(R): If t1[X]=t2[X], then
t1[Y]=t2[Y]
• X -> Y in R specifies a constraint on all relation instances r(R)
• Written as X -> Y; can be displayed graphically on a relation schema as in Figures. (
denoted by the arrow: ).
• FDs are derived from the real-world constraints on the attributes

Chapter 10-6
Examples of FD constraints (1)
• Social security number determines employee name
SSN -> ENAME
• Project number determines project name and location
PNUMBER -> {PNAME, PLOCATION}
• employee ssn and project number determines the hours per week that the employee
works on the project
{SSN, PNUMBER} -> HOURS

Chapter 10-7
Examples of FD constraints (2)
• An FD is a property of the attributes in the schema R
• The constraint must hold on every relation instance r(R)
• If K is a key of R, then K functionally determines all attributes in R (since we never have
two distinct tuples with t1[K]=t2[K])

Chapter 10-8
Fully Functional Dependence (FFD)
Fully Functional Dependence (FFD) is defined, as To be fully dependent,
• IF non-candidate key attributes must depend on the primary key.
• Primary Key is used to uniquely identify a database record.

An attribute is fully functional


dependent on another attribute,

if it is Functionally Dependent on that


attribute and not on any of its proper
subset.
Partial Dependency
If any proper subsets of the key determine any of the non-key attributes then there exist
a partial dependency.
• Example: Given a relation R(A,B,C,D,E) , Functional Dependency : AB→CDE ,
Primary_key(or simply 'key') is AB.

• Then A→C : is a Partial Dependency


A→D : is a Partial Dependency
A→E : is a Partial Dependency
B→C : is a Partial Dependency
B→D : is a Partial Dependency
B→E : is a Partial Dependency
Transitive Dependency
The transitivity rule is perhaps the most important one. It states that if X functionally
determines Y and Y functionally determine Z then X functionally determines Z.

X Y
Y Z
X Z
Multi-Value Dependency
• A Multi-Value Dependency (MVD) occurs when two or more independent multi
valued facts about the same attribute occur within the same table.
• Multivalued dependencies occur when the presence of one or more rows in a table
implies the presence of one or more other rows in that same table.

• Examples: For example, imagine a car company that manufactures many models of
car, but always makes both red and blue colors of each model.
• If you have a table that contains the model name, color and year of each car the
company manufactures, there is a multivalued dependency in that table.
• If there is a row for a certain model name and year in blue, there must also be a similar
row corresponding to the red version of that same car.
Join Dependency
• A Join Dependency exists if a relation R is equal to the join of the projections X Z.
• A join dependency is a constraint on the set of legal relations over a database scheme.
• A table T is subject to a join dependency if T can always be recreated by joining
multiple tables each having a subset of the attributes of T.
• If one of the tables in the join has all the attributes of the table T, the join dependency
is called trivial.
Multivalued Dependencies
• Suppose we record names of children, and phone numbers for instructors:
• inst_child(ID, child_name)
• inst_phone(ID, phone_number)
• If we were to combine these schemas to get
• inst_info(ID, child_name, phone_number)
• Example data:
(99999, David, 512-555-1234)
(99999, David, 512-555-4321)
(99999, William, 512-555-1234)
(99999, William, 512-555-4321)
• This relation is in BCNF
• Why?
Multivalued Dependencies (MVDs)

• Let R be a relation schema and let   R and   R. The multivalued


dependency
  
holds on R if in any legal relation r(R), for all pairs for tuples t1 and t2 in r such
that t1[] = t2 [], there exist tuples t3 and t4 in r such that:
t1[] = t2 [] = t3 [] = t4 []
t3[] = t1 []
t3[R – ] = t2[R – ]
t4 [] = t2[]
t4[R – ] = t1[R – ]
MVD (Cont.)
• Tabular representation of   
Example
• Let R be a relation schema with a set of attributes that are partitioned into 3
nonempty subsets.
Y, Z, W
• We say that Y  Z (Y multidetermines Z )
if and only if for all possible relations r (R )
< y1, z1, w1 >  r and < y1, z2, w2 >  r
then
< y1, z1, w2 >  r and < y1, z2, w1 >  r
• Note that since the behavior of Z and W are identical it follows that
Y  Z if Y  W
Example (Cont.)
• In our example:
ID  child_name
ID  phone_number
• The above formal definition is supposed to formalize the notion that given a
particular value of Y (ID) it has associated with it a set of values of Z (child_name)
and a set of values of W (phone_number), and these two sets are in some sense
independent of each other.
• Note:
• If Y  Z then Y  Z
• Indeed we have (in above notation) Z1 = Z2
The claim follows.
Use of Multivalued Dependencies
• We use multivalued dependencies in two ways:
1. To test relations to determine whether they are legal under a given set of functional
and multivalued dependencies
2. To specify constraints on the set of legal relations. We shall thus concern ourselves only
with relations that satisfy a given set of functional and multivalued dependencies.
• If a relation r fails to satisfy a given multivalued dependency, we can
construct a relations r that does satisfy the multivalued dependency by
adding tuples to r.
Theory of MVDs
• From the definition of multivalued dependency, we can derive the following
rule:
• If   , then   
That is, every functional dependency is also a multivalued dependency
• The closure D+ of D is the set of all functional and multivalued dependencies
logically implied by D.
• We can compute D+ from D, using the formal definitions of functional dependencies and
multivalued dependencies.
• We can manage with such reasoning for very simple multivalued dependencies, which seem
to be most common in practice
• For complex dependencies, it is better to reason about sets of dependencies using a system
of inference rules (see Appendix C).
Restriction of Multivalued Dependencies
• The restriction of D to Ri is the set Di consisting of
• All functional dependencies in D+ that include only attributes of Ri
• All multivalued dependencies of the form
  (  Ri)
where   Ri and    is in D+
Further Normal Forms
• Join dependencies generalize multivalued dependencies
• lead to project-join normal form (PJNF) (also called fifth normal form)
• A class of even more general constraints, leads to a normal form called
domain-key normal form.
• Problem with these generalized constraints: are hard to reason with, and no
set of sound and complete set of inference rules exists.
• Hence rarely used
References
• RamezElmasri and Shamkant B. Navathe, “Fundamentals of Database System”, The
Benjamin / Cummings Publishing Co.
• Korth and Silberschatz Abraham, “Database System Concepts”, McGraw Hall.
• C.J.Date, “An Introduction to Database Systems”, Addison Wesley.
• Thomas M. Connolly, Carolyn & E. Begg, “Database Systems: A Practical Approach to
Design, Implementation and Management”, 5/E, University of Paisley, Addison-
Wesley.

23
THANK YOU

For queries
Email: [email protected]
24
APEX INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Database Management System (22CSH-243)


Faculty: Ms. Shaveta Jain (13464)

NORMALIZATION & 1NF DISCOVER . LEARN . EMPOWER


1
DBMS: Course Objectives
COURSE OBJECTIVES
The Course aims to:
• Understand database system concepts and design databases for different applications
and to acquire the knowledge on DBMS and RDBMS.
• Implement and understand different types of DDL, DML and DCL statements.
• Understand transaction concepts related to databases and recovery/backup techniques
required for the proper storage of data.

2
COURSE OUTCOMES
On completion of this course, the students shall be able to:-
Understand the database concept, system architecture and role of database
CO1
administrator
CO2 Design database for an organization using relational model

CO3 Apply relational algebra and relational calculus to query the database of organization

CO4 Implement the package, procedures and triggers


CO5 Understand the concept of transaction processing and concurrency control

3
Lecture Outline
• Normal Forms Based on Primary Keys
1. Normalization of Relations
2. Practical Use of Normal Forms
3. Definitions of Keys and Attributes Participating in Keys
4. First Normal Form
5. Second Normal Form
6. Third Normal Form
• General Normal Form Definitions (For Multiple Keys)
• BCNF

Chapter 10-4
Normal Forms Based on Primary Keys

1. Normalization of Relations
2. Practical Use of Normal Forms
3. Definitions of Keys and Attributes Participating in Keys
4. First Normal Form
5. Second Normal Form
6. Third Normal Form
7. BCNF

Chapter 10-5
Normalization of Relations

• Normalization: The process of decomposing unsatisfactory "bad"


relations by breaking up their attributes into smaller relations

• Normal form: Condition using keys and FDs of a relation to certify


whether a relation schema is in a particular normal form

Chapter 10-6
Normalization of Relations

• 2NF, 3NF, BCNF based on Keys and FDs of a relation schema

• 4NF based on keys, multi-valued dependencies : MVDs;

• 5NF based on keys, join dependencies : JDs

• Additional properties may be needed to ensure a good relational


design (lossless join, dependency preservation);

Chapter 10-7
Goals of Normalization

• Let R be a relation scheme with a set F of functional dependencies.


• Decide whether a relation scheme R is in “good” form.
• In the case that a relation scheme R is not in “good” form, decompose
it into a set of relation scheme {R1, R2, ..., Rn} such that
• each relation scheme is in good form
• the decomposition is a lossless-join decomposition
• Preferably, the decomposition should be dependency preserving.
Practical Use of Normal Forms

• Normalization is carried out in practice so that the resulting


designs are of high quality and meet the desirable properties
• The practical utility of these normal forms becomes questionable
when the constraints on which they are based are hard to
understand or to detect
• The database designers need not normalize to the highest possible
normal form. (usually up to 3NF, BCNF or 4NF)
• De-Normalization: the process of storing the join of higher
normal form relations as a base relation—which is in a lower
normal form

Chapter 10-9
Definitions of Keys and Attributes Participating in Keys

• A Superkey of a relation schema R = {A1, A2, ...., An} is a set of


attributes S subset-of R with the property that no two tuples t1
and t2 in any legal relation state r of R will have t1[S] = t2[S]

• A Key K is a Superkey with the additional property that removal of


any attribute from K will cause K not to be a superkey any more.

Chapter 10-10
Definitions of Keys and Attributes Participating in Keys

• If a relation schema has more than one key, each is called a


candidate key. One of the candidate keys is arbitrarily designated
to be the primary key, and the others are called secondary keys.

• A Prime attribute must be a member of some candidate key

• A Nonprime attribute is not a prime attribute—that is, it is not a


member of any candidate key.

Chapter 10-11
First Normal Form (1NF)

• Disallows composite attributes, multivalued attributes, and


nested relations; attributes whose values for an individual tuple
are non-atomic

• Allows only Atomic & Single-valued

• Considered to be part of the definition of relation

Chapter 10-12
Normalization into 1NF
a) Relation Schema that is not in 1NF b) Example Relation Instance
c) 1NF Relations with redundancy

Note: The above figure is now called Figure 10.8 in Edition 4


Chapter 10-13
Normalizing Nested Relations into 1NF
a) Schema of the EMP_PROJ relation with ‘Nested Relation’ PROJS
b) Example Extension of EMP_PROJ relation

Note: The above figure is now called Figure 10.9 in Edition 4


Chapter 10-14
Normalizing Nested Relations into 1NF
c) Decomposing EMP_PROJ into 1NF relations EMP_PROJ1 and EMP_PROJ2 by propagating
the Primary Key.

Note: The above figure is now called Figure 10.9 in Edition 4


Chapter 10-15
References
• RamezElmasri and Shamkant B. Navathe, “Fundamentals of Database System”, The
Benjamin / Cummings Publishing Co.
• Korth and Silberschatz Abraham, “Database System Concepts”, McGraw Hall.
• C.J.Date, “An Introduction to Database Systems”, Addison Wesley.
• Thomas M. Connolly, Carolyn & E. Begg, “Database Systems: A Practical Approach
to Design, Implementation and Management”, 5/E, University of Paisley, Addison-
Wesley.

16
THANK YOU

For queries
Email: [email protected]
17
APEX INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Database Management System (22CSH-243)


Faculty: Ms. Shaveta Jain (13464)

NORMALIZATION(2NF & 3NF DISCOVER . LEARN . EMPOWER


1
DBMS: Course Objectives
COURSE OBJECTIVES
The Course aims to:
• Understand database system concepts and design databases for different applications
and to acquire the knowledge on DBMS and RDBMS.
• Implement and understand different types of DDL, DML and DCL statements.
• Understand transaction concepts related to databases and recovery/backup techniques
required for the proper storage of data.

2
COURSE OUTCOMES
On completion of this course, the students shall be able to:-

CO3 Apply relational algebra and relational calculus to query the database of organization

3
Outline
Second Normal Form (2NF)
Normalizing into 2NF
Third Normal Form (3NF)
Normalizing into 3NF
General Normal Form Definitions

Chapter 10-4
Second Normal Form (2NF)
• Uses the concepts of FDs, Primary key
Definitions:
• Prime attribute - Attribute that is member of the primary key K
• Full functional dependency - a FD Y -> Z where removal of any attribute from Y
means the FD does not hold any more
Examples:
• {SSN, PNUMBER} -> HOURS is a Full FD since neither SSN -> HOURS nor PNUMBER -> HOURS
hold
• {SSN, PNUMBER} -> ENAME is not a Full FD (it is called a Partial Dependency ) since SSN ->
ENAME also holds

Chapter 10-5
Second Normal Form (2NF)
• A relation schema R is in Second Normal Form (2NF) if:-
• It is in 1NF, and
• Every Non-prime attribute A in R is Fully Functionally Dependent on
the Primary Key
(i.e There should be no Partial Dependency)

• R can be decomposed into 2NF relations via the process of 2NF normalization

Chapter 10-6
Normalizing into 2NF
The Normalization process: a) Normalizing EMP_PROJ into 2NF relations

Note: The above figure is now called Figure 10.10 in Edition 4


Chapter 10-7
Normalization into 2NF
a) The Lots relation schema and its Functional Dependencies fd1 through fd4
b) Decomposing lots into the 2NF relations LOTS1 and LOTS2

Note: The above figure is now called Figure 10.11 in Edition 4


Chapter 10-8
Third Normal Form (3NF)
Definition:
• Transitive functional dependency - a FD X -> Z that can be derived from two FDs X -
> Y and Y -> Z

Examples:
• SSN -> DMGRSSN is a transitive FD since
SSN -> DNUMBER and DNUMBER -> DMGRSSN hold

• SSN -> ENAME is non-transitive since there is no set of attributes X where SSN -> X
and X -> ENAME

Chapter 10-9
Third Normal Form (3NF)

• A relation schema R is in Third Normal Form (3NF):-


1. If it is in 2NF and
2. No Non-prime attribute A in R is Transitively Dependent on the
primary key
(i.e. There should be no Transitive Dependency)

• R can be decomposed into 3NF relations via the process of 3NF normalization

Chapter 10-10
Third Normal Form (3NF)

NOTE:
• In X -> Y and Y -> Z, with X as the primary key, we consider this a problem only if Y
is not a candidate key.

• When Y is a candidate key, there is no problem with the transitive dependency .

• E.g., Consider EMP (SSN, Emp#, Salary ).


Here, SSN -> Emp# -> Salary and Emp# is a candidate key.

Chapter 10-11
Normalizing into 3NF
The Normalization process: b) Normalizing EMP_DEPT into 3NF relations

Note: The above figure is now called Figure 10.10 in Edition 4


Chapter 10-12
Normalization into 3NF
c) Decomposing LOTS1 into 3NF relations LOTS1A and LOTS1B
d) Summary of Normalization of Lots

Note: The above figure is now called Figure 10.11 in Edition 4


Chapter 10-13
General Normal Form Definitions (For Multiple Keys)
• The above definitions consider the primary key only

• The following more general definitions take into account relations with multiple
candidate keys

• A relation schema R is in second normal form (2NF) if every non-prime attribute A in R


is fully functionally dependent on every key of R

Chapter 10-14
General Normal Form Definitions
• A relation schema R is in Third Normal Norm (3NF) if whenever a FD X -> A holds in R,
then either:
(a) X is a Superkey of R, or
(b) A is a Prime Attribute of R

NOTE:
Boyce-Codd Formal Form (BCNF) disallows condition (b) above

Chapter 10-15
References
• RamezElmasri and Shamkant B. Navathe, “Fundamentals of Database System”, The
Benjamin / Cummings Publishing Co.
• Korth and Silberschatz Abraham, “Database System Concepts”, McGraw Hall.
• C.J.Date, “An Introduction to Database Systems”, Addison Wesley.
• Thomas M. Connolly, Carolyn & E. Begg, “Database Systems: A Practical Approach to
Design, Implementation and Management”, 5/E, University of Paisley, Addison-
Wesley.

16
THANK YOU

For queries
Email: [email protected]
17
APEX INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Database Management System (22CSH-243)


Faculty: Ms. Shaveta Jain (13464)

BCNF & De-NORMALIZATION DISCOVER . LEARN . EMPOWER


1
DBMS: Course Objectives
COURSE OBJECTIVES
The Course aims to:
• Understand database system concepts and design databases for different applications
and to acquire the knowledge on DBMS and RDBMS.
• Implement and understand different types of DDL, DML and DCL statements.
• Understand transaction concepts related to databases and recovery/backup techniques
required for the proper storage of data.

2
COURSE OUTCOMES
On completion of this course, the students shall be able to:-

CO3 Apply relational algebra and relational calculus to query the database of organization

3
Outline
• General Normal Form Definitions
• BCNF (3.5NF)
• BCNF Summary
• De-Normalization
• Typical Denormalization Techniques
• Problems of De-normalization

Chapter 10-4
General Normal Form Definitions (For Multiple Keys)
• The above definitions consider the primary key only

• The following more general definitions take into account relations with multiple
candidate keys

• A relation schema R is in second normal form (2NF) if every non-prime attribute A in


R is fully functionally dependent on every key of R

Chapter 10-5
General Normal Form Definitions
• A relation schema R is in Third Normal Norm (3NF) if whenever a FD X -> A holds in R,
then either:
(a) X is a Superkey of R, or
(b) A is a Prime Attribute of R

NOTE:
Boyce-Codd Formal Form (BCNF) disallows condition (b) above

Chapter 10-6
BCNF (3.5NF)
• BCNF was developed in 1974 by Raymond F. Boyce and Edgar F. Codd to address
certain types of anomalies not dealt with by 3NF as originally defined.

• BCNF is an extension to 3NF and is slightly stronger than 3NF

• BCNF doesn’t allow Non-prime attribute Prime Attribute


Boyce-Codd Normal Form (BCNF)
• A relation schema R is in BCNF:-
if an FD X -> A holds in R, then X is a Superkey of R

• The second point sounds a bit tricky, In simple words, it means, that for a dependency
X → A, X cannot be a non-prime attribute, if A is a prime attribute.

Chapter 10-8
Boyce-Codd Normal Form
(a) BCNF Normalization with the dependency of FD2 being “lost” in the De-Composition
(b) A relation R in 3NF but not in BCNF

Note: The above figure is now called Figure 10.12 in Edition 4


Chapter 10-9
BCNF Summary
• Each normal form is strictly stronger than the previous one
• Every 2NF relation is in 1NF
• Every 3NF relation is in 2NF
• Every BCNF relation is in 3NF
• There exist relations that are in 3NF but not in BCNF
• The goal is to have each relation in BCNF (or 3NF)
• If our database will be used for OLTP (on line transaction processing), then BCNF is
our target. Usually, we meet this objective.
• However, we might De-Normalize (3NF, 2NF, or 1NF) for performance reasons.

Chapter 10-10
De-Normalization
- It causes redundancy, but fast performance & no referential integrity
- De-normalize when
• specific queries occur frequently,
• a strict performance is required and
• it is not heavily updated

-So, de-normalize only when there is a very clear advantage to doing so and document
carefully the reason for doing so

11
Typical Denormalization Techniques
(1) Flatten a repeating group in one table
Instead of
EMP (E#, Ename)
SKILL (E#, Skill)

Use EMP (E#, Skill, Ename) when Emp has a smaller # of attributes.
- This means use Method 2 of 1NF algorithm. But know the danger of this
method as we discussed in MVD.

12
Problems of De-normalization
• Makes row longer
• Makes data transfer longer
• Needs more memory for memory processing
• Cause redundancy and expensive update

13
References
• RamezElmasri and Shamkant B. Navathe, “Fundamentals of Database System”, The
Benjamin / Cummings Publishing Co.
• Korth and Silberschatz Abraham, “Database System Concepts”, McGraw Hall.
• C.J.Date, “An Introduction to Database Systems”, Addison Wesley.
• Thomas M. Connolly, Carolyn & E. Begg, “Database Systems: A Practical Approach to
Design, Implementation and Management”, 5/E, University of Paisley, Addison-
Wesley.

14
THANK YOU

For queries
Email: [email protected]
15
APEX INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Database Management System (22CSH-243)


Faculty: Ms. Shaveta Jain (13464)

Inference Rules DISCOVER . LEARN . EMPOWER


1
DBMS: Course Objectives
COURSE OBJECTIVES
The Course aims to:
• Understand database system concepts and design databases for different applications
and to acquire the knowledge on DBMS and RDBMS.
• Implement and understand different types of DDL, DML and DCL statements.
• Understand transaction concepts related to databases and recovery/backup techniques
required for the proper storage of data.

2
COURSE OUTCOMES

On completion of this course, the students shall be able to:-


Apply relational algebra and relational calculus to query the database of
CO3
organization

3
Lecture Outline
• Closure
• Armstrong’s Axioms
• Procedure for Computing F+
• Closure of Attribute Sets
• Canonical Cover
Closure of a Set of Functional Dependencies

• Given a set F set of functional dependencies, there are certain other


functional dependencies that are logically implied by F.
• For e.g.: If A  B and B  C, then we can infer that A  C
• The set of all functional dependencies logically implied by F is the closure of
F.
• We denote the closure of F by F+.
Armstrong’s Axioms & Closure of a Set of Functional Dependencies

• We can find F+, the closure of F, by repeatedly applying Armstrong’s Axioms:


• if   , then    (reflexivity)
• if   , then      (augmentation)
• if   , and   , then    (transitivity)

• These rules are


• sound (generate only functional dependencies that actually hold), and
• complete (generate all functional dependencies that hold).
Example
• R = (A, B, C, G, H, I)
F={ AB
AC
CG  H
CG  I
B  H}
• some members of F+
• AH
• by transitivity from A  B and B  H
• AG  I
• by augmenting A  C with G, to get AG  CG
and then transitivity with AG  I
• CG  HI
• by augmenting CG  I to infer CG  CGI,
and augmenting of CG  H to infer CGI  HI,
and then transitivity
Procedure for Computing F+
• To compute the closure of a set of functional dependencies F:

F+=F
repeat
for each functional dependency f in F+
apply reflexivity and augmentation rules on f
add the resulting functional dependencies to F +
for each pair of functional dependencies f1and f2 in F +
if f1 and f2 can be combined using transitivity
then add the resulting functional dependency to F +
until F + does not change any further

NOTE: We shall see an alternative procedure for this task later


Closure of Functional Dependencies (Cont.)
• Additional rules/ Axioms :

• If    holds and    holds, then     holds (union)


• If     holds, then    holds and    holds (decomposition)
• If    holds and     holds, then     holds (pseudotransitivity)
The above rules can be inferred from Armstrong’s axioms.
Closure of Attribute Sets
• Given a set of attributes , define the closure of  under F (denoted by +) as the set
of attributes that are functionally determined by  under F

• Algorithm to compute +, the closure of  under F

result := ;
while (changes to result) do
for each    in F do
begin
if   result then result := result  
end
Example of Attribute Set Closure
• R = (A, B, C, G, H, I)
• F = {A  B
AC
CG  H
CG  I
B  H}
• (AG)+
1. result = AG
2. result = ABCG (A  C and A  B)
3. result = ABCGH (CG  H and CG  AGBC)
4. result = ABCGHI (CG  I and CG  AGBCH)
• Is AG a candidate key?
1. Is AG a super key?
1. Does AG  R? == Is (AG)+  R
2. Is any subset of AG a superkey?
1. Does A  R? == Is (A)+  R
2. Does G  R? == Is (G)+  R
Uses of Attribute Closure
There are several uses of the attribute closure algorithm:
• Testing for superkey:
• To test if  is a superkey, we compute +, and check if + contains all attributes of R.
• Testing functional dependencies
• To check if a functional dependency    holds (or, in other words, is in F+), just check if   +.
• That is, we compute + by using attribute closure, and then check if it contains .
• Is a simple and cheap test, and very useful
• Computing closure of F
• For each   R, we find the closure +, and for each S  +, we output a functional dependency  
S.
Canonical Cover
• Sets of functional dependencies may have redundant dependencies that can be
inferred from the others
• For example: A  C is redundant in: {A  B, B  C, A C}
• Parts of a functional dependency may be redundant
• E.g.: on RHS: {A  B, B  C, A  CD} can be simplified to
{A  B, B  C, A  D}
• E.g.: on LHS: {A  B, B  C, AC  D} can be simplified to
{A  B, B  C, A  D}

• Intuitively, a canonical cover of F is a “minimal” set of functional dependencies


equivalent to F, having no redundant dependencies or redundant parts of
dependencies
Extraneous Attributes (Unnecessary Attributes)
• Consider a set F of functional dependencies and the functional dependency 
  in F.
• Attribute A is extraneous in  if A  
and F logically implies (F – {  })  {( – A)  }.
• Attribute A is extraneous in  if A  
and the set of functional dependencies
(F – {  })  { ( – A)} logically implies F.
• Note: implication in the opposite direction is trivial in each of the cases above,
since a “stronger” functional dependency always implies a weaker one
• Example: Given F = {A  C, AB  C }
• B is extraneous in AB  C because {A  C, AB  C} logically implies A  C (I.e. the result
of dropping B from AB  C).
• Example: Given F = {A  C, AB  CD}
• C is extraneous in AB  CD since AB  C can be inferred even after deleting C
Testing if an Attribute is Extraneous
• Consider a set F of functional dependencies and the functional dependency   
in F.
• To test if attribute A   is extraneous in 
1. compute ({} – A)+ using the dependencies in F
2. check that ({} – A)+ contains ; if it does, A is extraneous in 
• To test if attribute A   is extraneous in 
1. compute + using only the dependencies in
F’ = (F – {  })  { ( – A)},
2. check that + contains A; if it does, A is extraneous in 
Canonical Cover
• A canonical cover for F is a set of dependencies Fc such that
• F logically implies all dependencies in Fc, and
• Fc logically implies all dependencies in F, and
• No functional dependency in Fc contains an extraneous attribute, and
• Each left side of functional dependency in Fc is unique.
• To compute a canonical cover for F:
repeat
Use the union rule to replace any dependencies in F
1  1 and 1  2 with 1  1 2
Find a functional dependency    with an
extraneous attribute either in  or in 
/* Note: test for extraneous attributes done using Fc, not F*/
If an extraneous attribute is found, delete it from   
until F does not change
• Note: Union rule may become applicable after some extraneous attributes have been
deleted, so it has to be re-applied
Computing a Canonical Cover

• R = (A, B, C)
F = {A  BC
BC
AB
AB  C}
• Combine A  BC and A  B into A  BC
• Set is now {A  BC, B  C, AB  C}
• A is extraneous in AB  C
• Check if the result of deleting A from AB  C is implied by the other dependencies
• Yes: in fact, B  C is already present!
• Set is now {A  BC, B  C}
• C is extraneous in A  BC
• Check if A  C is logically implied by A  B and the other dependencies
• Yes: using transitivity on A  B and B  C.
• Can use attribute closure of A in more complex cases
• The canonical cover is: AB
BC
References
• RamezElmasri and Shamkant B. Navathe, “Fundamentals of Database System”, The
Benjamin / Cummings Publishing Co.
• Korth and Silberschatz Abraham, “Database System Concepts”, McGraw Hall.
• C.J.Date, “An Introduction to Database Systems”, Addison Wesley.
• Thomas M. Connolly, Carolyn & E. Begg, “Database Systems: A Practical Approach to
Design, Implementation and Management”, 5/E, University of Paisley, Addison-
Wesley.

18
THANK YOU

For queries
Email: [email protected]

19
APEX INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Database Management System (22CSH-243)


Faculty: Ms. Shaveta Jain (13464)

DISCOVER . LEARN . EMPOWER


Introduction to DB Security 1
DBMS: Course Objectives
COURSE OBJECTIVES
The Course aims to:
• Understand database system concepts and design databases for different applications and to
acquire the knowledge on DBMS and RDBMS.
• Implement and understand different types of DDL, DML and DCL statements.
• Understand transaction concepts related to databases and recovery/backup techniques required
for the proper storage of data.

2
COURSE OUTCOMES

On completion of this course, the students shall be able to:-


Understand the database concept, system architecture and role of database
CO1
administrator
CO2 Design database for an organization using relational model
Apply relational algebra and relational calculus to query the database of
CO3
organization
CO4 Implement the package, procedures and triggers
CO5 Understand the concept of transaction processing and concurrency control

3
Introduction to Database Security Issues
• Types of Security
• Legal and ethical issues
• Policy issues
• System-related issues

• The need to identify multiple security levels

Chapter 23-4
Introduction to Database Security Issues (2)
• Threats to databases
- Loss of integrity
- Loss of availability
- Loss of confidentiality

• To protect databases against these types of threats four kinds of


countermeasures can be implemented : access control, inference control,
flow control, and encryption.
Introduction to Database Security Issues (3)
• A DBMS typically includes a database security and authorization subsystem
that is responsible for ensuring the security portions of a database against
unauthorized access.

Two types of database security mechanisms:


• Mandatory Access Control
• Discretionary Access Control
• Role Based Access Control
Introduction to Database Security Issues (4)
• The security mechanism of a DBMS must include provisions for
restricting access to the database as a whole; this function is called
access control and is handled by creating user accounts and passwords
to control login process by the DBMS.
Introduction to Database Security Issues (5)
• The security problem associated with databases is that of controlling the
access to a statistical database, which is used to provide statistical
information or summaries of values based on various criteria.

• The countermeasures to statistical database security problem is called


inference control measures.
Introduction to Database Security Issues (6)
• Another security is that of flow control, which prevents information from
flowing in such a way that it reaches unauthorized users.

• Channels that are pathways for information to flow implicitly in ways that
violate the security policy of an organization are called covert channels.
Introduction to Database Security Issues (7)
• A final security issue is data encryption, which is used to protect sensitive
data (such as credit card numbers) that is being transmitted via some type
communication network.

• The data is encoded using some coding algorithm. An unauthorized user who
access encoded data will have difficulty deciphering it, but authorized users
are given decoding or decrypting algorithms (or keys) to decipher data.
1.2 Database Security and the DBA
• The database administrator (DBA) is the central authority for managing a
database system.

• The DBA’s responsibilities include granting privileges to users who need to


use the system and classifying users and data in accordance with the policy of
the organization.

• The DBA has a DBA account in the DBMS, sometimes called a system or
superuser account, which provides powerful capabilities :
1.2 Database Security and the DBA
1. Account creation
2. Privilege granting
3. Privilege revocation
4. Security level assignment

• The DBA is responsible for the overall security of the database system.
• Action 1 is access control, whereas 2 and 3 are discretionary and 4 is
used to control mandatory authorization.

Chapter 23-12
Access Protection, User Accounts, and Database Audits
• Whenever a person or group of person s need to access a database system,
the individual or group must first apply for a user account.

• The DBA will then create a new account number and password for the user if
there is a legitimate need to access the database.

• The user must log in to the DBMS by entering account number and password
whenever database access is needed.

Chapter 23-13
Access Protection, User Accounts, and Database Audits(2)
• The database system must also keep track of all operations on the database
that are applied by a certain user throughout each login session.
• To keep a record of all updates applied to the database and of the particular
user who applied each update, we can modify system log, which includes an
entry for each operation applied to the database that may be required for
recovery from a transaction failure or system crash.
• If any tampering with the database is suspected, a database audit is
performed, which consists of reviewing the log to examine all accesses and
operations applied to the database during a certain time period.
• A database log that is used mainly for security purposes is sometimes called
an audit trail.

Chapter 23-14
Discretionary Access Control Based on Granting and Revoking
Privileges
• The typical method of enforcing discretionary access control in a database
system is based on the granting and revoking privileges.

Chapter 23-15
References
• RamezElmasri and Shamkant B. Navathe, “Fundamentals of Database System”, The
Benjamin / Cummings Publishing Co.
• Korth and Silberschatz Abraham, “Database System Concepts”, McGraw Hall.
• C.J.Date, “An Introduction to Database Systems”, Addison Wesley.
• Thomas M. Connolly, Carolyn & E. Begg, “Database Systems: A Practical Approach to
Design, Implementation and Management”, 5/E, University of Paisley, Addison-
Wesley.

16
THANK YOU

For queries
Email: [email protected] 17
APEX INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Database Management System (22CSH-243)


Faculty: Ms. Shaveta Jain (13464)

Access Control DISCOVER . LEARN . EMPOWER


1
DBMS: Course Objectives

COURSE OBJECTIVES
The Course aims to:
• Understand database system concepts and design databases for different
applications and to acquire the knowledge on DBMS and RDBMS.
• Implement and understand different types of DDL, DML and DCL statements.
• Understand transaction concepts related to databases and recovery/backup
techniques required for the proper storage of data.

2
COURSE OUTCOMES

On completion of this course, the students shall be able to:-


Understand the database concept, system architecture and role of database
CO1
administrator
CO2 Design database for an organization using relational model
Apply relational algebra and relational calculus to query the database of
CO3
organization
CO4 Implement the package, procedures and triggers
CO5 Understand the concept of transaction processing and concurrency control

3
Unit-II Syllabus
Unit-2
FUNCTIONAL DEPENDENCIES AND NORMALIZATION
Functional Functional dependencies, Decomposition, Full Functional
dependencies and Dependency (FFD), Transitive Dependency (TD), Join Dependency
Normalization: (JD), Multi-valued Dependency (MVD), Normal Forms (1NF, 2NF,
3NF, BCNF), De-normalization.

Database Introduction, Threats, Counter Measures.


Security:

Control Introduction to conditional control, Iterative control and sequential


Structures: control statements, Cursors, Views.

4
Discretionary Access Control Based on Granting and Revoking
Privileges

• The typical method of enforcing discretionary access control in a


database system is based on the granting and revoking
privileges.
Types of Discretionary Privileges
• The account level: At this level, the DBA specifies the particular privileges
that each account holds independently of the relations in the database.

• The relation (or table level): At this level, the DBA can control the
privilege to access each individual relation or view in the database.
Types of Discretionary Privileges(2)
• The privileges at the account level apply to the capabilities provided to the
account itself and can include the CREATE SCHEMA or CREATE TABLE
privilege, to create a schema or base relation;
• the CREATE VIEW privilege;
• the ALTER privilege, to apply schema changes such adding or removing
attributes from relations;
• the DROP privilege, to delete relations or views;
• the MODIFY privilege, to insert, delete, or update tuples; and the SELECT
privilege, to retrieve information from the database by using a SELECT query.
Types of Discretionary Privileges(3)
• The second level of privileges applies to the relation level, whether they are
base relations or virtual (view) relations.
• The granting and revoking of privileges generally follow an authorization
model for discretionary privileges known as the access matrix model, where
the rows of a matrix M represents subjects (users, accounts, programs) and
the columns represent objects (relations, records, columns, views,
operations).
• Each position M(i,j) in the matrix represents the types of privileges (read,
write, update) that subject i holds on object j.
Types of Discretionary Privileges(4)
• To control the granting and revoking of relation privileges, each relation R in
a database is assigned and owner account, which is typically the account that
was used when the relation was created in the first place.
• The owner of a relation is given all privileges on that relation. In SQL2, the
DBA can assign and owner to a whole schema by creating the schema and
associating the appropriate authorization identifier with that schema, using
the CREATE SCHEMA command.
• The owner account holder can pass privileges on any of the owned relation
to other users by granting privileges to their accounts.
Types of Discretionary Privileges(5)
• In SQL the following types of privileges can be granted on each individual
relation R:
• SELECT (retrieval or read) privilege on R: Gives the account retrieval privilege.
In SQL this gives the account the privilege to use the SELECT statement to
retrieve tuples from R.
• MODIFY privileges on R: This gives the account the capability to modify
tuples of R.
• In SQL this privilege is further divided into UPDATE, DELETE, and INSERT
privileges to apply the corresponding SQL command to R.
• In addition, both the INSERT and UPDATE privileges can specify that only
certain attributes can be updated by the account.
Types of Discretionary Privileges(6)
• REFERENCES privilege on R: This gives the account the capability to reference
relation R when specifying integrity constraints.

• The privilege can also be restricted to specific attributes of R.

• Notice that to create a view, the account must have SELECT privilege on all
relations involved in the view definition.
Revoking Privileges
• In some cases it is desirable to grant a privilege to a user temporarily.
• For example, the owner of a relation may want to grant the SELECT privilege
to a user for a specific task and then revoke that privilege once the task is
completed.
• Hence, a mechanism for revoking privileges is needed.
• In SQL, a REVOKE command is included for the purpose of canceling
privileges.
Propagation of Privileges using the GRANT OPTION
• Whenever the owner A of a relation R grants a privilege on R to another
account B, privilege can be given to B with or without the GRANT OPTION.
• If the GRANT OPTION is given, this means that B can also grant that privilege
on R to other accounts.
• Suppose that B is given the GRANT OPTION by A and that B then grants the
privilege on R to a third account C, also with GRANT OPTION.
• In this way, privileges on R can propagate to other accounts without the
knowledge of the owner of R.
• If the owner account A now revokes the privilege granted to B, all the
privileges that B propagated based on that privilege should automatically be
revoked by the system.
An Example
• Suppose that the DBA creates four accounts --A1, A2, A3, and A4-- and wants
only A1 to be able to create base relations; then the DBA must issue the
following GRANT command in SQL:

GRANT CREATETAB TO A1;

• In SQL2 the same effect can be accomplished by having the DBA issue a
CREATE SCHEMA command as follows:

CREATE SCHAMA EXAMPLE AUTHORIZATION A1;


An Example(2)
• User account A1 can create tables under the schema called EXAMPLE.

• Suppose that A1 creates the two base relations EMPLOYEE and


DEPARTMENT; A1 is then owner of these two relations and hence all the
relation privileges on each of them.

• Suppose that A1 wants to grant A2 the privilege to insert and delete tuples in
both of these relations, but A1 does not want A2 to be able to propagate
these privileges to additional accounts:

GRANT INSERT, DELETE ON EMPLOYEE, DEPARTMENT TO A2;


An Example(3)
EMPLOYEE

NAME SSN BDATE ADDRE SEX SALARY DNO


SS

DEPARTMENT
DNUMBER DNAME MGRSSN
2.5 An Example(4)
• Suppose that A1 wants to allow A3 to retrieve information from either of
the two tables and also to be able to propagate the SELECT privilege to
other accounts.
• A1 can issue the command:
GRANT SELECT ON EMPLOYEE, DEPARTMENT TO A3 WITH GRANT OPTION;
• A3 can grant the SELECT privilege on the EMPLOYEE relation to A4 by
issuing:
GRANT SELECT ON EMPLOYEE TO A4;
• (Notice that A4 can not propagate the SELECT privilege because GRANT
OPTION was not given to A4.)
2.5 An Example(5)
• Suppose that A1 decides to revoke the SELECT privilege on
the EMPLOYEE relation from A3; A1 can issue:
REVOKE SELECT ON EMPLOYEE FROM A3;

• (The DBMS must now automatically revoke the SELECT


privilege on EMPLOYEE from A4, too, because A3 granted
that privilege to A4 and A3 does not have the privilege any
more.)
2.5 An Example(6)
• Suppose that A1 wants to give back to A3 a limited capability to SELECT from the
EMPLOYEE relation and wants to allow A3 to be able to propagate the privilege. The
limitation is to retrieve only the NAME, BDATE, and ADDRESS attributes and only for
the tuples with DNO=5.
• A1 then create the view:
CREATE VIEW A3EMPLOYEE AS
• SELECT NAME, BDATE, ADDRESS
FROM EMPLOYEE
WHERE DNO = 5;
• After the view is created, A1 can grant SELECT on the view A3EMPLOYEE to
A3 as follows:
GRANT SELECT ON A3EMPLOYEE TO A3 WITH GRANT OPTION;
Mandatory Access Control and Role-Based Access Control for
Multilevel Security

• The discretionary access control techniques of granting and revoking privileges


on relations has traditionally been the main security mechanism for relational
database systems.
• This is an all-or-nothing method: A user either has or does not have a certain
privilege.
• In many applications, and additional security policy is needed that classifies
data and users based on security classes. This approach as mandatory access
control, would typically be combined with the discretionary access control
mechanisms.
Mandatory Access Control and Role-Based Access Control
for Multilevel Security(2)
• Typical security classes are top secret (TS), secret (S), confidential (C), and
unclassified (U), where TS is the highest level and U the lowest: TS ≥ S ≥ C ≥ U

• The commonly used model for multilevel security, known as the Bell-
LaPadula model, classifies each subject (user, account, program) and object
(relation, tuple, column, view, operation) into one of the security
classifications, T, S, C, or U: clearance (classification) of a subject S as class(S)
and to the classification of an object O as class(O).
Mandatory Access Control and Role-Based Access Control for
Multilevel Security(3)
Two restrictions are enforced on data access based on the subject/object
classifications:
1. A subject S is not allowed read access to an object O unless class(S) ≥
class(O). This is known as the simple security property.
2. A subject S is not allowed to write an object O unless class(S) ≤ class(O).
This known as the star property (or * property).

TS - 1
S-2
C-3
U-4
Mandatory Access Control and Role-Based Access Control
for Multilevel Security(4)
• To incorporate multilevel security notions into the relational database
model, it is common to consider attribute values and tuples as data
objects.
• Hence, each attribute A is associated with a classification attribute C
in the schema, and each attribute value in a tuple is associated with a
corresponding security classification.
• In addition, in some models, a tuple classification attribute TC is
added to the relation attributes to provide a classification for each
tuple as a whole.
• Hence, a multilevel relation schema R with n attributes would be
represented as
R(A1,C1,A2,C2, …, An,Cn,TC)
where each Ci represents the classification attribute associated
with attribute Ai.
Mandatory Access Control and Role-Based Access Control
for Multilevel Security(5)
• The value of the TC attribute in each tuple t – which is the highest of all
attribute classification values within t – provides a general classification for
the tuple itself, whereas each Ci provides a finer security classification for
each attribute value within the tuple.

• The apparent key of a multilevel relation is the set of attributes that would
have formed the primary key in a regular(single-level) relation.
Mandatory Access Control and Role-Based Access Control
for Multilevel Security(6)
• A multilevel relation will appear to contain different data to subjects (users)
with different clearance levels. In some cases, it is possible to store a single
tuple in the relation at a higher classification level and produce the
corresponding tuples at a lower-level classification through a process known
as filtering.
• In other cases, it is necessary to store two or more tuples at different
classification levels with the same value for the apparent key. This leads to
the concept of polyinstantiation where several tuples can have the same
apparent key value but have different attribute values for users at different
classification levels.
Mandatory Access Control and Role-Based Access Control
for Multilevel Security(7)
• In general, the entity integrity rule for multilevel relations states that all
attributes that are members of the apparent key must not be null and must
have the same security classification within each individual tuple.
• In addition, all other attribute values in the tuple must have a security
classification greater than or equal to that of the apparent key. This
constraint ensures that a user can see the key if the user is permitted to see
any part of the tuple at all.
Mandatory Access Control and Role-Based Access Control
for Multilevel Security(8)
• Other integrity rules, called null integrity and interinstance integrity,
informally ensure that if a tuple value at some security level can be filtered
(derived) from a higher-classified tuple, then it is sufficient to store the
higher-classified tuple in the multilevel relation.
Comparing Discretionary Access Control and Mandatory
Access Control
• Discretionary Access Control (DAC) policies are characterized by a high
degree of flexibility, which makes them suitable for a large variety of
application domains.
• The main drawback of DAC models is their vulnerability to malicious attacks,
such as Trojan horses embedded in application programs.
Comparing Discretionary Access Control and Mandatory
Access Control(2)
• By contrast, mandatory policies ensure a high degree of protection in a way,
they prevent any illegal flow of information.
• Mandatory policies have the drawback of being too rigid and they are only
applicable in limited environments.
• In many practical situations, discretionary policies are preferred because they
offer a better trade-off between security and applicability.
Role-Based Access Control
• Role-based access control (RBAC) emerged rapidly in the 1990s as a proven
technology for managing and enforcing security in large-scale enterprisewide
systems.
• Its basic notion is that permissions are associated with roles, and users are
assigned to appropriate roles.
• Roles can be created using the CREATE ROLE and DESTROY ROLE commands.
The GRANT and REVOKE commands discussed under DAC can then be used
to assign and revoke privileges from roles.
Role-Based Access Control(3)
• Another important consideration in RBAC systems is the possible temporal
constraints that may exist on roles, such as time and duration of role
activations, and timed triggering of a role by an activation of another role.
• Using an RBAC model is highly desirable goal for addressing the key security
requirements of Web-based applications.
• In contrast, discretionary access control (DAC) and mandatory access control
(MAC) models lack capabilities needed to support the security requirements
emerging enterprises and Web-based applications.
Role-Based Access Control(2)
• RBAC appears to be a viable alternative to traditional discretionary and
mandatory access controls; it ensures that only authorized users are given
access to certain data or resources.
• Many DBMSs have allowed the concept of roles, where privileges can be
assigned to roles.
• Role hierarchy in RBAC is a natural way of organizing roles to reflect the
organization’s lines of authority and responsibility.
References
• RamezElmasri and Shamkant B. Navathe, “Fundamentals of Database System”, The
Benjamin / Cummings Publishing Co.
• Korth and Silberschatz Abraham, “Database System Concepts”, McGraw Hall.
• C.J.Date, “An Introduction to Database Systems”, Addison Wesley.
• Thomas M. Connolly, Carolyn & E. Begg, “Database Systems: A Practical Approach to
Design, Implementation and Management”, 5/E, University of Paisley, Addison-
Wesley.

33
THANK YOU

For queries
Email: [email protected]
34
APEX INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Database Management System (22CSH-243)


Faculty: Ms. Shaveta Jain (13464)

DISCOVER . LEARN . EMPOWER


Access Control Policy 1
DBMS: Course Objectives

COURSE OBJECTIVES
The Course aims to:
• Understand database system concepts and design databases for different
applications and to acquire the knowledge on DBMS and RDBMS.
• Implement and understand different types of DDL, DML and DCL statements.
• Understand transaction concepts related to databases and recovery/backup
techniques required for the proper storage of data.

2
COURSE OUTCOMES

On completion of this course, the students shall be able to:-


Understand the database concept, system architecture and role of database
CO1
administrator
CO2 Design database for an organization using relational model
Apply relational algebra and relational calculus to query the database of
CO3
organization
CO4 Implement the package, procedures and triggers
CO5 Understand the concept of transaction processing and concurrency control

3
Lecture Outline
• Access Control Policy for E-Commerce and Web
• Introduction to Statistical Database Security
• Introduction to Flow Control
• Covert Channels
• Encryption
• Public Key Encryption

Chapter 10-4
Access Control Policies for E-Commerce and the
Web
• E-Commerce environments require elaborate policies that go beyond
traditional DBMSs.
• In an e-commerce environment the resources to be protected are not
only traditional data but also knowledge and experience.
• The access control mechanism should be flexible enough to support a
wide spectrum of heterogeneous protection objects.

• A related requirement is the support for content-based access-control.


Access Control Policies for E-Commerce and the
Web(2)
• Another requirement is related to the heterogeneity of subjects,
which requires access control policies based on user
characteristics and qualifications.
• A possible solution, to better take into account user profiles in the
formulation of access control policies, is to support the notion of
credentials. A credential is a set of properties concerning a user that are
relevant for security purposes (for example, age, position within an
organization).
• It is believed that the XML language can play a key role in access control
for e-commerce applications.
Introduction to Statistical Database Security
• Statistical databases are used mainly to produce statistics on various
populations.
• The database may contain confidential data on individuals, which should be
protected from user access.
• Users are permitted to retrieve statistical information on the populations,
such as averages, sums, counts, maximums, minimums, and standard
deviations.
Introduction to Statistical Database Security(2)
• A population is a set of tuples of a relation (table) that satisfy
some selection condition.
• Statistical queries involve applying statistical functions to a
population of tuples.
Introduction to Statistical Database Security(3)
• For example, we may want to retrieve the number of individuals in a
population or the average income in the population.
• However, statistical users are not allowed to retrieve individual data, such as
the income of a specific person.
• Statistical database security techniques must prohibit the retrieval of
individual data.
• This can be achieved by prohibiting queries that retrieve attribute values and
by allowing only queries that involve statistical aggregate functions such as
COUNT, SUM, MIN, MAX, AVERAGE, and STANDARD DEVIATION. Such queries
are sometimes called statistical queries.
Introduction to Statistical Database Security(4)
• It is DBMS’s responsibility to ensure confidentiality of information about
individuals, while still providing useful statistical summaries of data
about those individuals to users.
• Provision of privacy protection of users in a statistical database is
paramount.
• In some cases it is possible to infer the values of individual tuples from a
sequence statistical queries.
• This is particularly true when the conditions result in a population
consisting of a small number of tuples.
Introduction to Flow Control
• Flow control regulates the distribution or flow of information among
accessible objects. A flow between object X and object Y occurs when a
program reads values from X and writes values into Y.
• Flow controls check that information contained in some objects does not
flow explicitly or implicitly into less protected objects.
• A flow policy specifies the channels along which information is allowed to
move. The simplest flow policy specifies just two classes of information:
confidential (C) and nonconfidential (N), and allows all flows except
those from class C to class N.
Covert Channels
• A covert channel allows a transfer of information that violates
the security or the policy.

• A covert channel allows information to pass from a higher


classification level to a lower classification level through
improper means.
Covert Channels(2)
• Covert channels can be classified into two broad categories:
• storage channels do not require any temporal synchronization, in that
information is conveyed by accessing system information or what is otherwise
inaccessible to the user.
• in a timing channel the information is conveyed by the timing of events or
processes.
• Some security experts believe that one way to avoid covert channels is for
programmers to not actually gain access to sensitive data that a program is
supposed to process after the program has been put into operation.
Encryption and Public Key Infrastructures
• Encryption is a means of maintaining secure data in an insecure
environment.
• Encryption consists of applying an encryption algorithm to data
using some prespecified encryption key.
• the resulting data has to be decrypted using a decryption key to recover
the original data.
Public Key Encryption
• In 1976 Diffie and Hellman proposed a new kind of
cryptosystem, which they called public key encryption.

• Public key algorithms are based on mathematical functions


rather than operations on bit patterns.
• They also involve the use of two separate keys, in contrast to
conventional encryption, which uses only one key.
• The use of two keys can have profound consequences in the areas of
confidentiality, key distribution, and authentication.
Public Key Encryption(2)
• The two keys used for public key encryption are referred to as
the public key and the private key.
• the private key is kept secret, but it is referred to as private key rather
than a secret key (the key used in conventional encryption) to avoid
confusion with conventional encryption.
Public Key Encryption(3)
A public key encryption scheme, or infrastructure, has six
ingredients:
1. Plaintext : This is the data or readable message that is fed into the
algorithm as input.
2. Encryption algorithm : The encryption algorithm performs various
transformations on the plaintext.
3. and
4. Public and private keys : These are pair of keys that have been selected
so that if one is used for encryption, the other is used for decryption.
The exec transformations performed by the encryption algorithm
depend on the public or private key that is provided as input.
Public Key Encryption(4)
5. Ciphertext : This is the scrambled message produced as output. It
depends on the plaintext and the key. For a given message, two
different keys will produce two different ciphertexts.
6. Decryption algorithm : This algorithm accepts the ciphertext and
the matching key and produces the original plaintext.
Public Key Encryption(5)
• Public key is made for public and private key is known only by
owner.
• A general-purpose public key cryptographic algorithm relies on
one key for encryption and a different but related one for
decryption. The essential steps are as follows:
1. Each user generates a pair of keys to be used for the encryption and
decryption of messages.
2. Each user places one of the two keys in a public register or other
accessible file. This is the public key. The companion key is kept private.
Public Key Encryption(6)
3. If a sender wishes to send a private message to a receiver,
the sender encrypts the message using the receiver’s public
key.
4. When the receiver receives the message, he or she decrypts
it using the receiver’s private key. No other recipient can
decrypt the message because only the receiver knows his or
her private key.
References
• RamezElmasri and Shamkant B. Navathe, “Fundamentals of Database System”, The
Benjamin / Cummings Publishing Co.
• Korth and Silberschatz Abraham, “Database System Concepts”, McGraw Hall.
• C.J.Date, “An Introduction to Database Systems”, Addison Wesley.
• Thomas M. Connolly, Carolyn & E. Begg, “Database Systems: A Practical Approach to
Design, Implementation and Management”, 5/E, University of Paisley, Addison-
Wesley.

21
THANK YOU

For queries
Email: [email protected]
22
APEX INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Database Management System (22CSH-243)


Faculty: Ms. Shaveta Jain (13464)

DISCOVER . LEARN . EMPOWER


DB Security Threats & Countermeasure
1
DBMS: Course Objectives
COURSE OBJECTIVES
The Course aims to:
• Understand database system concepts and design databases for different
applications and to acquire the knowledge on DBMS and RDBMS.
• Implement and understand different types of DDL, DML and DCL statements.
• Understand transaction concepts related to databases and recovery/backup
techniques required for the proper storage of data.

2
COURSE OUTCOMES

On completion of this course, the students shall be able to:-


Understand the database concept, system architecture and role of database
CO1
administrator
CO2 Design database for an organization using relational model
Apply relational algebra and relational calculus to query the database of
CO3
organization
CO4 Implement the package, procedures and triggers
CO5 Understand the concept of transaction processing and concurrency control

3
Lecture Outline
• Database security
• DB Threats & Countermeasures
• Additional Database Security Countermeasures

Chapter 10-4
What is database security
• Database security refers to the range of tools, controls, and measures designed to
establish and preserve database confidentiality, integrity, and availability.
• This lecture will focus primarily on confidentiality since it’s the element that’s
compromised in most data breaches.
• Database security must address and protect the following:
The data in the database
The database management system (DBMS)
Any associated applications
The physical database server and/or the virtual database server and the
underlying hardware
The computing and/or network infrastructure used to access the database
DB Threats & Countermeasures
1. Excessive Database Privileges
• Database users may have different privileges. However, users may abuse them
and here are the major types of privilege abuses: excessive privilege abuse,
legitimate privileges abuse and unused privilege abuse.
• Excessive privileges always create unnecessary risks.
• According to statistics 80% of the attacks on company databases are executed by
current company employees or ex-employees.
• Countermeasures:
• It is advised to deploy and uphold a strict access and privileges control policy.
• Don’t grant excessive privileges to company employees and revoke outdated
privileges in time.
2. SQL Injections
• This is a type of attack when a malicious code is embedded in frontend
(web) applications and then passed to the backend database.
• As the result of SQL injections cybercriminals get unlimited access to any
data being stored in a database.
• There are two types of such computer attacks: SQL injection targeting
traditional databases and NoSQL injections targeting big data databases.
• Countermeasures:
• Stored procedure shall be used instead of direct queries.
• MVC Architecture shall be implemented.
3. Weak Audit Trail
If a database is not audited it represents risks of noncompliance with
national and international sensitive data protection regulations.
All database events shall be recorded and registered automatically and it’s
obligatory to use automatic auditing solutions.
Inability or unwillingness to do that represents a serious risk on many levels.
• Countermeasures:
Use automatic auditing solutions that impose no additional load on database
performance.
Using DataSunrise Database Auditing module could be the best solution for
you and your business
4. Database Backups Exposure
It’s a good practice to make backups of proprietary databases at defined periods
of time.
However, surprisingly database back-up files are often left completely
unprotected from attack.
As a result, there are numerous security breaches happening through database
backup leaks.
• Countermeasures:
Encrypt both databases and backups.
Storing data in encrypted form allows secure both production and back-up copies
of databases.
Audit both the database and backups.
Doing this helps to see who has been trying to get access to sensitive data.
5. DB Vulnerabilities and Misconfigurations
It often happens that databases are found totally unprotected due to
misconfiguration.
Moreover, some databases have default accounts and configuration
parameters. One should remember that hackers are often highly professional
IT specialists who surely know how to exploit database vulnerabilities and
misconfigurations and use them to attack your company.
• Countermeasures:
Your databases shouldn’t have any default accounts.
Your IT personnel should be highly qualified and experienced.
6. Lack of Security Expertise and Education.
Databases get breached and leaked due to insufficient level of IT security
expertise and education of non-technical employees who may break basic
database security rules and put databases at risk.
IT security personnel may also lack the expertise required to implement
security controls, enforce policies, or conduct incident response processes.
• Countermeasures:
Database users shall be educated in database security.
IT security specialists shall be urged to raise their professional level and
qualification.
7. Denial of service attack.
This type of attacks slows down a database server and can even make it
unavailable to all users.
Despite the fact that a DoS attack doesn’t disclose the contents of a database, it
may cost the victims a lot of time and money.
Moreover, what’s the use of a database if you can’t use or access it.
• Countermeasures:
Harden the TCP/IP stack by applying the appropriate registry settings to increase
the size of the TCP connection queue.
Decrease the connection establishment period.
Employ dynamic backlog mechanisms to ensure that the connection queue is
never exhausted.
Use a network Intrusion Detection System (IDS).
8. Unmanaged Sensitive Data.
Many companies store a lot of sensitive information and fail to keep an accurate
inventory of it.
Forgotten and unattended data may fall prey to hackers. In addition, new
sensitive data is added on a daily basis and it’s not easy to keep track of it all.
It means that newly added data may be exposed to threats.
• Countermeasures:
Encrypt all sensitive data in your database(s).
Apply required controls and permissions to the database.
Run periodic search for new sensitive data on your databases. You can do this
very effectively with the Periodic Data Discovery tool and Compliance Manager
that will automatically discover newly added sensitive data and protect it.
Additional Database Security Countermeasures
• To protect the database system from the threats. Here are some
countermeasures which are as follows:
1. Access Control:
A database for an organization contains a great deal of information and usually
has several users.
Most of them need to access only a small part of the database.
A policy defines the requirements that are to be implemented within hardware
and software and those that are external to the system, including physical,
personal, and procedural controls.
2. Flow Control:
Flow control provides the flow of information among accessible objects.
Flow controls check that information contained in objects does not flow explicitly
or implicitly into less protected objects.
3. Encryption:
An encryption algorithm should be applied to the data, using a user-specified
encryption key.
The output of the algorithm is the encrypted version.
There is also a decryption algorithm, which takes the encrypted data and a
decryption key as input and then returns the original data.
4. RAID:
Redundant Array of Independent Disks which protect against data loss due to
disk failure
5. Authentication:
Access to the database is a matter of authentication.
It provides the guidelines how the database is accessed. Every access should
be monitored.

6. Backup:
At every instant, backup should be done.
In case of any disaster, Organizations can retrieve their data.
Summary
• To achieve these objectives, a clear and consistent security policy should be
developed to define what security measure must be enforced.
• We must determine what part of data is to be protected and which users get
access to which part of the information.
• The security mechanisms of the underlying database management system, as
well as external mechanism, such as securing access to buildings, must be
utilized to enforce the policy.
References
• RamezElmasri and Shamkant B. Navathe, “Fundamentals of Database System”, The
Benjamin / Cummings Publishing Co.
• Korth and Silberschatz Abraham, “Database System Concepts”, McGraw Hall.
• C.J.Date, “An Introduction to Database Systems”, Addison Wesley.
• Thomas M. Connolly, Carolyn & E. Begg, “Database Systems: A Practical Approach to
Design, Implementation and Management”, 5/E, University of Paisley, Addison-
Wesley.

18
THANK YOU

For queries
Email: [email protected]
19
APEX INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Database Management System (22CSH-243)


Faculty: Ms. Shaveta Jain (E13464)

DISCOVER . LEARN . EMPOWER


Conditional Control Structure
1
DBMS: Course Objectives
COURSE OBJECTIVES
The Course aims to:
• Understand database system concepts and design databases for different
applications and to acquire the knowledge on DBMS and RDBMS.
• Implement and understand different types of DDL, DML and DCL statements.
• Understand transaction concepts related to databases and recovery/backup
techniques required for the proper storage of data.

2
COURSE OUTCOMES

On completion of this course, the students shall be able to:-


Apply relational algebra and relational calculus to query the database of
CO3
organization

3
Lecture Outline
• Control Structures of PL/SQL
• Loops
• Nested Loops
• For
• While

4
Structure of PL/SQL

5
Structure of PL/SQL

6
Example for Structure of PL/SQL

7
Example for Structure of PL/SQL

DECLARE
a number;
text1 varchar2(20);
text2 varchar2(20) := “HI”;
BEGIN
DBMS_OUTPUT.PUT_LINE(text2) ;
---------- ---------- ----------;
END;

8
DBMS_OUTPUT.PUT_LINE(text2)
• It prints Message and value of variable
• Package: Dbms_Output
• Procedure: Put_Line()

9
PL/SQL Control Structure
PL/SQL has a number of control structures which includes:
• Conditional controls
• Iterative or loop controls.
It is these controls, used singly or together, that allow the PL/SQL
developer to direct the flow of execution through the program.

10
PL/SQL Control Structure: Conditional Controls
• Conditional Controls
IF....THEN....END IF;

IF....THEN...ELSE....END IF;

IF....THEN...ELSIF....THEN....ELSE....END IF;

11
IF THEN ELSE STATEMENT:
1)

IF condition THEN
Statement 1;
ELSE
Statement 2;
END IF;

2)

IF condition 1 THEN
Statement 1;
Statement 2;
ELSIF condtion2 THEN
Statement 3;
ELSE
Statement 4;
END IF 12
Write PL/SQL code for finding Even Numbers.
BEGIN
FOR I IN 1..100 LOOP
IF MOD(I,2)=0 THEN
DBMS_OUTPUT.PUT_LINE(I);
END IF;
END LOOP;
END;
/

13
//Write PL/SQL code to find Largest of three numbers.
DECLARE
A NUMBER;
B NUMBER;
C NUMBER;
BEGIN
A:=&A;
B:=&B;
C:=&C;
IF A=B AND B=C AND C=A THEN
DBMS_OUTPUT.PUT_LINE('ALL ARE EQUAL');
ELSE IF A>B AND A>C THEN
DBMS_OUTPUT.PUT_LINE('A IS GREATER');
ELSE IF B>C THEN
DBMS_OUTPUT.PUT_LINE('B IS GREATER');
ELSE
DBMS_OUTPUT.PUT_LINE('C IS GREATER');
END IF;
END IF;
END IF;
END;/ 14
References
• RamezElmasri and Shamkant B. Navathe, “Fundamentals of Database
System”, The Benjamin / Cummings Publishing Co.
• Korth and Silberschatz Abraham, “Database System Concepts”,
McGraw Hall.
• C.J.Date, “An Introduction to Database Systems”, Addison Wesley.
• Thomas M. Connolly, Carolyn & E. Begg, “Database Systems: A Practical
Approach to Design, Implementation and Management”, 5/E,
University of Paisley, Addison-Wesley.

15
THANK YOU

For queries
Email: [email protected]
16
APEX INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Database Management System (22CSH-243)


Faculty: Ms. Shaveta Jain (E13464)

DISCOVER . LEARN . EMPOWER


Iterative Control Structure
1
DBMS: Course Objectives
COURSE OBJECTIVES
The Course aims to:
• Understand database system concepts and design databases for different
applications and to acquire the knowledge on DBMS and RDBMS.
• Implement and understand different types of DDL, DML and DCL statements.
• Understand transaction concepts related to databases and recovery/backup
techniques required for the proper storage of data.

2
COURSE OUTCOMES

On completion of this course, the students shall be able to:-


Apply relational algebra and relational calculus to query the database of
CO3
organization

3
Outline
• Control Structures of PL/SQL
• Loops
• Nested Loops
• For
• While

4
PL/SQL Control Structure : Loop

• This is used to repeatedly execute a set of statements. This is the


simplest form of looping structures.
LOOP
Statements;
-------------;
-------------;
EXIT [WHEN condition];
END LOOP;

5
Write PL/SQL code to find Factorial of a given number.

DECLARE
N NUMBER(2);
I NUMBER(2);
F NUMBER(5):=1;
BEGIN
N:=&N;
FOR I IN 1..N LOOP
F:=F*I;
END LOOP;
DBMS_OUTPUT.PUT_LINE('THE FACTORIAL VALUE IS =' || F);
END;
/

6
Write PL/SQL code to Read number and prints its
Multiplication Table.
DECLARE
T NUMBER(3):=3;
BEGIN
T:=&T;
FOR I IN 1..3 LOOP
DBMS_OUTPUT.PUT_LINE(T||'X'||I||'='||I*T);
END LOOP;
END;
/

7
PL/SQL Control Structure : Nested Loop

• It is possible to have a loop within another loop. When a loop is placed


within another loop it is called as nested loop. The inner loop is
executed for each iteration of outer loop.
• The following example will display table up to 10 for numbers from 1
to 5.
LOOP ...
LOOP ...
EXIT outerloop WHEN ...

END LOOP; ...
END LOOP;
8
Nested Loop: Example

DECLARE
i number(2);
j number(2);
BEGIN
i := 1;
LOOP
j:= 1;
Nested Loop: Example
LOOP
dbms_output.put_line(i || '*' || j || '=' || i * j);
j := j + 1;
exit when j > 10;
END LOOP;
i := i + 1;
exit when i > 5;
END LOOP;
END;/
9
PL/SQL Control Structure : While
• Executes a series of statements as long as the given condition is true.

WHILE condition LOOP


Statements;
-------------;
END LOOP;

10
While : Example

declare
i number(2) := 1;
begin
while i <= 10 loop
dbms_output.put_line(i);
i := i + 1;
end loop;
end;

11
PL/SQL Control Structure : For

This looping structure is best suited to cases where we have to


repeatedly execute a set of statements by varying a variable from one
value to another.

FOR counter IN [REVERSE] lower range .. Upper range


LOOP
Statements;
END LOOP;

12
For : Example

Declare
i int=1;
Begin
for i in 1..10 loop
dbms_output.put_line(i);
end loop;
End;/

13
For : Example

If REVERSE option is used the following steps will take place:

1. Counter is set to upper range.


2. If counter is greater than or equal to lower range then statements are
executed otherwise loop is terminated.
3. Counter is decremented by 1.
4. Go to step 2

14
Declare
i int=1;
Begin
for i in REVERSE 1..10 loop
dbms_output.put_line(i);
end loop;
End;/

15
Write PL/SQL code to print the numbers in this form
1
12
123
DECLARE
I NUMBER;
J NUMBER;
N NUMBER;
BEGIN
N:=&N;
FOR I IN 1..N LOOP
FOR J IN 1..I LOOP
DBMS_OUTPUT.PUT(J);
END LOOP;
DBMS_OUTPUT.PUT_LINE('');
END LOOP;
END;
/

16
References
• RamezElmasri and Shamkant B. Navathe, “Fundamentals of Database
System”, The Benjamin / Cummings Publishing Co.
• Korth and Silberschatz Abraham, “Database System Concepts”,
McGraw Hall.
• C.J.Date, “An Introduction to Database Systems”, Addison Wesley.
• Thomas M. Connolly, Carolyn & E. Begg, “Database Systems: A Practical
Approach to Design, Implementation and Management”, 5/E,
University of Paisley, Addison-Wesley.

17
THANK YOU

For queries

Email: [email protected]
18
APEX INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Database Management System (22CSH243)


Faculty: Ms. Shaveta Jain (E13464)

Views DISCOVER . LEARN . EMPOWER


1
DBMS: Course Objectives
COURSE OBJECTIVES
The Course aims to:
• Understand database system concepts and design databases for different
applications and to acquire the knowledge on DBMS and RDBMS.
• Implement and understand different types of DDL, DML and DCL statements.
• Understand transaction concepts related to databases and recovery/backup
techniques required for the proper storage of data.

2
COURSE OUTCOMES

On completion of this course, the students shall be able to:-


Apply relational algebra and relational calculus to query the database of
CO3
organization

3
Outline

• View
• Updateable View
• Read Only View
• Usage of Views

4
SQL Views
• In SQL, a view is a virtual table based on the result-set of an SQL
statement.
• A view contains rows and columns, just like a real table.
• You can add SQL functions, WHERE, and JOIN statements to a view and
present the data as if the data were coming from one single table.

SYNTAX:
• CREATE VIEW view_name AS SELECT column_name(s) FROM table_name
WHERE condition
EXAMPLE:-
• CREATE VIEW ait_dept AS SELECT * FROM EMP WHERE
dept=‘ait-cse’

5
Selecting a Data set from a view:-
• Once a view has been created, it can be queried exactly like a
database table.
• Syntax:-
• SELECT <ColumnName1>,<ColumnName2> FROM <ViewName>;

• Example:
• SELECT * FROM ait_dept;

6
Renaming the columns of a View
Syntax:-
• CREATE VIEW <view name> AS SELECT <Column Name1> <“New
Column Name1”>, <Column Name2><“New Column Name2”>
FROM <TableName>
Example:-
• Create View view101 as select rollno “s_rollno”, name “s_name”
from students WHERE program=‘aiml’;
• Output:-
• View created

7
RENAMING THE VIEW
Syntax:
RENAME oldame TO newname;

Example:-
• RENAME ait_cse_view TO ait_dept

8
TYPES OF VIEW
1. UPDATEABLE VIEW
2. READ ONLY VIEW

• NOTE: All Views are automatically updated when we update the


Master Table.
• Example:-
• UPDATE emp SET salary=salary + 300 WHERE dept=‘ait-me’

9
1. UPDATEABLE VIEW
• In Oracle SQL, views are not only query-able but also updatable.
• It means that you can use the INSERT or UPDATE statement to
insert or update rows of the base table/master table through the
updatable view.
• In addition, you can use DELETE statement to remove rows of the
underlying table through the view.

• EXAMPLE:-
• CREATE VIEW ait_dept AS SELECT * FROM EMP WHERE DEPT=‘ait';

10
1. UPDATEABLE VIEW
• EXAMPLE
• UPDATE ait_emp SET NAME='akash' WHERE eid='e104'
• SELECT * FROM AIT_EMP
• SELECT * FROM EMP
• UPDATE ait_emp SET salary=salary + 300

• NOTE: In updateable Views, when we update this view


the master table is also updated.

11
2. READ ONLY VIEW
• WITH READ ONLY Specify WITH READ ONLY to indicate that the table
or view cannot be updated.

• Example:
• CREATE VIEW me_dept AS SELECT * FROM EMP WHERE DEPT='me' WITH
READ ONLY;

• SELECT * FROM me_dept; // Display all the record in view

• UPDATE me_dept SET salary=salary + 300 //Try to update the


view

• OUTPUT:
• ORA-01733: virtual column not allowed here

12
DELETING THE VIEW
• The drop view command is used to remove a view from the
database.
Syntax:-
• DROP VIEW <ViewName>;

Example:-
• Drop view view101;
Output:-
• View dropped.

13
When to use the Oracle view
• You can use views in many cases for different purposes.
• The most common uses of views are as follows:
• Simplifying data retrieval.
• Maintaining logical data independence.
• Implementing data security.

14
FAQs

• Explain the concept of view.


• What are the types of views?
• Explain the updateable view with example.
• Explain the read only view with example.
References
• RamezElmasri and Shamkant B. Navathe, “Fundamentals of Database System”, The
Benjamin / Cummings Publishing Co.
• Korth and Silberschatz Abraham, “Database System Concepts”, McGraw Hall.
• C.J.Date, “An Introduction to Database Systems”, Addison Wesley.
• Thomas M. Connolly, Carolyn & E. Begg, “Database Systems: A Practical Approach to
Design, Implementation and Management”, 5/E, University of Paisley, Addison-
Wesley.

16
THANK YOU

For queries
Email: [email protected]
17
APEX INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Database Management System (22CSH-243)


Faculty: Ms. Shaveta Jain (E13464)

DISCOVER . LEARN . EMPOWER


Cursor
1
DBMS: Course Objectives
COURSE OBJECTIVES
The Course aims to:
• Understand database system concepts and design databases for different
applications and to acquire the knowledge on DBMS and RDBMS.
• Implement and understand different types of DDL, DML and DCL statements.
• Understand transaction concepts related to databases and recovery/backup
techniques required for the proper storage of data.

2
COURSE OUTCOMES

On completion of this course, the students shall be able to:-


Apply relational algebra and relational calculus to query the database of
CO3
organization

3
Lecture Outline

• Concept of Cursors
• Implicit cursor
• Explicit cursor

4
Cursors
• 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.
• A 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.
• In simple words, A cursor is a pointer that points to a result of a query.

5
Types of Cursor
There are two types of cursors:
1. Implicit cursors
2. Explicit cursors

6
Implicit cursors
• Implicit cursors are automatically created by Oracle whenever an SQL statement is
executed, when there is no explicit cursor for the statement.
• Programmers cannot control the implicit cursors and the information in it.
• Whenever Oracle executes an SQL statement such as SELECT INTO, INSERT, UPDATE,
and DELETE, it automatically creates an implicit cursor.
• Oracle internally manages the whole execution cycle of implicit cursors and reveals
only the cursor’s information and statuses such
as SQL%ROWCOUNT, SQL%ISOPEN, SQL%FOUND, and SQL%NOTFOUND.
• The implicit cursor is not elegant when the query returns zero or multiple rows which
cause NO_DATA_FOUND or TOO_MANY_ROWS exception respectively.

7
Write PL/SQL code to UPDATE values in created tables by using IMPLICIT CURSORS.

DECLARE
VAR_ROWS NUMBER(5);
BEGIN
UPDATE EMP SET SAL=SAL+100;
IF SQL%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE('NONE OF THE SALARIES WERE UPDATED');
ELSE IF SQL%FOUND THEN
VAR_ROWS:=SQL%ROWCOUNT;
DBMS_OUTPUT.PUT_LINE('SALARIES FOR'||VAR_ROWS||'EMPLOYEES ARE UPDATED');
END IF ;
END IF;
END;
/
Explicit cursors
• 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.

Working with an explicit cursor involves four steps:


1. Declaring the cursor for initializing in the memory
2. Opening the cursor for allocating memory
3. Fetching the cursor for retrieving data
4. Closing the cursor to release allocated memory

9
• Oracle defines an execution cycle that executes an SQL statement and associates a
cursor with it.
• The following illustration shows the execution cycle of an explicit cursor:

10
Cursor Attribute
• cursorname%ROWCOUNT :Rows returned so far
• cursorname%FOUND :One or more rows retrieved
• cursorname%NOTFOUND :No rows found
• Cursorname%ISOPEN :Is the cursor open

11
Syntax:
DECLARE
CURSOR <cursor_name> IS <SELECT statement>;
cursor_variable declaration;
BEGIN
OPEN <cursor_name>;
FETCH <cursor_name> INTO <cursor_variable>;
.
.
CLOSE <cursor_name>;
END;/

12
Write PL/SQL code to display Employee details using EXPLICIT CURSORS.

DECLARE
CURSOR emp_cur IS SELECT * FROM EMP;
emp_rec EMP%ROWTYPE;
BEGIN
OPEN emp_cur;
LOOP
FETCH emp_cur INTO emp_rec;
EXIT WHEN emp_cur%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(emp_rec.EMPNO||' '||emp_rec.ENAME||' '||emp_rec.SAL);
END LOOP;
CLOSE EMP_CUR;
END;/
PL/SQL Control Structure

DECLARE
name varchar2(20);
Cursor c1 IS select t.name from table t where date is not null;
BEGIN
OPEN c1;
LOOP
FETCH c1 into name;
EXIT WHEN c1%NOTFOUND;
END LOOP;
CLOSE c1;
END;/

14
The %TYPE Attribute

Declare a variable according to:


• A database column definition
• Another previously declared variable

– Prefix %TYPE with:


• The database table and column
• The previously declared variable name

15
%TYPE (table.col%TYPE)
DECLARE
vname emp.name%TYPE;
Cursor c1 IS select t.name from table t where date is not
null;
BEGIN
OPEN c1;
LOOP
FETCH c1 into vname;
EXIT WHEN c1%NOTFOUND;
END LOOP;
CLOSE c1;
END;/

16
Write a procedure to retrieve the salary of a particular employee.

DECLARE
vid emp.eid%TYPE;
vsal EMP.SALARY%TYPE;
BEGIN
vid:='e101' ;
--vid = &vid ;
SELECT SALARY INTO vsal FROM EMP WHERE eid = vid;
DBMS_OUTPUT.PUT_LINE('SALARY OF '|| vid || ' IS '|| VSAL);
END;/

17
%ROWTYPE: Using Explicit Cursor

18
FAQs

• Explain the concept of cursors


• What is explicit cursor?
• What is implicit cursor?
• Explain %TYPE?
References
• RamezElmasri and Shamkant B. Navathe, “Fundamentals of Database System”, The
Benjamin / Cummings Publishing Co.
• Korth and Silberschatz Abraham, “Database System Concepts”, McGraw Hall.
• C.J.Date, “An Introduction to Database Systems”, Addison Wesley.
• Thomas M. Connolly, Carolyn & E. Begg, “Database Systems: A Practical Approach to
Design, Implementation and Management”, 5/E, University of Paisley, Addison-
Wesley.

20
THANK YOU

For queries
Email: [email protected]
21

You might also like