DBMS All Chaptersnotes
DBMS All Chaptersnotes
Database Systems
Registration Society
In--Patients Accounts
The patients come to the hospital from the society. Upon the arrival of a preliminary
registration is done by seeking information about the patient. Then depending on the type
and illness, the patient will either be treated as out-patient (or) in-patient. In some cases
initially a patient will be treated as out-patient and then the patient will be admitted as
outpatient if necessary. Finally the bills are to be paid before the patient is discharged. In this
system we are using four files. The files are
Patient File: At the Registration.
The files are maintained in different sections of the hospital in a decentralized manner,
certain data items (patient no, patient name, patient address) will be duplicated. Which will
have some undesirable results? Some of the difficulties of the conventional file processing
system of the hospital are the following.
In-Patient Charges
Treatment
Out-Patient
Treatment
In the Conventional File Processing System there will be a separate system for in-patients.
But under the database approach, all the necessary files are included in a single database,
which minimizes redundancy of data. As a result all the drawbacks of Conventional File
Processing System are eliminated in the DataBase System.
Disadvantages of DBMS:
User User
Application Server
Database
9 M N Ravindra Department of Computer Science
Database
Application srever
Server
Database Architecture:
A database Architecture is shown below depending upon the three tier architecture. It
contains of 3 levels.
Internal level:
10 M N Ravindra Department of Computer Science
The internal schema defines the internal level. The internal level is the lowest level of data
abstraction. This level indicates how the data will be stored into the database and describes
the file structures and data structures and methods to be used by the data base.
Conceptual level:
The conceptual schema defines the conceptual level. The conceptual level in the middle
level abstraction. This level indicates entities, attributes, relationship between entities and
attributes.
External level:
External schema defines the external level. The external level is the highest level of data
abstraction. This level describes part of database. i.e., relevant to the user.
Data independency:
Data independency is the characteristic of database. To change the schema at one level
without changing the schema at the higher level. There are two types of data independency as
shown below.
Database Systems:
The database system is composed of the five major components.
1. Hardware
2. Software
3. People
4. Producers
5. Data
Data Models
Data model:
A data model is a collection of concepts that can be used to describe the structure of a
database
Data modeling in the first step in designing a database refers to the process of creating a
specific data model for a problem.
A model is an abstraction of a real world object. A data model represents data structures
and their characteristics, relations, constraints and transactions.
Data model is an iterative process we start with a simple understanding of the problem
increases, and finally design a database in a specific database model.
1. Data Model can facilitate interaction among the designer, the application programmer and
the end user.
2. Applications are used to transform data into information. But data are viewed in different
ways by different people.
3. For e.g. the manager and clerk both are working in the same company, the manager have
wide view of company data than the clerk.
4. A company president has universal view of data.
5. Different Managers views data differently in a company. The inventory manager is more
concerned about inventory levels, while purchasing manager concerned about items and
supplies.
6. Application programmers have another view of data i.e., concerned with data locations
and formatting.
7. A house is a collection of roots, if someone is going to build a house, they have the overall
view i.e., provided by blue print. A sound data environment requires an overall database
blue print based on appropriate data model.
8. When a good database blue print is available, an application programmer view of data is
different from the managers and end users. When a good database blue print is not
available problems are likely to ensure.
The basic building blocks of data models are entities, attributes, relationships and
constraints. An entity represents a real world object person (or) place.
For e.g. customer entity have attributes customer_no, customer_name, customer_address etc.
A relationship describes an association between entities. Data models use three types of
associations. One-to-many, many-to-many and one-to-one.
One-to-many (1:M, 1…..*): A painter paints many different paintings. Therefore, the
database designer label the relationship PAINTER PAINTS PAINTINGS as one-to-many.
Many-to-many (M:N, *…….*): An employee may learn many job skills and each job skill may
be learned by many employees. Therefore, the database designer label the relationship
Employee learns skills as many-to-many (M:N).
One-to-one (1:1, 1…….1): Each store manager manages only a single store. Therefore, the
data designer label the relationship employee manages stores as one-to-one (1:1).
By using the business rules we can properly identify entities, attributes, relationships and
constraints.
Business rules:
The first business rule establishes two entities (customer, invoices) and a one-to-many
relationship between these two entities.
The 2nd business rule establishes a constraint. (No fewer than 10 people (or) more than
30 people) and two entities (training, people) and a relationship between employee and
training.
General rule: A noun in a business rule be translate into an entity in that model, and a verb
associating nouns will translated into a relationship among the entities.
For e.g. the business rule “ customer may generate many voices “
Containing two nouns (customer and invoices) and a verb (generate) that associates the
noun.
For e.g. the business rule “ A customer may generate many invoices”, the relationship is
one-to-many (1:M, 1…….*). Customer is the 1 side and invoice is the many side.
Objectivity
Extended Relational
Model
The hierarchical data model is the oldest type of data model, developed by IBM in 1968. This
data model organizes the data in a tree-like structure, in which each child node (also known
as dependents) can have only one parent node. The database based on the hierarchical data
model comprises a set of records connected to one another through links. The link is an
association between two or more records. The top of the tree structure consists of a single
node that does not have any parent and is called the root node.
1. The hierarchical data model consists of a set of nested relationships one-to-many and one-
to-one association.
2. In hierarchical data model the relations are presented in the form of tree-structure in
which the root segment is kept at the top and further branches emanate downwards from
the root segment.
3. In this model the type of association can be one-to-one and one-to-many. This means that
many-to-one association is not permitted. This is equivalent to say that multiple
percentages for a child segment is not permitted.
The above conceptual data model can be mapped into any one ways as shown below.
1. The association from student to enrollment is one-to-many. This mapped without any
modifications.
2. The association from enrollment to subject is many-to-one. This is not permitted in
hierarchical data model. Hence it is modified into one-to-one association.
3. The association from subject to faculty in many-to-one. This is not permitted in
hierarchical data model. Hence it is modified into one-to-one association.
In alternative1 while mapping the conceptual data model into hierarchical data model,
the many-to-one association presents at two levels are modified into one-to-one association.
These modifications will increase the data redundancy.
In alternative2 the faculty file is kept at the root of the tree and student file is kept at
the bottom of the tree. While mapping the conceptual data model the following facts are
observed.
1. The association from faculty to subject file is one-to-many. So it is mapped without any
modifications.
2. The association from to subject enrollment is many-to-one. This is not permitted in
hierarchical data model. Hence it is modified into one-to-one association.
3. The association from enrollment to student is many-to one. This is not permitted in
hierarchical data model. Hence it is modified into one-to-one association.
Finally which alternative has less redundancy should be selected for implementation.
In alternative2, the association change between enrollment and student. That means we
are changing one type. When we compare alternative2 with alternative1, alternative2 has less
redundancy and it is implemented.
Advantages:
22 M N Ravindra Department of Computer Science
1. It promotes data sharing.
2. Parent/Child relationship promotes conceptual simplicity.
3. Database security is provided and enforced by DBMS.
4. Parent/Child relationship promotes data integrity.
5. It is efficient with 1:M relationships.
Disadvantages:
1. Complex implementation requires knowledge of physical data storage characteristics.
2. Changes in structure require changes in all application programs.
3. There are implementation limitations (no multi parent or M:N relationships).
4. There is no data definition or data manipulation language in the DBMS.
5. There is a lack of standards.
A Network data model consists of a set of pair wise association between the entities.
The Network data model was created to improve database performance, database
standards and represent complex relationships effectively than the hierarchical data model.
1. Schema: The schema provides overall view of the database to the administrator.
2. Sub Schema: The sub schema which defines the portion of the database seen by the
application programs.
3. Database Management Language: That defines the environment in which data can be
changed. The DBTC specify 3 DML components.
a. A schema data Definition Language (DDL), which enables the data base administrator
to create the database.
b. A subschema DDL, which allows the application programs to define database
component that will be used by the application.
c. A Data Manipulation Language, to manipulate the data in the database.
In Network database, a relationship is called a set. Each set contains two entities one
entity is owner and other entity is member.
Advantages:
3. Data access is more flexible than in hierarchical and file system models.
6. It includes data definition language (DDL) and data manipulation language (DML) in DBMS
Disadvantages:
The relational model was introduced in 1970 by E.M.Codd. The foundation of relation is
a mathematical concept known as relation. The Relation is composed of intersecting rows and
columns. Each row in a relation represents a tuple. Each column represents an attribute.
Agent
Customer
By matching the Agent_Code in the customer table with Agent_Code in the Agent table we can
find Agent details of that customer.
A relationship diagram is a representation of entities, the attributes within the entities and
the relationship between the entities.
Agent Customer
Agent_Code Cust_No
Agent_Name Cust_name
Agent_Address Cust_Address
Agent_PhoneNo Phone_No
In the above diagram, the relationship is one-to-many. The symbol ∞ indicates many.
The customer represents “many” sides, because an AGENT can have many CUSTOMERS.
26 M N Ravindra Department of Computer Science
The AGENT represents the “1” side because each CUSTOMER has only one AGENT.
The languages which are supported to relational data model is powerful and
flexible. Because of that the relational data model is popular. FoxPro, database,
M.S.Acess, SQL are relational database software’s. This software’s allows the user to
specify what must be done without specifying how it must be done.
SQL based database applications involves 3 parts. 1. End user interface. 2. Set of tables
stored in the database. 3. SQL Engine.
Advantages:
4. Powerful RDBMS isolates the end user from physical-level details and improves
implementation and management simplicity.
Disadvantages:
2. Conceptual simplicity gives relatively untrained people to use a good system poorly, and if
unchecked, it may produce the same data anomalies found in file systems.
Peter Chen first introduced the E.R.data model in 1976; it was the graphical
representation of entities and their relationship in a database.
a. Entity: entities are the real time objects. Entities represented by a rectangle.
e.g. painter, employee, skills, noun.
b. Attribute: Attributes are the characteristics of entities.
e.g. Empno, Empname, Empaddress etc.
1. Chen notation
2. Crow’s foot notation.
For different types of relationships.
CHEN NOTATION
In Chen notation, entities are represented rectangle and entity names are written in the
capital letters at the centre of the rectangle. Relationships are represented by a diamond. The
diamonds are connected to entities through a relationship name is written inside the
diamond.
In the crows foot notation, the crow foot is derived from the three pronged symbol used
to represent many relationships. In this notation, the one represented by a short line
Advantages:
1. Visual modeling yields exceptional conceptual simplicity.
2. Visual representation makes it an effective communication tool.
3. It is integrated with dominant relational model.
Disadvantages:
1. There is limited constraint representation.
2. There is limited relationship representation.
3. There is no data manipulation language.
4. Loss of information content occurs when attributes are removed from entities to avoid
crowded displays. (This limitation has been addressed in subsequent graphical versions)
For E.g. Let us use invoice program. In this case the invoices are generated by customer, each
invoice contains one (or) more lines, and each line represents an item purchased by
customer.
The UML class diagram uses 3 separate classes (customer, invoice and line) and two
relationships to represent this problem.
The E.R Model also uses the 3 separate entities and two relationships to represent the
invoice problem.
Advantages:
Disadvantages:
1. Slow development of standards caused vendors to supply their own enhancements, thus
eliminating a widely accepted standard.
Chapter -3
Relational Database Model
31 M N Ravindra Department of Computer Science
In Relational Data base model records are stored into tables. Relational data model is easier
to understand than the hierarchal data models and network data models. Relational data model
provides a logical view of the data and its relationship among other data.
Tables and Characteristics:
A Table is composed of rows and columns. Each row of the table is called as tuple. Each
column of the table is called as attribute. A table is also called as Relation. A table contains a
group of related entities.
Characteristics of a Table:
1. A table is composed of rows and columns.
2. Each row of the table represents one entity (tuple) in the entity set.
3. Each column represents an attribute and each column has distinct name.
4. Each cell represents a single value.
5. All values in a column must have same data format.
6. Each column has a specified range of values which is called domain.
7. The order of the rows and columns is immaterial to the DBMS.
8. Each table must have an attribute or group of attributes that uniquely identified each
row.
Keys
Key field or Primary Field:
A key consists of one or more attributes that determines other attributes. For example, an
invoice number identifies attributes such as invoice date, customer details, items details and
amount.
The statement “A DETERMINES B” indicates that if we know the value of attribute A then
determine the value of B.
Eg: In the student table if we know the value of student number then determines student last
name, st_fname, stu_inital. This can be represented in the following way.
STU_NUMSTU_LNAME, STU_FNAME, STU_INIT.
Functional Dependency:
The term Functional Dependency can be defined for “A DETERMINES B”, if each value in a
column “A” determines only one value in column B.
32 M N Ravindra Department of Computer Science
Eg: STU_NUM functionally determines STU_LNAME ( or STU_LNAME functionally depends on
STU_NUM).
STU_NUM STU_LNAME.
Super Key : A sub set of Attributes that uniquely identifies a tuple(row) in a relation(table).
Eno Ename Salary Dept_no Voter_Id
{Eno } No two rows have same Eno ( Eno uniquely identifies a tuple(row) in a
relation)
{Ename } Two employee’s may have same name.
{Voter_id} No two rows have same Voter_id (Voter_id uniquely identifies a tuple(row) in a
relation)
{Eno, Ename } Eno itself uniquely identifies a tuple(row) in a relation, hence combination of
Eno and
Ename also uniquely identifies a tuple(row) in a relation
Note :
A Relation(table) can have many Superkeys, and also many Minimal Superkeys.
If a Relation(table) has more than on Minimal Superkeys each can be called as Candidate
Keys.
One of the candidate keys is arbitrarily designated to be the primary key, and the others are
called secondary keys(or Alternative key).
Key Hierarchy
Foreign Key:
A foreign key is an attribute whose values match the primary key values in the related
table.
(FK)
In EMP table Eno is Primary Key. (Duplicates and Null values are not allowed in Eno)
(PK)
10 MTech BVRM
20 MBA HYD
30 MCA BVRM
Integrity Rules:
Integrity rules are used in the database design.
1. Entity Integrity: All primary key entries are unique and no part of the primary key may
be NULL.
Example: In Agent table the agent_code is primary key and this column is free from
null values.
2. Referential Integrity: A foreign key is an attribute whose values match the primary key
values in the related table.
Example: The vendor_code is the primary key in the vendor key and it occurs as a
foreign key.
3. NOT NULL: NOT NULL constraint can be placed in a column while inserting a row that
column must have a value.
4. Unique: Unique constraint can be placed in a column while inserting a row that column
have unique values. (No duplication).
Product 2
2. INTERSECT:
3. DIFFERENCE:
The DIFFERENCE operator gives all rows in one table that are not found in other table.
STUDENT EMPLOYEE
5. SELECT:
The SELECT operator gives all rows that satisfies a given condition.
6. PROJECT:
39 M N Ravindra Department of Computer Science
The PROJECT operator gives all values for selected attributes. In other words project gives
a vertical subset of tables.
7. JOIN: The JOIN operator combines rows from 2 or more tables. There are several types of
joins.
a. Natural Join
A Natural Join joins tables by selecting the rows with common values in their common
attributes. A natural join is the result of a three-stage process:
1). First, a PRODUCT of the tables is created, yielding the results shown in Figure 3.12.
3). A PROJECT is performed on the results of Step b to yield a single copy of each attribute,
thereby eliminating duplicate columns.
The final outcome of a natural join yields a table that does not include unmatched pairs and
provides only the copies of the matches.
Product:
Prod_code Prod_Descp Vend_code
Vendor:
Vend_code Vend-name
V101 ravi
V102 ram
V103 krishna
Result:
Prod_code Prod_Descp Vend_code Vend-name
Outer Join:
In the Outer Join the matched pair of records would be written and any unmatched
values in other table would be NULL.
Product:
Prod_code Prod_Descp Vend_code
Vendor:
Vend_code Vend-name
V101 ravi
V102 ram
V103 krishna
Result:
8. DIVIDE:
The DIVIDE operator uses one single column table as a deviser and two column table as
the dividend. The output of DIVIDE operator is a single column with a values column-A
from the dividend table rows where the values of the common column in both tables
match.
Data Dictionary:
The Data Dictionary provides a description of all tables in the database. The Data Dictionary
contains attribute names and characteristics of each table in the system. The data dictionary
contains meta data.
Example:
One-to-One
In this relationship one entity of one table is associated with one entity of other table and
vice-versa.
Consider the PROFESSOR AND DEPARTMENT. The ER data model and implementation are
shown in below.
In above each and every entity of student file is associated with one or more entities of the
subject table because each student will opt one or more subjects in a semester.
Each and every entity of subject file is associated with one or more entities of student table
because each sub will be opted by more than one student in a semester. Many to Many
associations are not supported.
Hence the relationship will be converted into two one to many associations are as shown
below by introducing an intermediate table in which the common data of the original file are
stored.
Index: An Index is composed of and index key and set of points. Each key points to the
location of data identified by the key.
Example: Suppose we want to look up all of the paintings created by the given painter
without an index, we must read each row in the painting table. If we index the painter table
and use the index key of painter number, we look up appropriate painter number in the index
DBMSs use indexes for many different purposes. You just learned that an index can be
used to retrieve data more efficiently. But indexes can also be used by a DBMS to retrieve
data ordered by a specific attribute or attributes.
For example, creating an index on a customer’s last name will allow you to retrieve the
customer last name in alphabetical ordered.
Indexes play an important role in DBMS for implementation of primary keys. When we
define a table primary key the DBMS automatically creates an unique index on the primary
key column.
When we declare the customer-code to be the primary key of the customer table, the
DBMS automatically creates a unique index on that attribute.An unique index is an index in
which the index key can have one pointer.
Chapter - 4
Entity Relationship Modeling
49 M N Ravindra Department of Computer Science
The Entity Relationship modeling forms an Entity Relationship diagram. The ERD represents
the conceptual database. The Entity Relationship diagram contains mainly three components.
Entity, Attribute and Relationship.
Entity: An Entity represents a real world object.
Eg: Student, Customer, Employee, Subject, Faculty, and Product
In chen and crow foot notation an entity is represented by rectangle containing entity name.
The entity names usually return in capital letters.
In the cross foot Notation the attributes are written in the attribute box below the entity
rectangle.
Derived Attribute: A Derived Attribute is an attribute whose values are calculated from
other Attributes.
Eg: An Employee age computing difference between current data and the employee date of
birth.
A Derived Attribute is indicated in a chen’s Notation by a dashed line by the connecting to the
attribute and entity.
A Relationship exist if the primary key of the related by contains a primary key
component of the parent entity. The relationship between course and class is strong because
the class entity composite entity key is composed of class_code+ Crs_code. The class primary
key inherit the primary key component from the course entity. In the strong relationship we
can write ‘o’ symbol next to the entity.
Weak Entity: In Weak Entity the primary key is primary key is partially as totally derived
from the parent entity in the relationship .For example: The dependent entity key was
inherited from the employee entity as show below.
Strong Entity: In Strong entity the primary key has not partially or totally derived from the
parent entity in the relationship. For example in the course and class relationship the class
table primary key is class code which is not derived from the course parent key. The entity
class is a strong entity.
Class(class_code, course_code,class_desc,class_time, prof_code)
In the Course and Class relationship is composed of class_code and course_code is derived
from the course parent entity. The entity class is a weak entity.
Class(class_code, course_code, desc,class_time, prof_code)
Relationship Participation: The Relationship Participation between the entities is either
optional or mandatory.
Optional participation
Optional participation means that one entity occurrences does not require a corresponding
entity occurrence in a particular Relationship.
Eg: “course generate class” relationship an entity occurrence in the course table does not
necessary require the corresponding entity occurrences in the class table.
In the crows foot notation an optional relationship between entities is shown by drawing a
circle on the side of optional entity. The minimum cardinality is zero for the optional entity.
The cardinality (1,1) represents one class is taken by one professor. The cardinality (0,3)
indicates the professor may teach no classes or theory classes.
The following table shows various cardinalities that are supported by crow’s foot notation.
Relationship Degree: A Relationship Degree indicates the number of entities associated with
a relationship.
A Unary Relationship: A Unary Relationship exists when an association is maintained within
a single entity.
Eg: An Employee within the employee entity is the manger for one or more entities within
that entity.
One to Many: A One to Many unary relationships may be expressed by an employee may
manage many employees.
Developing an ER diagram:
6. Each professor may teach the classes. A professor may not teach the class.
7. A student may enroll several classes, each class contains several students. Student is
optional to class in the many to many relationships. This many to many relationship
must be divided into two one to many relationship through many enroll entities.
Database designers often must make design compromises that are triggered by conflicting
goals, such as adherence to design standards (design elegance), processing speed, and
information requirements.
Design standards:
The database design must conform to design standards. Such standards have guided you in
developing logical structures that minimize data redundancies.
In short, design standards allow you to work with well-defined components and to evaluate
the interaction of those components with some precision.
Processing speed:
In many organizations, particularly those generating large numbers of transactions, high
processing speeds are often a top priority in database design.
High processing speed means minimal access time.
If the focus is on data-retrieval speed, you might also be forced to include derived attributes
in the design.
Information requirements:
The quest for timely information might be the focus of database design. Complex information
requirements may dictate data transformations, and they may expand the number of entities
and attributes within the design.
Therefore, the database may have to sacrifice some of its “clean” design structures and/or
some of its high transaction speed to ensure maximum information generation.
A design that meets all logical requirements and design conventions is an important goal.
However, if this perfect design fails to meet the customer’s transaction speed and/or
information requirements, the designer will not have done a proper job from the end user’s
point of view.
Compromises are a fact of life in the real world of database design.
Even while focusing on the entities, attributes, relationships, and constraints, the designer
should begin thinking about end-user requirements such as performance, security, shared
access, and data integrity.
Finally, prepare the document! Put all design activities in writing. Then review what you’ve
written.
Chapter - 5
62 M N Ravindra Department of Computer Science
Normalization of Database Tables
Def:
The normalization process is used to create a good table structure to minimize data
redundancy.
Business Databases: Business databases are sufficient to normalize to 2NF or 3NF. The
other stages are
DeNormalization produces a lower normal form i.e., 3NF will be connected into 2NF
will be converted.
The Easiest way to generate the required report to create a table that table has some fields of
the Report.
For example: Employee number 104 has been assigned to two project .Therefore knowing the
project _no and employee no will find the job classification and house worked. Therefore
project_No and emp_no will be taken as primary key.
1. The project _no is a part of primary key. But it contains null values.
2. The table entries invites data inconsistency for example job classification value
Electrical_Engineer might be entered.Elec_engi ,EE
3. The table displays data redundancy.
Update Anomalies: Modify the job class for Employee_No 105 requires many
alternatives.
Insertion Anomalies: To complete a row definition of a new employee must be
assigned to a project. If the employee is not assigned, a dummy project must be created
to complete the row.
Deletion Anomalies: Suppose only one employee is associated with a project, if that
employee leaves the company and the employee data are deleted, the project
information will also be deleted.
The above deficiency of table structure appears to work, the report gives
different results depending on data.
Normalization Process: The most common Normal forms and their characteristics are
1. First Normal Form (1NF): A Relation is said to be in first normal form if it is already
in un normalized form and it has no repeating group.
2. Second Normal Form (2NF): A Relation is said to be in second normal form if it is
already in first normal form and it has no partial dependency.
3. Third Normal Form (3NF): A Relation is said to be in third Normal form if it is
already in second normal form and it has no transitive dependency.
4. Boyce code Normal Form(BCNF): A Relation is said to be in Boyce code Normal form
if it is already in third normal form and every determinant is a candidate key.
5. Fourth Normal Form (4NF): A Relation is said to be in fourth normal form if it is
already in Boyce code normal form and it has no multi valued dependency.
6. Fifth Normal Form(5NF): A Relation is said to be fifth normal form if it is already in
fourth normal form and it has no loss less decompose.
The construction company report is represented in the form of relation. The relation named
as CONSTRUCTION_COMPANY this is in un normalized form as shown below
CONSTRUCTION_COMPANY(Proj_No,Proj_Name,(Emp_No,Emp_Name, Job_Classification,
Charge_Per_Hour, Hours_ Billed) ----- (1)
The field Total charge, SUB TOTAL,GRAND TOTAL are not included in the relation because
they are derived Attribute.
Database Keys
Super Key
Super Key is defined as a set of attributes within a table that uniquely identifies each record
within a table. Super Key is a superset of Candidate key.
Candidate Key
Candidate keys are defined as the set of fields from which primary key can be selected. It is an
attribute or set of attribute that can act as a primary key for a table to uniquely identify each
record in that table.
Primary Key
Primary key is a candidate key that is most appropriate to become main key of the table. It is
a key that uniquely identify each record in a table.
Composite Key
Key that consist of two or more attributes that uniquely identify an entity occurance is called
Composite key. But any attribute that makes up the Composite key is not a simple key in its
own.
Non-key Attribute
Non-key attributes are attributes other than candidate key attributes in a table.
In Relation (1), the fields in the inner most set of parenthesis put together is known as
repetating group. This will result in redundancy of data for the first two relations remove the
repetating group.
Now above relation (2) & (3) are in 1NF. In relation (3) Proj_No , Emp_No jointly serve as key
field.
One non key attribute is depending on the part of the composit primary key then
it is said to be Partial Dependency.
In Relation 2 the number key fields is only one and hence there is no scope for partial
dependency the absence of partial dependency in relation 2 takes it 2NF without any
modification.
Emp_Job(Emp_No,Emp_Name,Job_Class,Charge-Per_Hour)--------------(5)
Transitive Dependency:
If one non prime attribute is determines the other non prime attribute then it is
called as transitive dependency..
In Relation (2) there is only one non key field. This means that it has no transitive
dependency. Hence Relation (2) can be treated as 3NF without any modification similarly in
relation (4) there is only one non key field. This means that it has no transitive dependency.
Hence relation (4) can be related as 3Nf in without any modification.
Hence relation (5) is sub divided into two relations. Relation (6) and relation (7) as shown
below.
Job(Job_Class, Charge_Per_Hour)-----------------(6)
Emp(Emp_No,Emp_Name,Job_Class)------------(7)
The process of normalization is stopped and the final 3NF relations of construction company
as shown below.
Project(Proj_No,Proj_Name)---------------------------------(1)
Emp(Emp_No,Emp_Name,Job_Classification)------------(3)
Job(Job_Classification, Charge_Per_Hour)----------------(4)
Improving Design:
Candidate key:
A key is said to be candidate key if the superkey that does not contain a subset of
attributes ie the key itself a superkey.
A+B -------------C,D
C ---------- B
The table structure has no partial dependency and there is no transitive dependency. But the
condition C ---B indicates that a nonkey attribute determines the part of key the primary
key and that dependency is not transitive.
Thus the above diagram meets the 3NF but not the BCNF requirements.
To convert the above table structure from 3NF to BCNF, first change the primary key to A+C.
The dependency C---B means that C is in effect a superset of B. The Decomposition
procedures to produce the results shown below.
Each Class_Code identifies a class iniquely. A student contains many classes and earning the
grades respectively. A staff member can teach many classes. But each class is taught by only
one staff member.
Class_Code ---------------Staff_Id
The above table contains two candidate keys to violets the BCNF. Now we can eliminate the
one candidate key from the above table.
Consider an employee can have multiple assignment i.e, that employee works as an
volunteer in service organization and worked in different projects which is shown below
In volunteer-3 table has a primary key but it is composed of all attributes of the table.
When you consider like this it produces many redundancies.To eliminate multi valued
dependency by creating the assignment and service tables as shown below.
In the Assignment table and service table does not contain multi valued dependency
De Normalization produces lower normal forms 3Nf will be converted to 2NF or 2Nf
will be converted to 1NF.Eg: The need for de normalization due to generate evaluation of
faculty report in which each row list the scores of obtaining during the last 4 semester taught.
instructor Dept. Sem- Mean Sem- Mean Sem- Mean Sem- Mean Last_sem
1 2 3 4 avg
We can generate easy above the report but the problem arises. The data are stored in a
normalized table. In which each row represented a different score for a given faculty in a
given semester.
EVALDATA:
It is some difficulty to generate faculty evaluation report the normalized table. The other table
FACHLST faculty history table contains the last four semester mean for each faculty .The faculty history table is
a temporary table created from the evaldata as shown below.
Instructor Dept. Sem- Mean Sem- Mean Sem- Mean Sem- Mean Last_sem
1 2 3 4 avg
The FACHIST is a un normalized from table using the table we can generate .The faculty
evaluation report very firstly. After generating the report, the temporary table, FACHIST will
be deleted. We are doing like this, we can increase. The performance of the database
Chapter – 6
75 M N Ravindra Department of Computer Science
Advanced Data Modeling
In an Organization contains different types of employee and all the employees are not
having the same attributes. If you create a one table for all employees to store their
information many columns have null values.
For Example the pilot shares certain characteristics with other employee. Such as employee
no, emp_name, emp_address, Employee hire date on the other employees. The pilot
characteristics are not shared by other employee. The pilot characteristics are employee
license and employee rating will generates nulls for employees who are not pilot.
The pilot entity store only the attributes that are unique to pilot, and the employee
entity store attribute that are common to all employees.
We can conclude that pilot is a sub type of employee and employee is a super type of
pilot. An entity super type is a generic type i.e, related to one or more entity.
Specialization Hierarchy:
Entity super types and sub types are organized in a hierarchy which describes the
higher level entity super types and lower level entity sub types.
The following diagram shows specialization hierarchy by an employee super type and three
entity sub types.
Eg:
Inheritance:
The property of inheritance enables an entity subtype, to inherit the attributes and
relationships of the super type.
77 M N Ravindra Department of Computer Science
In the above example the employee entity participating in a one-to-many relationship with a
dependent entity through inheritance.
Subtype Discriminator:
A sub type discriminator is the attribute in the super type entity that determines to
which sub type; the super type occurrence is related.
If the emp_type has a value of p the super type is related to pilot sub type.
If the emp_type has a value of A the super type is related to Account subtype.
If the emp_type has a value of M the super type is related to mechanic subtype.
The Disjoint subtypes are indicated by the letter ‘d’ inside the category shape. In
disjoint the super type entity is related to only one sub entity types.
Eg: An employee who is a pilot can appear only in the pilot sub type, not in any of other sub
types.
The Overlapping subtypes are indicated by the letter’ o’ inside the category shape. In
the overlapping the super type entity is not relate to only one sub entity types.
Partial completeness means that not every super type entity is related to a sub type
entity. A single horizontal line under the circle represents a partial constraint O.
Total completeness means that every super type is related to latest one sub type. A double
horizontal line under the circle represents the total completeness constraint.
Specialization is the top down process of identifying lower level entity sub type from a higher
level entity super type.
Eg: The specialization is used to identify multiple entity supply (Pilot, mechanic, Accountant)
from the super entity employee.
Generalization is the bottom-up process of identifying higher level entity super types from a
lower level entity sub types.
Eg: The Generalization is used to identify entity super type from the sub type (Pilot,
mechanic, Accountant).
Entity Clustering:
Generally the data modeler will develop an initial ERD containing a few entities. As the
designed approach completion the ERD will contain hundreds of entities and relationships. In
those cases, we can use entity cluster to minimize the number of entities in the ERD.
An entity cluster is a virtual entity type used to represent multiple entities and the
relationship in the ERD.
An entity cluster is formed by combining multiple inter related entities into a single
entity object. An entity cluster is considered virtually in the sense that it is not actually an
entity in the final ERD.
The most important characteristics of an entity is its primary key, which uniquely
identifies each entity instance. The primary key and foreign key works together implement
relationship between the tables in the relational data model.
The unique identifies is commonly uncounted in the real world. For example class_no
to register for classes, Invoice_no to identify a particular invoice, Account-no., to identify
credit cards and soon. These Examples contains natural keys.
The natural keys class_no, invoice_no, account_no is used to uniquely identify the real
world objects.
The primary key main function is to uniquely identity an entity for a given primary key
value the relational model can determine values of all dependent attributes.
The second function is primary key and foreign key implement relationship between
tables or entities.
A primary key contains unique values and not accept the null values.
The primary key should be permanent and unchangeable
A primary key should have the minimum number of attributes.
In the first case assume that we have a student entity and class. Entity and the relationship
between these two entities is many to many via enroll entity. The enroll entity contains key
fields of student entity and class entity which is used to identity entity instance in the enroll
entity.
Eg: The key field of employee entity is used one of the key filed of dependent entity.
Emp(Emp_no, Emp_Fname,Emp_Lname,email)
These are some instances when a primary key does not exist in the real world object.
(or)
When the existing natural key is not suitable as primary keys.
For Example: Consider the facility that rent for rooms for small parties. The manager of the
facility keep the all the events in the following table formats.
In the above entity there is no simple natural keys i.e, used as a primary key in the model.
Based on the concept of primary key we suggest one of these options (Date, Time_start,
Room) or (Date, Time_End, Room).
1. When Implementation of data model, the composite primary key in the event entity
makes complexity and also coding.
2. The solution to the problem is to use a numeric single attribute as surrogate primary
key.
Unit-3
84 M N Ravindra Department of Computer Science
Unit-III: Interaction with Databases and Construction of Information System:
3.1 Introduction to SQL:
Data Definition Commands,
Data Manipulation Commands,
Select queries,
Advanced Data Definition Commands,
Advanced Select queries,
Virtual Tables,
Joining Database Tables.
3.2 Advanced SQL:
Relational Set operators,
SQL Join Operators,
Sub queries and correlated queries,
SQL Functions,
Oracle Sequences,
Updatable Views,
Procedural SQL.
3.3 Database Design:
The Information System,
The Systems Development Life Cycle,
The Database Life Cycle,
Database Design Strategies,
Centralized Vs Decentralized design.
Introduction to SQL
DDL is abbreviation of Data Definition Language. It is used to create and modify the
structure of database objects in database.
Create:
Create table <table name>(column name1 data type, column name2 data
type………..column name n data type);
Alter:
Syntax:
Example:
The Student table is already exist and then we added two more
columns Age and Marks respectively, by the use of above command.
Syntax:
Example:
Syntax:
Example:
The Name column already exist in Student table, it was char and size 30, now it is
modified by Varchar2 and size 40.
Using the ALTER TABLE clause the following tasks cannot be performed.
Rename:
Syntax:
Example:
Drop:
Truncate:
DML commands:
Select:
Insert:
Insert into <table name> values (&column name, &column name……&column name);
Syntax:
Ex:
Delete:
Ex:
DCL commands:
REVOKE – Withdraws user’s access privileges to database given with the GRANT command
Grant:
Syntax:
Ex:
Revoke:
Syntax:
Ex:
Commit:
Syntax:
Commit;
Rollback:
Syntax:
Rollback;
Rollback to <save-point>
Save point:
Syntax:
Ex:
Data Types
• CHAR(size)
– Used to store character strings. The size determines number of characters the
cell can hold. The max number is 255 Characters
• VARCHAR(size)/VARCHAR2(size)
– Used to represent date and time. The standard format is DD-Mon-YY as in 03-
dec-08. If we want to change date function use appropriate function. Valid date
range is Jan 1,4712 B.C to December 31,4712 A.D.
• NUMBER(p,s)
• LONG
• TIME STAMP
• ROWID
– Fixed length binary data. Every record in the data base has unique Physical
Address. The format is BBBBBBB.RRRR.FFFFF where BBBBBBB is the block in
database file, RRRR is the row in the block and FFFFF is the database file
• BFILE
– File locator that points to a read-only binary object outside the database. Up to 4
GB.
• BLOB
• CLOB
DATA CONSTRAINTS
• Oracle permits data constraints to be attached to table columns via SQL Syntax
• Once data constraints are part of table column construct, the Oracle database engine
checks the data being entered into a table column against the data constraints.
90 M N Ravindra Department of Computer Science
• If the data passes this check, it is stored in the table column else it is rejected.
• Both CREATE TABLE and ALTER TABLE SQL syntax are used to attach constraints
• Once these constraints are attached data must be carefully loaded into the database.
• Primary Key is one or more columns in a table used to uniquely identifies a row.
Foreign Key
• It is a column whose values are derived from the primary key or unique key of some
other table or same table also
• The foreign key columns in the master and child tables must be of same data type
• Syntax
• Syntax
Unique
• Unique key can combine upto 16 columns to from composite unique key
• UNIQUE(<ColumnName1>, <ColumnName2> )
NULL
• A null value is not equal to zero we set null when the value is unknown
• Syntax
– Example
CHECK
• Syntax
Assigment:
Table created
SQL>desc sailors;
SNAME VARCHAR2(10)
RATING NUMBER(1)
AGE NUMBER(3,1)
Table created
SQL>desc boats;
BNAME VARCHAR2(10)
COLOR VARCHAR2(10)
SQL>desc reserves;
DAY DATE
PK PK
RESERVES (Child)
FK FK
Composite PK
Insert data into Sailors, Boats and Reserves table in the same order
22 Dustin 7 45.0
29 Brutus 1 33.0
94 M N Ravindra Department of Computer Science
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rusty 10 35.0
64 Horatio 7 35.0
71 Zobra 10 16.0
74 Horatio 9 35.0
85 Art 3 25.5
95 Bob 3 63.5
22 101 10-10-98
22 103 10-10-98
22 104 10-7-98
31 102 11-10-98
31 103 11-06-98
31 104 11-12-98
64 101 9-5-98
64 102 9-8-98
74 103 9-8-98
sid in Sailors
BID in Boats
SID,BID in reserves
The following restrictions are followed for fields which are declared as foreign key
To insert records into sailors and boats there is no restriction , but to insert record into
reserves we must have the particular record with sid and bid values in sailors and boats
tables.
To update a record in reserves we will have the restriction that only the updating are
allowed up to the values in sailors table
Deletion in reserves has no restriction but to delete a record from sailors and boats the
records must not have references in child.
We can allow the updating and deleting in parent and child by using the following
syntax
PRIMARY KEY(sid,bid),
This syntax will carry updating and deleting in parent to child without above
restrictions.
By using the following syntax we can change the column’s data type of a particular
table.
97 M N Ravindra Department of Computer Science
Note: Some RDBMS, such as Oracle, do not let you change data types unless the column
to be changed is empty.
Syntax:
If you want to increase the width of the column data type size, use the following
syntax.
Syntax:
Ex:
If you want to add new column to the existing table, use the following syntax;
Syntax:
Ex:
Dropping a column:
If you want to delete a column to the existing table, use the following syntax;
Syntax:
Ex:
1. Order by
2. Group by
3. Having by
Order by Clause:
Syntax:
SQL ORDER BY
The ORDER BY clause is used in a SELECT statement to sort results either in ascending
or descending order. Oracle sorts query results in ascending order by default.
SELECT column-list
FROM table_name [WHERE condition]
[ORDER BY column1 [, column2, .. columnN] [DESC]];
The query first sorts the result according to salary and then displays it.
You can also use more than one column in the ORDER BY clause.
If you want to sort the employee table by the name and salary, the query would be
like.,
NOTE: The columns specified in ORDER BY clause should be one of the columns
selected in the SELECT column list.
You can represent the columns in the ORDER BY clause by specifying the position of a
column in the SELECT list, instead of writing the column name.
The above query sorts only the column 'salary' in descending order and the column
'name' by ascending order.
If you want to select both name and salary in descending order, the query would be as
given below.
SELECT name, salary FROM employee ORDER BY name DESC, salary DESC;
For example: If you want to display employee name, current salary, and a 20% increase in
the salary for only those employees for whom the percentage increase in salary is greater
than 30000 and in descending order of the increased price, the SELECT statement can be
written as shown below
Using a group function one can group entire table data and provide a single result,
however you can use the GROUP BY clause to break the result set into logical groupings and
get a result for each group.
The SQL GROUP BY Clause is used along with the group functions to retrieve data
grouped according to one or more columns.
Syntax:
For Example: If you want to know the total amount of salary spent on each department, the
query would be:
NOTE: The group by clause should contain all the columns in the select list expect those
used along with the group functions.
Ex: SELECT location, dept, SUM (salary) FROM employee GROUP BY location, dept;
Having clause is used to filter data based on the group functions. This is similar to
WHERE condition but is used with group functions. Group functions cannot be used in
WHERE Clause but can be used in HAVING clause.
Syntax:
SELECT <column_list> FROM < table name > WHERE <condition> GROUP BY <columns>
[HAVING] <condition>;
If you want to select the department that has total salary paid for its employees more
than 25000, the sql query would be like;
When WHERE, GROUP BY and HAVING clauses are used together in a SELECT
statement, the WHERE clause is processed first, then the rows that are returned after the
WHERE clause is executed are grouped based on the GROUP BY clause.
Finally, any conditions on the group functions in the HAVING clauses are applied to the
grouped rows before the final output is displayed.
Views:
In the SQL language, a view is a representation of one or more tables. A view can be
used to hide the complexity of relationships between tables or to provide security for
sensitive data in tables. In the following example, a limited view of the emp table is created.
When a view is defined, a SQL statement is associated with the view name. Whenever the
view is accessed, the SQL statement will be executed.
Table Created
1 row created
In the following example, the view emp_1 is created as a limited number of columns
(Empno,Ename,salary) and limited set of data ( WHERE salary > 3000 ) from the emp table.
View created.
Once the view is created, it can be queried with a SELECT statement as if it were a
table.
Views can be dropped in a similar fashion to tables. The DROP VIEW command
provides this facility. In the following example, the view just created is dropped.
View dropped.
View can be again created with the same name emp_1 as a limited number of columns
(Empno,Ename,salary,dno) and limited set of data ( WHERE dno=10 ) from the emp table.
SQL> CREATE VIEW emp_1 AS SELECT Empno, Ename, salary, dno FROM emp WHERE
dno=10;
View created.
Once the view is created, it can be queried with a SELECT statement as if it were a
table.
1 row created
The same record will be inserted into base table also and Vice versa
1 row created
The record will not be visible in view because the record does not satisfy the WHERE
dn0=10 condition, but it will be inserted in base table EMP
Actually this record must not be accepted while inserted in view EMP_1 because it
does not hold the condition so we can enable this condition by including WITH CHECK
OPTION in View creation.
View droped.
SQL> CREATE VIEW emp_1 AS SELECT Empno, Ename, salary, dno FROM emp WHERE
dno=10 WITH CHECK OPTION;
View created.
Table altered
SQL> CREATE VIEW emp_2 AS SELECT Ename, salary, dno FROM emp WHERE dno=10 WITH
CHECK OPTION;
View created.
abc 1000 10
def 2000 10
ewd 4000 10
htg 4500 10
This view cannot accept insertion because when it inserts a record it is trying to insert
NULL into primary key field of Base table EMP.
Sub Queries:
A Sub query or Inner query or Nested query is a query within another SQL query and
embedded within the WHERE clause.
A sub query is used to return data that will be used in the main query as a condition to
further restrict the data to be retrieved.
Sub queries can be used with the SELECT, INSERT, UPDATE, and DELETE statements
along with the operators like =, <, >, >=, <=, IN, BETWEEN etc.
A sub query can have only one column in the SELECT clause, unless multiple columns
are in the main query for the sub query to compare its selected columns.
An ORDER BY cannot be used in a sub query, although the main query can use an
ORDER BY. The GROUP BY can be used to perform the same function as the ORDER BY
in a sub query.
Sub queries that return more than one row can only be used with multiple value
operators, such as the IN operator.
The SELECT list cannot include any references to values that evaluate to a BLOB,
ARRAY, CLOB, or NCLOB.
The BETWEEN operator cannot be used with a sub query; however, the BETWEEN
operator can be used within the sub query.
Sub queries are most frequently used with the SELECT statement. The basic syntax is
as follows:
| 6 | Komal | 22 | MP | 4500.00 |
Sub queries also can be used with INSERT statements. The INSERT statement uses the
data returned from the subquery to insert into another table. The selected data in the
subquery can be modified with any of the character, date or number functions.
Example:
WHERE ID IN (SELECT ID
FROM CUSTOMERS) ;
The sub query can be used in conjunction with the UPDATE statement. Either single or
multiple columns in a table can be updated when using a sub query with the UPDATE
statement.
Example:
Following example updates SALARY by 0.25 times in CUSTOMERS table for all the
customers whose AGE is greater than or equal to 27:
SQL> UPDATE CUSTOMERS SET SALARY = SALARY * 0.25 WHERE AGE IN (SELECT AGE
FROM CUSTOMERS_BK WHERE AGE >= 27 );
This would impact two rows and finally CUSTOMERS table would have the following
records:
+----+----------+-----+-----------+----------+
| 6 | Komal | 22 | MP | 4500.00 |
The sub query can be used in conjunction with the DELETE statement like with any
other statements mentioned above.
Example:
Following example deletes records from CUSTOMERS table for all the customers
whose AGE is greater than or equal to 27:
SQL> DELETE FROM CUSTOMERS WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE > 27 );
This would impact two rows and finally CUSTOMERS table would have the following
records:
| 6 | Komal | 22 | MP | 4500.00 |
A query is called correlated subquery when both the inner query and the outer query
are interdependent. For every row processed by the inner query, the outer query is processed
as well. The inner query depends on the outer query before it can be processed.
NOTE:
1) You can nest as many queries you want but it is recommended not to nest more than 16
Sub queries in oracle.
2) If a subquery is not dependent on the outer query it is called a non-correlated subquery.
Here is an example for a typical correlated subquery. In this example we are finding
the list of all employees whose salary is above average for their departments.
SELECT employee_number, name FROM employees AS Bob WHERE salary > ... and
the inner query (the correlated subquery) is
In the above nested query the inner query has to be re-executed for each employee.
Correlated Sub queries may appear elsewhere besides the WHERE clause; for example, this
query uses a correlated subquery in the SELECT clause to print the entire list of employees
alongside the average salary for each employee's department. Again, because the subquery is
correlated with a column of the outer query, it must be re-executed for each row of the result.
SQL FUNCTIONS:
Number functions:
ABS(number)
ABS(expression)
Example:
1.0 .0 1.0
CEIL(number)
Returns the smallest integer greater than, or equal to, the specified numeric expression.
Syntax:
CEILING(expression)
Example:
FLOOR(number)
Returns the largest integer less than, or equal to, the specified numeric expression. Syntax:
FLOOR(expression)
Example:
223.0 -224.000.00
MOD(number, divisor)
Syntax:
POWER(number, power)
8.0
SIGN(number)
Returns the sign i.e. positive or negative value for the numeric expression. It returns -1 for
negative expressions, a value of 0 for zero
Syntax:
SIGN(number)
ROUND(number, precision)
Returns the numeric value rounded off to the next value specified.
Syntax:
Example:
SELECT ROUND(1.3456, 2)
SQRT(number)
Syntax:
SQRT(number)
Example:
116 M N Ravindra Department of Computer Science
SELECT SQRT(4.0)
Output:
2.0
TRUNC(number, precision)
TRUNCATE(number,places)
Example:
1.34
String functions:
1. CONCAT(string1, string2)
2. INITCAP(string)
3. LENGTH(string)
4. LPAD(string, #,padding_char)
5. RPAD(string, #,padding_char)
6. LTRIM(string,searchString)
7. RTRIM(string,searchString)
8. REPLACE(string,searchString,replacement)
9. SUBSTR(string,start,length)
10. UPPER(string)
11. LOWER(string)
CONCAT(string1, string2)
Syntax:
CONCAT(string1, string2)
Example:
Output:
Brad cooper
INITCAP(string)
Returns a string with each word's first character in uppercase and the rest in lowercase.
Syntax:
INITCAP(character-expression)
Example:
Output:
Analyst
LENGTH(string)
Returns the length of the string. Also called as LEN()in sql server.
Syntax:
LENGTH(string)
Example:
Output:
LPAD(string, #,padding_char)
Syntax:
Output:
‘ tech’
RPAD(string, #,padding_char)
Used to pad the string to right to length n characters.string_pad parameter is optional. If not
specified, string will be padded spaces to the right-side of string.
syntax:
Output:
‘tech ’
LTRIM(string,searchString)
Used to remove all white spaces from the beginning of the string.
Syntax:
Ltrim(string)
Example:
Output:
‘sample ’
RTRIM(string,searchString)
Syntax:
Example:
Output:
‘ sample’
REPLACE(string,searchString,replacement)
Syntax:
Example:
SUBSTR(string,start,length)
Displays the string Starting with the th character in string and select the next characters.
Syntax:
SUBSTR(str,pos,len):
Example:
Output:
‘an D’
UPPER(string)
Syntax:
UPPER(string):
Example:
Output:
SAND
LOWER(string)
Syntax:
LOWER(string):
Example:
SELECT LOWER(‘sANd’);
Output: sand
Date functions:
SYSDATE
ADD_MONTHS(Date, months_to_add)
LAST_DAY(Date)
MONTHS_BETWEEN(Date1, Date2)
SYSDATE
SYSDATE
Example:
28-May-2010
ADD_MONTHS(Date, months_to_add)
Returns the month by adding n months to the month of the date specified. Syntax:
add_months( date1, n )
Output: 01-Nov-03
LAST_DAY(Date)
Syntax:
LAST_DAY(date1)
Example:
last_day(to_date('2003/03/15', 'yyyy/mm/dd'))
Output:
MONTHS_BETWEEN(Date1, Date2)
Syntax:
MONTHS_BETWEEN(date1,date2)
Example:
output:
GROUP FUNCTIONS
1. Sum()
2. Avg ()
3. Max ()
4. Min ()
5. Count()
Oracle sequences:
A sequence is a database object, which can generate unique, sequential integer values.
It can be used to automatically generate primary key or unique key values. A sequence can be
either in an ascending or descending order.
By defalult the sequence starts with 1, increments by 1 with minvalue of 1 and with
nocycle, nocache.
Cache option pre-alloocates a set of sequence numbers and retains them in memory
for faster access.
SQL> create sequence s increment by 10 start with 100 minvalue 5 maxvalue 200
cycle cache 20;
USING SEQUENCE
ALTERING SEQUENCE
DROPPING SEQUENCE
Procedural SQL:
Procedures:
Functions: These subprograms return a single value, mainly used to compute and
return a value.
Declarative Part:
It is an optional part. However, the declarative part for a subprogram does not start
with the DECLARE keyword. It contains declarations of types, cursors, constants, variables,
exceptions, and nested subprograms. These items are local to the subprogram and cease to
exist when the subprogram completes execution.
Executable Part:
This is a mandatory part and contains statements that perform the designated action.
Exception-handling:
This is again an optional part. It contains the code that handles run-time errors.
{IS | AS}
BEGIN
The optional parameter list contains name, mode and types of the parameters.
OUT represents that this parameter will be used to return a value outside of the procedure.
IN OUT
An IN OUT parameter passes an initial value to a subprogram and returns an updated value to
the caller.
The AS keyword is used instead of the IS keyword for creating a standalone procedure.
AS
BEGIN
END;
When above code is executed using SQL prompt, it will produce the following result
Procedure created.
Syntax:
Execute <procedure_name:>
Execute greetings.
This program finds the minimum of two values, here procedure takes two numbers
using IN mode and returns their minimum using OUT parameters
DECLARE
a number;
b number;
c number;
BEGIN
IF x < y THEN
z:= x;
ELSE
z:= y;
END IF;
END;
BEGIN
a:= 23;
findMin(a, b, c);
END;
o/p:
Syntax:
BEGIN
END;
Example-3
DECLARE
a number;
BEGIN
x := x * x;
END;
BEGIN
a:= 23;
squareNum(a);
END;
When the above code is executed at SQL prompt, it produces the following result:
Functions:
RETURN return_datatype
{IS | AS}
BEGIN
END [function_name];
Where,
The optional parameter list contains name, mode and types of the parameters.
IN represents that value will be passed from outside and OUT represents that this
parameter will be used to return a value outside of the procedure.
RETURN clause specifies that data type you are going to return from the function.
The AS keyword is used instead of the IS keyword for creating a standalone function.
Example-1
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
RETURN number IS
total number(2) := 0;
BEGIN
FROM customers;
RETURN total;
END;
When above code is executed using SQL prompt, it will produce the following result:
Function created.
Calling a Function:
A called function performs defined task and when its return statement is executed or
when it last end statement is reached, it returns program control back to the main program.
To call a function you simply need to pass the required parameters along with function
name and if function returns a value then you can store returned value. Following program
calls the function totalCustomers from an anonymous block:
DECLARE
c number(2);
BEGIN
c := totalCustomers();
END;
When the above code is executed at SQL prompt, it produces the following result:
n! = n*(n-1)!
= n*(n-1)*(n-2)!
...
= n*(n-1)*(n-2)*(n-3)... 1
The following program calculates the factorial of a given number by calling itself
recursively:
DECLARE
num number;
factorial number;
RETURN number
IS
f number;
BEGIN
IF x=0 THEN
f := 1;
ELSE
f := x * fact(x-1);
END IF;
RETURN f;
END;
BEGIN
factorial := fact(num);
END;
When the above code is executed at SQL prompt, it produces the following result:
Factorial 6 is 720
Cursor:
Oracle creates a memory area, known as context area, for processing an SQL
statement, which contains all information needed for processing the statement, for example,
number of rows processed, etc.
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.
You can name a cursor so that it could be referred to in a program to fetch and process
the rows returned by the SQL statement, one at a time.
1. Implicit cursors
Implicit Cursors:
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which
always has the attributes like %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT.
Attribute Description
%NOTFOUND
Example:
We will be using the CUSTOMERS table we had created and used in the previous
chapters.
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
The following program would update the table and increase salary of each customer by
500 and use the SQL%ROWCOUNT attribute to determine the number of rows affected:
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
IF sql%notfound THEN
total_rows := sql%rowcount;
END IF;
END;
When the above code is executed at SQL prompt, it produces the following result:
6 customers selected
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
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.
Declaring the cursor defines the cursor with a name and the associated SELECT
statement.
For example:
CURSOR c_customers IS
Opening the cursor allocates memory for the cursor and makes it ready for fetching
the rows returned by the SQL statement into it. For example, we will open above-defined
cursor as follows:
OPEN c_customers;
Fetching the cursor involves accessing one row at a time. For example we will fetch
rows from the above-opened cursor as follows:
Closing the cursor means releasing the allocated memory. For example, we will close
above- opened cursor as follows:
CLOSE c_customers;
Example:
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
BEGIN
OPEN c_customers;
LOOP
CLOSE c_customers;
END;
When the above code is executed at SQL prompt, it produces the following result:
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP
Triggers:
Triggers are stored programs, which are automatically executed or fired when some
events occur. Triggers are, in fact, written to be executed in response to any of the following
events:
140 M N Ravindra Department of Computer Science
A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
Triggers could be defined on the table, view, schema, or database with which the event
is associated.
Benefits of Triggers
Auditing
Creating Triggers
[OF col_name]
ON table_name
WHEN (condition)
DECLARE
Declaration-statements
141 M N Ravindra Department of Computer Science
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
Where,
{BEFORE | AFTER | INSTEAD OF}: This specifies when the trigger would be executed.
The INSTEAD OF clause is used for creating trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
[OF col_name]: This specifies the column name that would be updated.
[ON table_name]: This specifies the name of the table associated with the trigger.
[REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old values for
various DML statements, like INSERT, UPDATE, and DELETE.
[FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be executed
foreach row being affected. Otherwise the trigger will execute just once when the SQL
statement is executed, which is called a table level trigger.
WHEN (condition): This provides a condition for rows for which the trigger would fire.
This clause is valid only for row level triggers.
Example:
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
+----+----------+-----+-----------+----------+
The following program creates a row level trigger for the customers table that would
fire for INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table.
This trigger will display the salary difference between the old values and new values:
DECLARE
sal_diff number;
BEGIN
END;
When the above code is executed at SQL prompt, it produces the following result:
Trigger created.
OLD and NEW references are not available for table level triggers, rather you can use
them for record level triggers.
If you want to query the table in the same trigger, then you should use the AFTER
keyword, because triggers can query the table or change it again only after the initial changes
are applied and the table is back in a consistent state.
Above trigger has been written in such a way that it will fire before any DELETE or
INSERT or UPDATE operation on the table, but you can write your trigger on a single or
multiple operations, for example BEFORE DELETE, which will fire whenever a record will be
deleted using DELETE operation on the table.
Triggering a Trigger:
Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT
statement, which will create a new record in the table:
trigger display_salary_changes will be fired and it will display the following result:
144 M N Ravindra Department of Computer Science
Old salary:
Salary difference:
Because this is a new record so old salary is not available and above result is coming as
null.
Now, let us perform one more DML operation on the CUSTOMERS table. Here is one
UPDATE statement, which will update an existing record in the table:
UPDATE customers
WHERE id = 2;
Chapter-10
Transaction:
A Transaction is a series of actions to be performed on the database such that either all
actions are performed or none.
In database terms a transaction is any action that read from and/or writes to a
database. A transaction may consists of a single SQL statement or a series of related update
statements or insert statements or combination of select, update and insert statements.
1. A Transaction is logical units of work that must entirely complete or entirely aborted
no intermediate states are accepted. All of the SQL statements in a transaction must be
completed successfully. If any of the SQL statements fail the entire transaction is roll
back.
2. A successful transaction changes the database one consistent state to another. A
consistent database state is one in which all data integrity constraints are satisfied.
Transaction Properties
Atomicity.
Consistency.
Isolation.
Durability.
Atomicity: All Operations of the transaction must be completed. If not the transaction is
aborted.
Example: If a transaction T1 has four SQL requests, all four requests must be successfully
completed otherwise the entire transaction is aborted.
Consistency: When a transaction is completed the database must be consistent state. That
means it must satisfies all integrity constraints otherwise the entire transaction is
aborted.
Isolation: The data used during the execution of the transaction cannot be used by a
second transaction until the first transaction is completed.
Durability: Once the transaction changes are done they cannot be undone even in the
system failure.
1. A COMMIT statement is reached in which case all changes are permanently recorded
into the database.
2. A ROLLBACK statement is reached in which case all changes are aborted and the
database is ROLLBACK to previous state.
3. The END of the transaction is successfully reached. In which case all changes are
regarded within the database. This action is equivalent to COMMIT.
4. The transaction is abnormally terminated. In which case the changes made in the
database are aborted and the database is ROLLLBACK to previous state. This action
equivalent to ROLLBACK.
Where prod_code=’p10001’;
Where cust_no=’c1234’;
TRL_i TRX PREV NEXT OPERATIO TABLE ROW ATTRIBUT BEFOR AFTE
d - -PTR -PTR N -ID E E R
NU VALUE VALU
M E
363 101 352 365 Update Custmer 363 Cust_Balan 525.1 615.75
ce 5
If the system failures occur the DBMS will examine the transaction log for incomplete
transaction and ROLLBACK the database to its previous state.
1. Lost updates.
2. Uncommitted data
3. Data inconsistency.
Lost Updates:
The Lost update problem occurs when two concurrent transitions T 1 and T2 are
updating the same data element and one of the update is lost.
Eg: The two concurrent transactions T1 and T2 update the prod_qua value for same item in the
prod table. Assume that current prod_qua value is 35.
151 M N Ravindra Department of Computer Science
Transaction Computation
The following table shows the serial execution of those transaction under the normal
circumstance gives the answer.
1 T1 READ PROD_QOH 35
2 T1 PROD_QOH=35+10
0
5 T2 PROD_QOH=135-30
Suppose that transaction is read a prod_qua value from a table before a previous transaction
has been committed. This sequence shows the following table, how the lost update problem
can occur.
1 T1 READ PROD_QOH 35
152 M N Ravindra Department of Computer Science
2 T2 READ PROD_QOH 35
3 T1 PROD_QOH=35+10
0
4 T2 PROD_QOH=35-30
6 T2 WRITE PROD_QOH 5
Uncommitted Data
The uncommitted data problem occur when two transactions T1 and T2 are executed
concurrently and the first transaction T1 is Rolled back after the second transaction T2 has
already accessed the uncommitted data.
Eg: The two concurrent transactions T1 & T2 update the prod_qua value for some item in the
prod table assumes that the current prod_qua value is 35.
Transaction Computation
The following table shows under normal circumstance, the serial execution of this transaction
use that transaction.
2 T1 PROD_QOH=35+100
4 T1 ROLLBACK 35
5 T2 READ PROD_QOH 35
6 T2 PROD_QOH=135-30
7 T2 WRITE PROD_QOH 5
The following table shows, how the uncommitted data problem can arise when the Roll back
is completed after T2 has begin its execution.
1 T1 READ PROD_QOH 35
2 T1 PROD_QOH=35+10
0
(Read uncommitted
data)
5 T2 PROD_QOH=135-30
6 T1 ROLLBACK 35
Inconsistency Retrievals
Inconsistency retrieval occur when a transaction access data before and after another
transaction finish working with same data.
154 M N Ravindra Department of Computer Science
For example the transaction T1 calculates the total prod_qua of the products stored in
the product table. At the same time T 2 updates prod_qua for two products in the product
table.
TRANSACTION 1 TRANSACTION 2
Prod_code=1003;
Prod_code=1004;
Commit;
PROD_QOH PROD_QOH
1001 8 8
1002 32 32
1003 15 15+10=25
1004 23 23-10=13
1005 8 8
1006 6 6
Total=92 Total=92
While summing the prod_qua of the transaction T1 reads the after prod_qua25 for
prod_code=1003 and reads the before prod_qua=23 for prod_code=1004. Gives the result
102.
11 T2 COMMIT
The Scheduler:
The scheduler is a special DBMS process. The scheduler uses the concurrency control
algorithms such as locking or time stamp methods to control the concurrent executions of
transactions on the same database.
A transaction acquires a lock before to data access the lock is released when the
transaction is completed. So that another transaction can lock the data item for its exclusive
use all lock information is managed by a lock manager.
Lock Granularity
Lock granularity indicates the level of use locking can takes place at the following
levels:
Database level:
In Database level lock the entry database is lock preventing the use of any tables in the
database by transaction T2 while transacting T1 is being executed.
1. This type of locking is unsuitable for multi user DBMS because transactions to be
completed.
2. In database level lock transactions cannot access the same database concurrently even
when they use different tables.
1. In table level lock, the entire table is locked preventing access to any row by
transaction T2 while transaction T1 is using a table.
2. If a transaction requires several tables, each table may be locked.
3. Table level locks also cause traffic jam when many transactions are waiting to access
the same table.
The following shows transactions T1 and T2 cannot access the same table even when they
trying to use different rows, T2 must wait until T1 unlocks the table.
1. A table can span several pages and a page can contains several rows. A page level locks
are most frequently used multi user DBMS locking method.
The following shows transactions access the same table while locking different pages. If T 2
requires the use of a row located on a page that is locked by T 1, T2 must wait until the page is
unlocked by T1.
Row level
159 M N Ravindra Department of Computer Science
The DBMS allows concurrent transactions to access different rows of a same table even
when the row are rotated on the same page. Although the row level locking approach the
improves the availability of the rows but its management requires high overhead.
Field Level
The field level lock allows concurrent transactions to access the same but different
fields. The field level locking gives most flexible multiuser data access but it requires an
extremely high level overheads.
Lock Types:
1. Binary lock
2. Shared/ Exclusive lock.
Binary Lock: A binary lock has two states locked (1), unlocked (0). Every transaction
requires a lock and unlock operations for each data item that is accessed such operations
automatically managed by DBMS.
1 T1 LOCK PRODUCT
2 T1 READ PROD_QOH 35
3 T1 PROD_QOH=35+100
5 T1 UNLOCK PRODUCT
6 T2 LOCK PRODUCT
8 T2 PROD_QOH=135-30
10 T2 UNLOCK PRODUCT
1. A shared lock exists when concurrent transactions are granted read access on the
database of a common locking.
2. An exclusive lock is issued when a transaction wants to update a data item and no lock
are held on that data item by any other transaction.
The following table shows conflict when at least one of a transaction is a write operation.
TRANSACTION RESULT
For example if transaction T1 has a shared lock on a data item x and transaction T 2
wants to read data item x, T2 may also obtain a shared lock on data item x.
For example if a shared or exclusive lock is already held on data item x by transaction
T1 exclusive lock cannot be granted to transaction T2 and T2 must wait until T1 completes. This
condition is known as mutual exclusive rule.
i. Growing Phase
ii. Shrinking Phase.
Growing Phase:
In growing phase the transaction acquires all required locks on data item. Once all
locks have been acquired the transaction is in locked point and performs the operation.
Shrinking Phase:
When the transaction completed the operations then starts the shrinking phase. In shrinking
phase the transaction releases all locks and cannot obtain any new locks.
Dead Lock
A dead lock occurs when two users have a lock each on separate resources. They want
to acquire a lock on each other resources.
In this situation, the first user has to wait until the second user releases the lock and
alternatively the second user also waits till the first user releases the lock. At this stage both
the users are in a waiting state. They cannot proceed with their work.
A transaction requesting a new lock is aborted when there is possibility that a dead
lock can occurs. If a transaction is aborted, all changes made by the transaction are rolled
back and all locks obtained by the transaction are released.
The DBMS periodically test the database for dead locks. If a dead lock is found one of
the transactions is rolled back and other transaction continues.
The transaction must obtain all the locks it needs before it can be executed. The choice
of the best deadlock control method to use depends on the database environment.
For example, if the Probability of deadlocks is low, deadlock detection is recommended.
However, if the probability of deadlocks is high, deadlock prevention is recommended.
Assume that we have two conflicting transactions T 1 and T2. T1 has a time stamp 1154
and T2 has a time stamp 1956. T1 is older transaction and T2 is younger transaction.
1. If a transaction requesting a lock is the older of two transactions, the older transaction
will wait until the younger transaction is completed.
2. If a transaction requesting a lock is the younger of two transactions, the younger
transaction will die (rollback) and younger transaction is rescheduled using the same
time stamp.
Unintentional
Intentional
An Unintentional Failure: Under this category, the humans are deleting the wrong rows
from a table pressing the keys or shutdown the server by accidentally.
An Intentional Failure: Under this category, the unauthorized users accessing the database
to perform operations on the database and virus attackers on the database to damage the
data on the computers.
Natural Incidents
Under this category earthquakes and floods, because of that the database may be lost.
The critical events can render the database in an consistent state. The various
techniques are used to recovery the database from an inconsistent state to consistent state.
Transaction Recovery
The following are the four important concepts that affect the recovery process.
The transaction logs are always written before any database data are updated.
3. Database Buffer
Database buffers are temporary storage areas in primary memory used to speed
up disk operations.
Differed Write
In this technique the transaction operations do not immediately update the database,
only the transaction log is updated. The database is updated only after the transaction
reaches commit, using information from the transaction log if the transaction aborts
before it reaches commit, no changes made in the database by the transaction because the
database was never updated. The recovery process for all started and committed
transaction follows these steps.
1. For a transaction that started and was committed before the last check point. Nothing
needs to be done because the data already saved.
2. For a transaction that performed a commit operation after the last check point, the
DBMS uses the transaction log records to redo the transaction and to update the
database, using the after values in the transaction log.
3. For a transaction that has a roll back operation after the last check point, nothing
needs to be done because the database was never updated.
1. For a transaction that started and was committed before the last check point. Nothing
needs to be done because the data are already saved.
2. For a transaction that was committed after the last check point, the DBMS uses the
transaction log records to redo the transaction, using the after values in the
transaction log.
3. For any transaction that had a any roll back operation after the log check point the
DBMS uses the transaction log to undo the operations using the before values in the
transaction log.
Chapter - 11
The use of a centralized database required that corporate data be stored in a single
central site, usually a mainframe computer. Data access was provided through dumb
terminals.
ADVANTAGES DISADVANTAGES
• Faster data access. End users often work with only a locally stored subset of the company’s
data.
• Faster data processing. A distributed database system spreads out the systems workload
by processing data at several sites.
• Growth facilitation. New sites can be added to the network without affecting the
operations of other sites.
168 M N Ravindra Department of Computer Science
• Improved communications. Because local sites are smaller and located closer to customers,
local sites foster better communication among departments and between customers and
company staff.
• User-friendly interface. PCs and workstations are usually equipped with an easy-to-use
graphical user interface (GUI). The GUI simplifies training and use for end users.
• Less danger of a single-point failure. When one of the computers fails, the workload is
picked up by other workstations. Data are also distributed at multiple sites.
• Processor independence. The end user is able to access any available copy of the data, and
an end user's request is processed by any processor at the data location.
Disadvantages:
• Complexity of management and control. Applications must recognize data location, and
they must be able to stitch together data from various sites. Database administrators must
have the ability to coordinate database activities to prevent database degradation due to data
anomalies.
• Security. The probability of security lapses increases when data are located at multiple
sites. The responsibility of data management will be shared by different people at several
sites.
• Lack of standards. There are no standard communication protocols at the database level.
(Although TCP/IP is the de facto standard at the network level, there is no standard at the
application level.) For example, different database vendors employ different—and often
incompatible—techniques to manage the distribution of data and processing in a DDBMS
environment.
• Increased storage and infrastructure requirements. Multiple copies of data are required
at different sites, thus requiring additional disk storage space.
• Increased training cost. Training costs are generally higher in a distributed model than
they would be in a centralized model, sometimes even to the extent of offsetting operational
and hardware savings.
Distributed processing:
Although the database resides at only one site (Miami), each site can access the data
and update the database. The database is located on Computer A, a network computer known
as the database server.
Distributed Database:
A Distributed database stores a logically related data base in two or more sites. The
sites are connected via a communication network.
3. Both distributed processing and distributed databases require a network to connect all
components.
1. Application interface: To interact with the end user, application programs, and other
DBMSs within the distributed database.
7. Backup and recovery: To ensure the availability and recoverability of the database in
case of a failure.
9. Transaction management: To ensure that the data moves from one consistent state
to another. This activity includes the synchronization (bringing together) of local and
remote transactions as well as transactions across multiple distributed segments.
DDBMS COMPONENTS:
Computer workstations: It form the network system. The distributed database system must
be independent of the computer system hardware.
Network hardware and software: the network hardware and software components that
resides in each workstation. The network components allow all sites to interact and
exchange data.
Communications media: The communication media that carry the data from one node to
another.
The transaction processor (TP), which is the software component found in each
computer or device that requests data. The transaction processor receives and processes the
application’s data requests (remote and local). The TP is also known as the application
processor (AP) or the transaction manager (TM).
The data processor (DP), which is the software component residing on each
computer or device that stores and retrieves data located at the site. The DP is also known as
the data manager (DM).
The transaction processor and Data processor are embedded with in the DBMS located on a
single computer.
Under the multiple-site processing, single-site data (MPSD) scenario, multiple processes
run on different computers sharing a single data repository. The MPSD scenario requires a
network file server.
The TP on each workstation acts only as a redirector to route all network data requests to the
file server.
All data selection, search, and update functions take place at the workstation, thus requiring
that entire files travel through the network for processing at the workstation. Such a
requirement increases network traffic, slows response time, and increases communication
costs.
a. About the data are partitioned (meaning the table’s rows and columns are split
vertically or horizontally and stored among multiple sites.)
Transaction transparency, which allows a transaction to update data at more than one
network site. Transaction transparency ensures that the transaction will be either entirely
completed or aborted, thus maintaining database integrity.
Failure transparency, which ensures that the system will continue to operate in the event of
a node failure.
Performance transparency: The system will not suffer any performance degradation due
to its use on a network or due to the network’s platform differences.
DISTRIBUTION TRANSPARENCY:
Location transparency: This is the middle level of transparency. The end user must specify
fragement name and does not need to specify the location name.
Local mapping transparency: This is the lowest level of transparency. The end user or
programmer must specify both the fragment names and their locations name.
For example the employee data are distributed over three different locations – Delhi,
Hyderabad, Banglore.
The Delhi employees data are stored in fragment E1, Hyderabad employees data are stored in
fragment E2, Banglore employees data are stored in fragment E3 is shown below.
Suppose the end user wants to list all the employees with a date of birth before Jan 1,1980.
The end user written this query in the fragmentation transparency as shown below.
The end user written this Query in the location Transparency as shown below.
Union
Union
The end user written this Query in the local Transparency as shown below.
Union
Union
TRANSACTION TRANSPARENCY
To understand how the transactions are managed in the DDBMS, we should know the basic
concepts of remote request, remote transaction, Distributed request and Distributed
transaction.
The single SQL statement access the data that are to be processed by a single Remote
Database processor.
Remote Transaction:
COMMIT WORK;
1. The transaction updates the product and invoice table (located at site B).
Distributed Transaction:
UPDATE PRODUCT
COMMIT WORK;
2. The first two requests (UPDATE PRODUCT and INSERT INTO INVOICE) are processed
by the DP at the remote site C, and the last request (UPDATE CUSTOMER) is processed
by the DP at the remote site B.
The third characteristic may create problems. For example, suppose the table PRODUCT is
divided into two fragments, PRODl and PROD2, located at sites B and C, respectively, the
distributed transaction cannot access the data from more than one site. Therefore the DDBMS
must be support a distributed request.
The Distributed request allows a single request to reference a partitioned table in several
sites.
For ex. Customer table is divided into two fragments E1 and E2 located at site B and Site C are
shown below.
Suppose that each transaction operation was committed by each local DP, but one of the DPs
could not commit the transaction. Then the transaction is ‘Aborted’. Otherwise the
transaction(s) would yield an inconsistent database.
In distributed database a transaction access data at several sites. A final commit must not be
issued until all sites have committed their parts of the transaction.
The two phase commit protocol guaranties that if a portion of a transaction operations
cannot be committed all changes made at the others sites by the transaction will be aborted.
Each DP maintains its own transaction log. The transaction log for each DP written before the
database fragment is updated.
The two phase commit protocols requires a DO-UNDO-REDO protocol and a write a head
protocol. The DO-UNDO-REDO protocols defines three types of Operations.
a) Performs the operations and before and after values in the transaction log.
c) REDO reduces the operation using the Transaction Log written by the DO portion of
sequences.
The Two-Phase commit protocol defines the operations between two types of nodes: the
coordinator and one or more subordinates, or cohorts. The participating nodes agree on a
coordinator.
Phase 1: Preparation
1. The sub coordinator receive the message; write the transaction log, using the write-ahead
protocol; and send an acknowledgment (YES/PREPARED TO COMMIT or NO/NOT
PREPARED) message to the coordinator.
1. The coordinator broadcasts a COMMIT message to all subordinates and waits for the
replies.
2. Each subordinate receives the COMMIT message, and then updates the database using the
DO protocol.
If one or more subordinates did not commit, the coordinator sends an ABORT message,
thereby forcing them to UNDO all changes.
Note: The objective of the two-phase commit is to ensure that each node commits its part of
the transaction; otherwise, the transaction is aborted.
In centralized database all data resides at a single site. The DBMS evaluate data request and
find the most efficient way to access the data.
In DDBMS the database is divided into several fragments. In DDBMS Query evoluation is more
complicated, because the DDBMS must decide which fragment of data is access. In addition
the data may also repeated several times.
The DDBMS uses query optimization technique to deal with such problems.
The objective of the query optimization is to minimize the total execution cost of the request.
Access time (I/O) cost: It involved in accessing the physical data stored on disk.
Communication cost: It associated with the transmission of data among nodes in distributed
database systems.
CPU time cost: It associated with the processing overhead of managing distributed
transactions.
Replica transparency refers to the DDBMS’s ability to hide the existence of multiple copies
of data from the user.
182 M N Ravindra Department of Computer Science
Query optimizations are based on two principles:
Query optimization algorithm can be evaluated the request on the basis of its operation mode
or the timing of its optimization.
Static query optimization: When the program is submitted to the DBMS for compilation, it
creates the necessary plan to access the database. When the program is executed, the DBMS
uses that plan to access the database.
Dynamic query optimization. Database access plan defined when the program is executed.
Finally, query optimization techniques can be classified according to the type of information
that is used to optimize the query.
A statistically based query optimization algorithm uses statistical information about the
database.
The statistics provide information about database characteristics such as size, number of
records, average access time, number of requests serviced, and number of users with access
rights.
The statistical information is managed by the DDBMS and is generated in one of two different
modes: dynamic or manual.
In the dynamic statistical generation mode, the DDBMS automatically evaluates and
updates the statistics after each access.
In the manual statistical generation mode, the statistics must be updated periodically.
Data fragmentation allows you to break a single object into two or more segments, or
fragments. The object might be a user’s database, a system database, or a table. Each fragment
can be stored at any site over a computer network.
Horizontal fragmentation partitions the rows of a global fragment into subsets. A fragment
r1 is a selection on the global fragment r using a predicate Pi, its qualification. The
reconstruction of r is obtained by taking the union of all fragments.
Vertical fragmentation subdivides the attributes of the global fragment into groups. The
simplest form of vertical fragmentation is decomposition. A unique row-id may be included in
each fragment to guarantee that the reconstruction through a join operation is possible.
1. Fragments are formed by the select predicates associated with dominant database
transactions. The predicates specify attribute values used in the conjunctive (AND) and
disjunctive (OR) form of select commands, and rows (records) containing the same values
form fragments.
2. Fragments must be disjoint and their union must become the whole fragment. Overlapping
fragments are too difficult to analyze and implement.
3. The largest fragment is the whole table. The smallest table is a single record. Fragments
should be designed to maintain a balance between these extremes.
Rule-1.
Local Autonomy. Local data is locally owned and managed, even when it is accessible by a
remote site. Security, integrity, and storage remain under control of the local system. Local
users should not be hampered when their system is part of a distributed system.
Rule-2.
No Central Site. There must be no central point of failure or bottleneck. Therefore the
following must be distributed: dictionary management, query processing, concurrency
control, and recovery control.
Rule-3.
Rule-4.
Location Independence (or Transparency). A common global user view of the database
should be supported so that users need not know where the data is located. This allows data
to be moved for performance considerations or in response to storage constraints without
affecting the user applications.
Rule-5.
Rule-6.
Replication Independence (or Transparency). This allows several copies of a table (or
portions thereof) to reside at different nodes. Query performance can be improved since
applications can work with a local copy instead of a remote one. Update performance,
however, may be degraded due to the additional copies. Availability can improve.
Rule-7.
Distributed Query Processing. No central site should perform optimization; but the
submitting site, which receives the query from the user, should decide the overall strategy.
Other participants perform optimization at their own levels.
Rule-8.
Rule-9.
Rule-10.
Rule-11.
Rule-12.