DBMS Unit 2
DBMS Unit 2
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
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.
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
Chapter 10-10
EXAMPLE OF AN UPDATE ANOMALY
Consider the relation:
EMP_PROJ ( Emp#, Proj#, Ename, Pname, No_hours)
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
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.
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
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.
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)
23
THANK YOU
For queries
Email: [email protected]
24
APEX INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
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
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
Chapter 10-6
Normalization of Relations
Chapter 10-7
Goals of Normalization
Chapter 10-9
Definitions of Keys and Attributes Participating in Keys
Chapter 10-10
Definitions of Keys and Attributes Participating in Keys
Chapter 10-11
First Normal Form (1NF)
Chapter 10-12
Normalization into 1NF
a) Relation Schema that is not in 1NF b) Example Relation Instance
c) 1NF Relations with redundancy
16
THANK YOU
For queries
Email: [email protected]
17
APEX INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
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
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)
• 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.
Chapter 10-11
Normalizing into 3NF
The Normalization process: b) Normalizing EMP_DEPT into 3NF relations
• The following more general definitions take into account relations with multiple
candidate keys
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
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
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.
• 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
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
2
COURSE OUTCOMES
3
Lecture Outline
• Closure
• Armstrong’s Axioms
• Procedure for Computing F+
• Closure of Attribute Sets
• Canonical Cover
Closure of a Set of Functional Dependencies
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
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
AC
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}
• R = (A, B, C)
F = {A BC
BC
AB
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: AB
BC
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
2
COURSE OUTCOMES
3
Introduction to Database Security Issues
• Types of Security
• Legal and ethical issues
• Policy issues
• System-related issues
Chapter 23-4
Introduction to Database Security Issues (2)
• Threats to databases
- Loss of integrity
- Loss of availability
- Loss of confidentiality
• 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 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
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
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.
4
Discretionary Access Control Based on Granting and Revoking
Privileges
• 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.
• 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:
• In SQL2 the same effect can be accomplished by having the DBA issue a
CREATE SCHEMA command as follows:
• 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:
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 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
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
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.
21
THANK YOU
For queries
Email: [email protected]
22
APEX INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
2
COURSE OUTCOMES
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
2
COURSE OUTCOMES
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
2
COURSE OUTCOMES
3
Outline
• Control Structures of PL/SQL
• Loops
• Nested Loops
• For
• While
4
PL/SQL Control Structure : 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
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.
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
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
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
2
COURSE OUTCOMES
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
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
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;
• 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
16
THANK YOU
For queries
Email: [email protected]
17
APEX INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
2
COURSE OUTCOMES
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.
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
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
20
THANK YOU
For queries
Email: [email protected]
21