Database System and Architecture
Database System and Architecture
1.1 Introduction:
Database: A database is a collection of related data. Data is a collection of raw facts that can be
recorded. Database has the following properties
1. It represents some aspects of real world.
2. It is a logically coherent collection of data with some inherent meaning
3. It is designed, built and populated with data for a specific purpose
4. It has an intended group of users and some preconceived applications in which these
users are interested
E.g. An address book containing names, addresses and phone numbers of people in a software
like MS-Excel or MS-Access
1.2 Example:
Consider a COLLEGE database maintaining information concerning students, courses and their
grades in a particular college. The database is organized into three files namely STUDENT,
COURSE and GRADE REPORT. To define the database, we must specify the structure of the
records of each file by specifying the different data types of data elements to be stored in each
record. Each student record includes the following – Roll no, name, class and department.
Similarly, records in course file includes – course name, course number and department. Grade
file includes roll no, class and grade. The information stored in each file is called as record. The
record in Student could be {1, AMAR, IBCA, Computers}. A record in course file could be
{BCA, BC001, Computers}. A record in grade file would be {1, IBCA, ‘A’}
User Programs
Application Programs/Queries
Software to process
Programs/Queries
2
Simplified Database system Environment
1.3 Characteristics of Database Approach:
In file processing, each user defines and implements the files needed for a specific software
application as a part of programming the application.
E.g. Consider a student file. A person trying to grade the students uses the student file and
calculates grade. A clerk who wants to print students’ attendance will create another file with the
same data.
Hence, when files are used there is redundancy in storing the same data and redundant
effort to maintain the common data. In database approach, a single repository of data is
maintained that is defined and then accessed by various users.
The characteristics of database approach vs. file processing are as follows
1. Self describing nature of database system
2. Insulation between data and programs and data abstraction
3. Support of multiple views of data
4. Sharing of data and multi-user transaction processing
derived from database files. A multi-user DBMS whose users have a variety of distinct
applications must provide facility for defining multiple views.
DBA: DBA stands for Data Base Administrator. In a database environment, the primary
resource is the database itself and the secondary resource is the database itself. Administering
these resources is the responsibility of the DBA. The DBA is responsible for authorizing access
to the database, coordinating and monitoring its use and acquiring the software and hardware
resources as needed. DBA is also accountable for system security.
DB Designers: These are people who are responsible for identifying data to be stored in the
database and for choosing appropriate structures to represent and store data
End Users: End users are people whose jobs require access to the database for querying,
updating and generating reports. These people make use of the existing database.
2. Restricting unauthorized access: When multiple users share a large database, it is likely
that all users will not want all the information in the database. Moreover, all the users will
not be authorized to use all the data. Some users may be only allowed to retrieve while
others may be allowed to retrieve a well as to update data. In order to provide
authorization, users are given user names and passwords. A DBMS provides security and
authorization subsystem, which the DBA uses to create accounts and passwords to
different users
3. Providing Storage structures for efficient query processing: Database systems must
provide capabilities for efficiently executing a query. DBMS must provide specialized
data structures to speed up disk access. The query processing and optimization module of
the DBMS is responsible for choosing efficient query execution plan for each query
based on the existing storage structures
4. Providing Backup and recovery: DBMS must provide facilities for recovering from
hardware or software failures. The backup and recovery systems are responsible for
recovery of data in such situations
5. Providing multiple user interfaces: DBMS has a wide variety of users. Hence, it should
provide multiple user interfaces for each class of user. For example: Query language for
casual users, programming language interface for application programmers.
7. Enforcing integrity constraints: DBMS should provide capability for defining and
enforcing integrity constraints. For example specifying data types for each data item is
done to ensure that erroneous data is not entered into the data base
8. Permitting inferencing and actions using rules: Some database provide capabilities for
defining deduction rules for inferencing new information from the stored database facts.
Such systems are called deductive database systems. Some database provide active rules
that can automatically initiate actions when certain events and conditions occur.
Assignment
Short Answers (2 marks)
1.Define database
2.Define DBMS
3. What is the role of DBA?
4. List the different users of databases
5.Who are end users in database
approach?
Hierarchical Data Model: Here different records are interrelated through a hierarchical or a
tree-like structure. A parent record can have several children but a child can have only one
parent.
Network Data Model: Here, a parent record can have several children and a child record can
also have many parent records.
DBMS and Oracle 8
Srinivas Institute of Management Studies II Semester BCA
Relational Data Model: In this model, there are no physical links between records. All the data
is maintained in the form of tables, comprising of rows and columns. Data in two tables is
related through common columns. Querying is much easier in this model. It is very much
programmer friendly and is the most widely used model.
STUDENT
Roll No Student Name Class Department
COURSE
Course Name Course Number Department
GRADE REPORT
Roll N Class Grade
o
Meta data: The description of the schema constructs and constraints is called meta data. The
meta data is stored in the DBMS catalog so that DBMS software can refer to it whenever
necessary.
The internal level has an internal schema, which describes the physical storage structure of the
database. The internal schema uses physical data model and describes the complete details of
data storage and access paths for the database.
The conceptual level has a conceptual schema which describes the structure of the whole
database for a community of users. It hides details of physical storage and concentrates on
describing entities, data types, relationships, operations and constraints. The representational
model is used to describe the conceptual schema.
The external or view level includes a number of external schemas or user views. Each external
schema describes a part of the database that a particular user group is interested and hides the
rest of the database from that user group.
The process of transforming requests and results between levels is called mappings.
Physical Data Independence: It is the capacity to change the internal schema without having to
change conceptual schemas. Changes to the internal schema may be needed because physical
files had to be reorganized.
The three schema architecture makes it easier to achieve true data independence i.e. both
physical and logical data independence.
b. Form based Interfaces: It displays a form to each user. Users can fill data in the form to
insert new data. The user can also fill specific entries in which case the DBMS retrieves
data from the database
c. Graphical user interfaces: A GUI displays a schema in a diagrammatic form to the user.
The user specifies a query by manipulating the diagram. A pointing device such as mouse
is used.
d. Natural Language Interfaces: These interfaces accept request written in English and
attempts to understand them. It has its own schema and dictionary of important words. If
the interpretation is successful, the interface generates a high level query corresponding
to the natural language request and submits it to the DBMS. Otherwise a dialog is started
with the user for clarification of request.
e. Interface for parametric users: Parametric users such as bank tellers perform small set of
operations on the database repeatedly. A small set of abbreviated commands are included
to minimize the number of keystrokes for each request.
f. Interface for DBA: Privileged commands can be used only by the DBA. These include
commands for creating user accounts, granting account authorization and reorganizing
storage structure of data.
2.8.2 Number of users: Depending on the number of users supported by the system, DBMS can
be categorized into
a. Single user systems- that support only one user at a time
b. Multi-user system – that support multiple users concurrently
2.8.3 Number of sites: Based on the number of sites over which the database is distributed ,
DBMS can be classified as
a. Centralized DBMS- Here the data is stored at a single computer site. It supports multiple
users but the DBMS and database reside at a single computer site.
b. Distributed DBMS- The database and DBMS are distributed over many sites connected
through network. This can again be divided as
i. Homogeneous DDBMS: They use same DBMS software at multiple sites ii.
Heterogeneous DDBMS: They use different DBMS software at different sites
2.8.4 Types of application: Based on the types of application DBMS can be classified as
follows
a. General Purpose DBMS: DBMS that can be used for all types of application
b. Special Purpose DBMS: DBMS used for a specific application for which they are
designed. E.g. airline reservation – it cannot be used for other applications.
Assignment
Short Answers (2 marks)
1. Define schema
2. What is a schema diagram? Give example
3. Define snapshot.
4. Define mapping
5. What is logical data independence?
6. What is physical data independence?
• The next step is the actual implementation of the database using some data model. This
step is the logical design or data model mapping and results in a database schema
• The last step is the physical design during which the internal storage structures and
organization of the database files are specified
its attributes. The attribute values that describe the entity become major part of the data stored in
database.
E.g. Employee is an entity. It can have the following attributes
Employee name, DOB, DOJ, designation
“John”, 19-05-1981, 21-6-2007, “Officer” is a set of values assigned to the attributes.
Examples
1. Composite Attributes: The attribute “customer address” can have the attributes number,
street, city, and state. These are called composite attributes.
Customer
Teacher Subjects
3. Derived Attributes:
Name
An entity type has an attribute whose values are distinct for each individual entity in the
entity set. Such an attribute is called a key attribute and its value can be used to identify each
entity uniquely. An entity with no key attribute is called a weak entity.
Domains of attributes: Each simple attribute is associated with a value set or domain of values.
It specifies the set of values that may be assigned to that attribute for each individual entity.
E.g. The value set for attribute age of employee to be the set of integers between 16 and 70.
Supervision
Employee
• One-to-Many
Only one entity of the first set is related to multiple entities of the second set. E.g. A
teacher teaches students. Only one teacher is teaching many students. This can be
expressed in the following diagram as:
• Many-to-One
Multiple entities of the first set are related to multiple entities of the second set. E.g.
Teachers teach a student. Many teachers are teaching only one student. This can be
expressed in the following diagram as:
• Many-to-Many
DBMS and Oracle 20
Srinivas Institute of Management Studies II Semester BCA
Multiple entities of the first set is related to multiple entities of the second set. E.g.
Teachers teach students. In any school or college many teachers are teaching many
students. This can be considered as a two way one-to-many relationship. This can be
expressed in the following diagram as:
Participation Constraints:
The participation constraint specifies whether the existence of an entity depends on its being
related to another entity via a relation type. It specifies the minimum number of relation instance
that each entity can participate in and is also called the minimum cardinality relation. The two
types of participation constraints are total and partial participation.
Example: If a company policy states that every employee must work for a department. An
employee entity can exist only if it participates in at least one ‘works for’ relation instance. The
participation of EMPLOYEE in ‘works for’ is called total participation. i.e. every entity in a set
of employee must be related to department entity via works for. Total participation is also called
existency dependency. Not every employee can manage a department. Hence participation of
employee in ‘manages’ relation is partial i.e. a part of the set of employee entities are related to
some department entity via ‘manages’ relation. Cardinality ratio and participation constraint
together are known as structural constraints.
Example: Consider the entity type Dependant related to Employee, used to keep track of the
dependents of each employee.
Dependent – Name, DOB, Sex, Relation.
Two dependents of 2 distinct employees may by chance be the same value. They can be
identified as distinct only after determining the particular employee entity to which each
dependent is related. In this example, EMP is parent entity type or dominant entity type. Weak
entity is the child/subordinate entity type. A weak entity has a partial key which is a set of
attributes that can uniquely identify weak entities that are related to the same owner entity. In an
ER diagram, weak entity and its attributes are surrounded by double lines. Partial key attributes
is underlined with dashed lines.
Assignment
Short Answers (2 marks)
1. Define entity type
2. Define entity set
3. Define ER model
4. What are weak entity types
5. Give an example for recursive relation 6.What do you mean by cardinality ratio?
7. What do you mean by degree of a relation? Give example
8. Define a recursive relation with an example.
4.1.1 Domain: A domain D is a set of atomic values. Each value in the domain is indivisible. A
common method of specifying a domain is to specify a data type from which the data values
forming the domain are drawn.
Example:
Set of telephone numbers- Numbers
Set of student names- Character strings representing names of students
They are logical definitions of domains. A data type or format is specified for each domain.
4.1.2 Relation Schema: A relation schema R(A1,A2,….,An) is made up of a relation R and a list
of attributes A1,A2,….,An. Each attribute Ai is the name of the role played by some domain D
in the relation schema R. D is called the domain of Ai and is denoted by dom(Ai). A relation
schema is used to describe a relation. The degree of a relation is the number of attributes in the
relation schema. A relation or a relation state r of a relation schema R(A1,A2,….,An), is also
denoted by r(R) is a set of n-tuples r={t1,t2,…,tn}. Each n-tuple is an ordered list of values
t=<v1,v2,….,vn> where each value vi is 1<=i<=n is an element of dom(Ai) or a special null
value.
3. Values and nulls in a tuple: Each value in a tuple is an atomic value. This model is called
a flat relation. Hence composite and multi-valued attribute are not allowed. Multi-valued
attributes must be represented by a separate relation. Null values are used to represent the
values of attributes that may be unknown or may not be applied to a tuple.
Domain Constraint: This constraint specifies that within each tuple the value of each
attribute A must be an atomic value from the domain dom(A). The data types for domain
include standard numeric data types for integer and real values, fixed length and variable
length strings.
Key Constraints: A relation is a set of tuples. By definition all the elements in a set are
distinct. No two tuples can have the same combination of values for all attributes. Let SK be
a sub set of attributes of R with the property that no two tuples have the same combination of
values. Let t1,t2 be two distinct tuples. Then, t1[SK]t2[SK].
Such set of attributes is called a super key of the relation schema R. A super key SK
specifies uniqueness constraint that no two tuples in the state r of R can have the same value
for SK. Every relation has at least one default super key- the set of all its attributes. A super
key can have redundant attributes. A key K of a relation R is a super key of R with an
additional property that removing any attribute A from K leaves a set of attributes K’ that is
not a super key of R. A key satisfies two constraints:
1. Two distinct tuples in any state of a relation cannot have identical values for the
attributes in the key.
2. It is a minimal super key i.e. a super key from which we cannot remove any attributes
and still have the uniqueness constraint in condition 1 to hold.
Candidate Key: A relation schema can have more than one key. Each of the key is called a
candidate key.
Primary key: A candidate key whose values are used to identify tuples in a relation is called
a primary key.
Constraints as null: This is a constraint on attributes that specifies whether null values are
permitted or not. E.g. If every student tuple must have a valid non-null value for name
attribute, then the name attribute is constrained as not null.
Entity Integrity Constraint: It states that no primary key value can be null. This is because
primary keys are used to identify the tuples in a relation.
4.3.1 Insert operation: It provides a list of attribute values for a new tuple that is to be inserted
into R. Insert operation can violate the following constraints:
• Domain constraint can be violated if an attribute value does not match the specified
domain.
• Key constraint can be violated if a key value in the new tuple t already exists in another
tuple in the relation r(R).
• Entity integrity constraint can be violated if the primary key of the new tuple t is null
• Referential integrity constraint can be violated if the value of any foreign key in t refers
to a tuple that does not exist in the referenced relation.
4.3.3 Update Operation: This operation is used to modify / change values of one or more
attributes in tuple(s) in a relation R. It is necessary to specify a condition on attributes of a
relation to select a tuple to be modified. Updating an attribute that is neither a primary key nor a
foreign key creates no problem. Modifying a primary key is similar to deleting a tuple and
inserting another in its place. When updating DBMS checks to confirm the new value is of
correct data type and domain.
Assignment
Short Answers (2 marks)
1. Define primary key
2. Define candidate key
3. Define foreign key
4. Define domain of a relation
5. Define relation schema
6. Define tuple in a relation
7. Define attribute in a relation
The basic set of operations on relational model is the relational algebra. These operations enable
a user to specify basic retrieval requests. The result of retrieval is a new relation that is formed
from one or more relations
5.1.1 SELECT Operation: The select operation is used to select a subset of tuples from a
relation that satisfy a selection condition. It can be considered as a filter that keeps only those
tuples that satisfy a qualifying condition. The select operation can be visualized as a horizontal
partition of the relation into two sets of tuples- those that satisfy the condition are selected and
those that do not satisfy the condition are discarded. Select operation is denoted by
<select condition>(R)
E.g. To select employee tuples whose department is 4, it can be specified as follows:
DNO=4(EMPLOYEE)
The boolean expression specified in the selection condition is made up of a number of clauses of
the form
<attribute name><comparison operator><constant value>
OR
<attribute name><comparison operator><attribute name>
The comparison operators can be any of the elements in the set {, , , , , }
Two or more selection conditions can be combined using boolean operators like AND, OR and
NOT.
Condition 1 AND condition2 is true only if both condition1 and condition2 are true, otherwise it
is false.
Condition 1 OR condition2 is true only if either of the condition is true, otherwise it is false.
NOT condition is true if condition is false and false otherwise
The select operation is commutative
i.e. condition 1 (condition 2 (R))=condition 2condition1 (R))
A sequence of selects can be applied in any order. We can also combine a cascade of select
operations into a single select operation with an AND condition
i.e. condition 1 (condition 2 (…..condition n (R))= condition 1AND condition2 AND condition 3…..condition n(R)
5.1.2 PROJECT Operation: Project operation selects certain columns from the table and
discards other columns. It can be visualized as vertical partitioning of relation into two relations
– one has the required attributes that contains the result of the operation and the other contains
discarded columns. Project operations is denoted by
<attribute list> (R)
Here, <attribute list> is the desired list of attributes that are to be projected from the relation R
For example, if the name and salary of an employee is to be listed, it can be written as follows:
NAME,SAL (EMPLOYEE)
The number of tuples in a relation resulting from project operation is always less than or equal to
the total number of tuples in R.
Union Compatibility:
These are binary operations and are applied on two relations. But, the relations must have same
type of tuples. Two relations R(A1,A2,….,An) and S(B1,B2,…,Bn) are said to be union
compatible if they have the same degree n and if dom(Ai)=dom(Bi) for 1 i n
i.e. Two relations should have the same number of attributes and each corresponding pair of
attributes should have the same domain. This condition is known as union compatibility.
Example: Two union Compatible relations
STUDENT INSTRUCTOR
FNAME LNAME
Suresh Rao
Ramesh Krishna
Ravi Reddy
Vipul Kumar
Vinay Kumar
Sachin Kumar
Rohit Sharma
5.2.2 INTERSECTION – The result of this operation is denoted by RS. It results in a relation
that contains all tuples that are present in both R and S
5.2.3 SET DIFFERENCE – The result of this operation is denoted by R-S. It is a relation that
includes all tuples that are in R but not in S.
Examples:
a) STUDENT-INSTRUCTOR
FNAME LNAME
Suresh Rao
Ramesh Krishna
Vipul Kumar
Vinay Kumar
b) INSTRUCTOR-STUDENT
FNAME LNAME
Rohit Sharma
a) Equi-Join – When join conditions involve only equality comparisons on the attributes of
2 tables ,then, such joins are called equi-joins. The result of equi-join operation has
always one or more pair of attributes that are identical in every tuple.
EMP
EMPNO ENAME DNO
E001 RAMA D001
E002 GITA D002
E003 RITA D001
DEPT
DNUM DNAME
D001 HR
D002 SALES
EMP DEPT
EMPNO ENAME DEPTNO DNAME
E001 RAMA D001 HR
E002 GITA D002 SALES
E003 RITA D001 HR
b) Natural Join- In order to eliminate identical values in every tuple, we use natural joins.
The definition of natural join requires that the two join attributes have the same name in
both the relations. It is denoted by. In case the two attributes do not have the same name,
renaming is done.
EMP
EMPNO ENAME DNAME
E001 RAMA HR
E002 GITA SALES
E003 RITA HR
DEPT
DNAME DLOCATION
HR CHENNAI
SALES KANNUR
EMP⋈ DEPT
EMPNO ENAME DNAME
E001 RAMA HR
E002 GITA SALES
E003 RITA HR
c) Theta Join – When the join conditions involve all comparison operators on the attributes
i.e.{<,>,<=,>=,!=} then, such a join is called theta join.
CAR
CarModel CarPrice
CarA 20,000
CarB 30,000
CarC 50,000
BOAT
BoatModel BoatPrice
Boat1 10,000
Boat2 40,000
Boat3 60,000
CAR⋈CARPRICE>=BOATPRICE BOAT
CarModel CarPrice BoatModel BoatPrice
CarA 20,000 Boat1 10,000
CarB 30,000 Boat1 10,000
CarC 50,000 Boat1 10,000
CarC 50,000 Boat2 40,000
The join operations where only matching tuples are kept in the result are called inner joins. In
inner joins, tuples are without a match and those with null values are eliminated. This amounts to
loss of information if the result of the join is suppose to contain all the information. A set of
operations called outer join can be used when we need all the tuples in R or all those in S or all
those both in R and S, regardless of whether they have matching tuples in the other relations.
This will satisfy the need of the query in which tuples from both the tables are to be combined
by matching corresponding rows but without losing any tuples for lack of matching values. The
different types of outer joins are
a. Left Outer Join
b. Right Outer Join
c. Full Outer Join
Left Outer Join ⟕: This operation keeps all the tuples in the first or left relation (R x S) i..e. R. If
no match is found in S then the join result pads the attribute with null values.
Employee
Name EmpId DeptName
Hari 3415 Finance
Samit 2241 Sales
Geetha 3401 Finance
Haritha 2202 Sales
Tom 1123 Executive
Dept
DeptName Manager
Sales Haritha
Production Charles
Employee ⟕ Dept
Name EmpId DeptName Manager
Hari 3415 Finance NULL
Samit 2241 Sales Haritha
Geetha 3401 Finance NULL
Haritha 2202 Sales Haritha
Tom 1123 Executive NULL
Right Outer Join(⟖): This operation keeps all the tuples in the second or right relation (R x S)
i..e. S. If no match is found in R then the join result pads the attribute with null values. Employee
Name EmpId DeptName
Hari 3415 Finance
Samit 2241 Sales
Geetha 3401 Finance
Haritha 2202 Sales
Tom 1123 Executive
Dept
DeptName Manager
Sales Haritha
Production Charles
Employee ⟖ Dept
Name EmpId DeptName Manager
Samit 2241 Sales Haritha
Haritha 2202 Sales Haritha
NULL NULL Production Charles
Full Outer Join(⟗): This operation keeps all the tuples in both the left and right relations. When
no match is found in either relations, the corresponding attributes are padded with null values as
needed.
Employee
Name EmpId DeptName
Hari 3415 Finance
Samit 2241 Sales
Geetha 3401 Finance
Haritha 2202 Sales
Tom 1123 Executive
Dept
DeptName Manager
Sales Haritha
Production Charles
Employee ⟗ Dept
Name EmpId DeptName Manager
Hari 3415 Finance NULL
Samit 2241 Sales Haritha
Geetha 3401 Finance NULL
Haitha 2202 Sales Haritha
Tom 1123 Executive NULL
NULL NULL Production Charles
5.3.2 Division Operator:
The division operation is denoted by and is useful for special kind of query that sometimes
occur in database operation. The division operator is applied to two relations R(Z)
S(X) where XZ. For a tuple t to appear in the result T of the division, the values in t must
appear in R in combination with every tuple t in S.
Example: T=RS
R S T
so that each group includes tuples for employees working in the same department. Aggregate
functions are defined using the operator and specifies the following request.
<grouping attributes><function list> (R)
1 2
where 1: list of attributes of relation specified and 2: list of (function, attribute) pair in R
is used for rename operation.
Example: To retrieve the department number, number of employees in the department and their
average salary, we can write it as
R(DNO,NO-OF-EMP,AVG-SAL) (DNO COUNTENO,AVERAGE SAL(EMPLOYEE))
Assignment
Short Answers (2 marks)
1. What is the purpose of SELECT operation in relational algebra?
2. What is the purpose of PROJECT operation in relational algebra?
3. List the set theory operations in relational algebra.
4. What is union compatibility?
5. What do you mean by outer union operation?
Here, rollno does not uniquely identify rows in a table, therefore it cannot be a primary key.
Similarly, sub-code does not uniquely identify rows in a table. But, a combination of rollno and
sub_code uniquely identifies a row in the table. Hence (rollno,sub-code) together will be a
primary key in a table
Normal Forms:
The different forms of normalization that can be applied to relations are as follows:
• First Normal Form 1NF
• Second Normal Form 2NF
• Third Normal Form 3NF
• Boyce-Codd Normal Form BCNF
First Normal Form (1NF)
A relation R is said to be in 1NF if every attribute of R takes only single atomic values. In order
to transform un-normalized table to 1NF we identify and remove repeating groups within a table.
Example
DEPT
Deptno Deptname DeptLoc
D001 Accounts Chennai
D002 R&D Delhi,Bangalore
E
2
P-NUMBER PROJ-NAME PLOCATION
E3
ECODE ENAME
Transitive Dependency:
A functional dependency X→Y is a transitive dependency if there is a set of attributes Z in R
such that if X→Y and Y→Z, then, X→Z. Example:
ECODE ENAME DOB DEPTNO DNAME DMNGR
The above table has transitive dependency. Here, ecode→deptno and deptno→dmngr. Hence,
ecode→dmngr.
Example:
EMPDEPT
ECODE ENAME DOB ADDR DEPTNO DNAME DMNGR
3NF
EMP
ECODE ENAME DOB ADDR DEPTNO
DEPT
DEPTNO DNAME DMNGR
Assignment
Short Answers (2 marks)
1. Define normalization
2. Define 1NF
3. Define functional dependency
4. Define transitive dependency
CHAPTER 7 DISK
STORAGE
7.1 Introduction:
The collection of data that makes up a computerized database must be physically stored on a
computer storage medium. The DBMS can then retrieve, update and process data as and when
needed. The two main categories of computer storage media are
a. Primary Storage – This category includes storage media that can be directly accessed by
CPU. It provides fast access to data but is of limited storage. Example: RAM, ROM
b. Secondary Storage – Data stored on these devices cannot be directly accessed by the
CPU. It must be first be copied onto the primary storage. These devices have larger
capacity, cost less and provide slower access to data. Example: Magnetic disks, optical
disks and tapes
are tracks on each disk. These are called fixed head disks. Disk heads with an actuator are called
movable head disks. The time required for the disk controller to mechanically position the
read/write head on the correct track is called seek time. Rotational delay/rotational latency is the
time required for the beginning of the desired block to rotate and position itself on the read/write
head. Block transfer time is the time needed to transfer data to/from the buffer and the disk.
Disks are random access storage devices because an arbitrary disk block may be accessed at
random. Magnetic tapes are sequential access devices. i.e. to access the nth block on tape, we
must first scan the preceding n-1 blocks. A tape drive is used to read data from or to write the
data to a tape reel. A read/write head is used to read/write data onto tape. The main characteristic
of tape is that data blocks can be accessed in sequential order. For this reason the access to data
can be slow and hence are not used for online applications. Tapes are usually used for backing
up the data base.
One reason for backup is to keep the copies of disk files in case the data is lost because of disk
crash. Hence, disk files are periodically copied onto files. Database files that are seldom used or
are outdated, but are required for historical record keeping can be archived on magnetic tapes.
Double Buffering: The CPU can start processing a block once its transfer to the main memory is
completed. At the same time disk I/O processor can be reading and transferring the next block
into a different buffer. This technique can be used to write a continuous stream of blocks from
memory to disk. It permits continuous reading/writing of blocks thus, eliminating seek time and
rotational delay for all except for the first block transfer.
A file may have variable length records because of the following reasons
• The file records are of same record type but one or more fields may be of varying size.
• The file records are of same record type but , one or more fields may have multiple value
for the same field for individual records. Such fields are called repeating fields.
• A file may contain same record type but the fields may be optional.
• A file may contain records of different record types and hence of varying size.
For variable-length fields, each record has a value for each field, but we do not know the
exact length of some fields. To determine the bytes within a particular record that represent each
field, we can use special characters (such as $, %,?) - which do not appear in any field value to
terminate variable length fields. These characters are called separator characters.
The values in the record are stored as <field name, field value> pairs. Separators are used to
separate field name from field value, separate one field from the next and for repeating field.
We can also assign a short field type code – say, an integer number to each field and include the
record sequence as <field-type, field value>pairs. Repeating field needs one separator character
to separate the repeating values of the field and another separator to indicate the termination of
the field.
organization. Variable length records usually use spanned organization. When records are not
allowed to cross block boundaries the organization is unspanned. This is generally used in fixed
length records.
• Read/Get – copies the current record from buffer to program variable in the user
program
• FindNext – searches for the next record in the file that satisfies the search
condition
• Delete – deletes the current record and updates the file on the disk to reflect
deletion
• Modify – modifies the field values for current record and updates the file on the
disk
• Insert – inserts a new record in the file by locating the block where the record is to
be inserted
• Close – completes file access by releasing the buffers.
All the above operations except open/close are called record-at-time operations because
they apply to single record.
The following are set at time operations that apply to a set of records
• Find All – locates all records that satisfy a given search condition
• Find n – searches for first record that satisfies a given search condition and then
continues to locate next n-1 records
• Find ordered – retrieves all the records in a file in some specified order
• Reorganize – starts reorganizing process. Reorders the file records by sorting
them in a specified order.
2. Finding a record in the ordering of the key field requires no additional block
access.
3. A search condition based on the value of the ordering key results in faster access.
Binary search method is used to search records in sorted files. Inserting and
deleting a record is expensive because the records are ordered. To insert a record,
we must find a correct position in the file to insert the record in that position. In
order to overcome the above situation two files are used. A transaction file –
unordered file and a master file – ordered file. New records are added to the end
of the transaction files. Periodically this file is sorted and merged with the master
file during reorganization.
• Multiple hashing – The program applies a second hash function if the first results in a
collision
Assignment
Short Answers (2 marks)
1. Define mirroring
2. Define stripping
3. Define seek time
4. Define block transfer time
5. What are the limitations in internal hashing?
6. What do you mean by track?
7. Define cylinder.
Oracle SQL*Plus
• Oracle server is a separate tool that comes as a part of oracle enterprise server as well as
Oracle Workgroup server via which user can communicate interactively with the Oracle
server.
• Oracle provide an interactive SQL tool called SQL*Plus, which allow user to enter ANSI
SQL sentences and pass them to the Oracle Engine for execution.
• To use ANSI SQL the user must load the SQL*Plus tool in clients memory, link to the
server & then communicate with the Oracle Engine loaded on the server.
data to tables, or modify data, drop the table, set permissions for users. SQL commands are
grouped into four major categories depending on their functionality:
• Data Definition Language (DDL) - These SQL commands are used for creating,
modifying, and dropping the structure of database objects. The commands are CREATE,
ALTER, DROP, RENAME, and TRUNCATE.
• Data Manipulation Language (DML) - These SQL commands are used for storing,
retrieving, modifying, and deleting data. These commands are SELECT, INSERT,
UPDATE, and DELETE.
• Transaction Control Language (TCL) - These SQL commands are used for managing
changes affecting the data. These commands are COMMIT, ROLLBACK, and
SAVEPOINT.
• Data Control Language (DCL) - These SQL commands are used for providing security to
database objects. These commands are GRANT and REVOKE.
Features of SQL
• SQL can be used by a range of users, including those with little or no programming
experience.
• It is a non procedural language.
• It reduces the amount of time required for creating and maintaining systems.
• It is an English-like language.
8.3.1 CHAR
The CHAR datatype stores fixed-length character strings. When you create a table with a
CHAR column, you must specify a string length (in bytes or characters) between 1 and 2000
bytes for the CHAR column width. The default is 1 byte. Oracle then guarantees that:
When you insert or update a row in the table, the value for the CHAR column has the
fixed length.
• If you give a shorter value, then the value is blank-padded to the fixed length. If a value
is too large, Oracle Database returns an error.
8.3.2 VARCHAR2
The VARCHAR2 data type stores variable-length character strings. When you create a
table with a VARCHAR2 column, you specify a maximum string length (in bytes or characters)
between 1 and 4000 bytes for the VARCHAR2 column. For each row, Oracle Database stores
each value in the column as a variable-length field unless a value exceeds the column's
maximum length, in which case Oracle Database returns an error. Using VARCHAR2 and
VARCHAR saves on space used by the table.
For example, assume you declare a column VARCHAR2 with a maximum size of 50
characters. In a single-byte character set, if only 10 characters are given for the VARCHAR2
column value in a particular row, the column in the row's row piece stores only the 10 characters
8.3.3 NUMBER
The NUMBER datatype stores fixed and floating-point numbers. Numbers of virtually
any magnitude can be stored and are guaranteed portable among different systems operating
Oracle Database, up to 38 digits of precision. For numeric columns, you can specify the column
as:
column_name NUMBER
Optionally, you can also specify a precision (total number of digits) and scale (number of
digits to the right of the decimal point):
If a precision is not specified, the column stores values as given. If no scale is specified,
the scale is zero.
8.3.4 DATE
The DATE datatype stores point-in-time values (dates and times) in a table. The DATE
datatype stores the year (including the century), the month, the day, the hours, the minutes, and
the seconds (after midnight). For input and output of dates, the standard Oracle date format is
DD-MON-YY e.g. 13-AUG-89
Syntax:
a. The general format of CREATE command is
CREATE TABLE tablename
(column1 data type(size),
column2 data type(size), column3
data type(size),
:
column-n data type(size));
b. We can create a table from anther table in SQL. The syntax is as follows
CREATE TABLE <new table> (<column1>, <column2>)
AS SELECT <column1>, <column2> FROM <existing table>;
Example:
a. Create a table called student that contains roll number, name and marks in three subjects
SQL> create table student
2 (rollno number(2),
3 name varchar2(20),
4 m1 number(2),
5 m2 number(2), 6 m3 number(2)); Table created.
b. Create a table named sample from the existing table student that contains only rollno and
names of students
SQL> create table sample(rollno, name)
2 as select rollno,name from student;
Table created.
c. Create a table named sample1 that contains the same structure as student but with no
records SQL> create table sample1
2 as select * from student where 1=2;
Table created.
Syntax:
a. To select all rows and all columns
SELECT * FROM <table name>;
ROLLNO NAME M1 M2 M3
------------- --------------- -------- -------- -------
11 Raja 50 60 70
12 Rama 70 80 75
13 John 45 55 65
14 Gita 40 50 45
15 Tom 30 35 25
DBMS and Oracle 58
Srinivas Institute of Management Studies II Semester BCA
5 rows selected
ROLLNO NAME
---------- --------------------
11 Raja
12 Rama
13 John
14 Gita
15 Tom
5 rows selected
ROLLNO NAME M1 M2 M3
---------- -------------------- ---------- ---------- ----------
11 Raja 50 60 70
12 Rama 70 80 75
2 rows selected
d. Display names of students who secured more than 50 either in subject1 or subject 3
SQL> select name from student where m1>=50 or m3>=50;
NAME
--------------------
Raja
Rama
John
3 rows selected
e. Display the different courses available
SQL> select distinct course from student;
COURS
-----
bca
bbm
mca
3 rows selected
The DELETE command is used to delete rows from a table that satisfies the condition and
returns the number of records that were deleted. If the DELETE command is executed without a
WHERE clause then, all rows are deleted. This verb either deletes all the rows or a set of rows in
a given table
Syntax:
a. DELETE FROM <table name>;
b. DELETE FROM <table name WHERE <condition>;
Example:
a. Remove all the records from sample table.
SQL> select * from sample;
ROLLNO NAME
---------- --------------------
11 Raja
12 Rama
13 John
14 Gita
15 Tom
5 rows selected
Syntax:
a. Adding new tables
ALTER TABLE <table name>
ADD(<new column><data type>(size),
:
Example:
a. Add a new column Total with data type number and size 2
SQL> alter table student
2 add (total number(2));
Table altered.
Syntax:
a. UPDATE <table name> SET
<column 1>=<expression>,
:
<column n>=<expression>;
Example:
a. Increment the marks of all students by 10 in subject2 SQL> update student set
m2=m2+10; 4 rows updated.
8.4.7 RENAME
Purpose:
RENAME command is used to rename or give another name to the existing table.
Syntax:
RENAME <old table name> TO <new table name>;
Example:
SQL> rename student to student1;
Table renamed.
8.4.8 DESCRIB
EPurpose:
The DESCRIBE command is used to display the structure of a table. This command displays the
column names, the data types and the special attributes that are connected to the table.
Syntax:
DESCRIBE <table name>;
Example:
SQL> describe student;
Name Null? Type
------------------------------------------------- ----------------------------
ROLLNO NUMBER(2)
NAME VARCHAR2(20)
M1 NUMBER(2)
M2 NUMBER(2)
M3 NUMBER(2)
TOTAL NUMBER(3)
Syntax:
DROP TABLE <table name>;
Example:
SQL> drop table student1;
Table dropped.
Operators Description
= equal to
<>, != is not equal to
< Less than
> Greater than
<= less than or equal to
>= greater than or equal to
Examples:
a. List the roll number and names student whose total is more than 200
SQL> select rollno,name from student
2 where total>200;
ROLLNO NAME
12 Sriram
17 Shyam
2 rows selected
NAME
John
Gita
Tom
3 rows selected
c. List the names of students who got more than or equal to 70 in subject3
SQL> select name from student
2 where m3>=70;
NAME
Sriram
Shyam
2 rows selected
Example:
a. List the details of students who secured more than 60 in subject 1 and subject 2 SQL>
select * from student where m1>60 and m2>60;
b. List the names of students who secured less than 50 in any subject.
SQL> select name from student where m1<50 or m2<50 or m3<50;
NAME
John
Gita
Tom
3 rows selected
Example:
a.List the names of students whose total is in the range 180 and 250
SQL> select * from student where total between 180 and 250;
2 rows selected
Example:
a.List the names of students whose name begins with ‘R’
SQL> select name from student where name like 'S%'
NAME
--------------------
Sriram
Sita
Shyam
3 rows selected
b. List the name and roll number of students whose name ends with ‘a’ SQL> select
rollno,name from student where name like '%a';
ROLLNONAME
14 Gita
DBMS and Oracle 65
Srinivas Institute of Management Studies II Semester BCA
16 Sita
2 rows selected
c. List the names of students who have ‘i’ as the second letter in their name.
SQL> select name from student where name like '_i%';
NAME
--------------------
Gita
Sita
2 rows selected
d. List the course whose name ends with the letter ‘a’
SQL>select course from student where course like '%m'
COURSE
bbm
bbm
2 rows selected
IN and NOT IN
The arithmetic operator (=) compares a single value to another single value. In case a value
needs to be compared to a list of values then the IN predicate is used. It reduces the need to use
multiple OR conditions in a query.
Example:
a. List the student names and course who are studying either mca or bca
SQL> select name, course from student where course in ('mca','bca');
NAME COURSE
Sriram bca
Gita bca
Sita mca
Tom Mca
4 rows selected
b. List the student names along with their course who are not studying mca SQL>
select name, course from student where course not in ('mca')
NAME COURSE
Sriram Bca
John Bbm
Gita bca
Shyam Bbm
4 rows selected
8.6 DUAL and SYSDATE
DBMS and Oracle 66
Srinivas Institute of Management Studies II Semester BCA
SYSDATE
--------------
18-NOV-15
Average
----------
171.666667
• MAX – Returns the maximum value in a given column E.g. Display the maximum total
from student table
SQL> select max(total) "Maximum Total" from student;
Maximum Total
--------------------
235
• MIN – Returns the minimum value in a given column E.g. Display the minimum total
from student table
SQL> select min(total) "Minimum Total" from student;
Minimum Total
-------------------
100
• COUNT – Returns the number of rows in a table
E.g. Display the number of students in student table
SQL> select count(*) from student;
COUNT(*)
--------------
6
• SUM – Returns the sum of values in a given column
E.g. Display the sum total of marks in subject1 from student table
SQL> select sum(m1) "Marks in Subject1" from student;
Marks in Subject1
-----------------
295
String Functions:
String functions are used to manipulate text strings. They accept strings or characters as
input and can return both character and number values as output. Few of the character or text
functions are as given below:
DBMS and Oracle 68
Srinivas Institute of Management Studies II Semester BCA
returned.
Examples:
Numeric Functions:
Numeric functions are used to perform operations on numbers. They accept numeric
values as input and return numeric values as output. Few of the Numeric functions are:
The following examples explains the usage of the above numeric functions
Function Name Examples
ABS (x) SQL> select abs(-26) from dual;
ABS(-26)
26
CEIL (x) SQL> select ceil(34.6) from dual;
CEIL(34.6)
35
FLOOR (x) SQL> select floor(34.6) from dual;
FLOOR(34.6)
34
TRUNC (x, y) SQL> select trunc(38.546,2) from dual;
TRUNC(38.546,2)
38.54
ROUND (x, y) SQL> select round(38.546,2) from dual
ROUND(38.546,2)
38.55
POWER(m,n) SQL> select power(5,2) from dual;
POWER(5,2)
25
Date Functions:
These functions are used to manipulate and extract values from the date column of a table
Function Name Return Value
ADD_MONTHS(date,n) Returns the date after adding the number of months
specified in the function
LAST_DAY(date) Returns the last date of the month specified in the
function
Conversion Functions:
These are functions that help us to convert a value in one form to another form. For
example, a null value into an actual value, or a value from one datatype to another datatype like
NVL, TO_CHAR, TO_NUMBER, TO_DATE.
The below table provides the examples for the above functions
There are two types of data constraints that can be applied to data being inserted into an oracle
table. One type of constraint is the I/O constraint that determines the speed at which data can be
inserted or extracted from a table. The other type of constraint is called the business rule
constraint.
Example:
Create a table EMPLOYEE using SQL command to store details of employees such as EMPNO,
NAME, DESIGNATION, DEPARTMENT, GENDER and SALARY. Specify Primary Key and
NOT NULL constraints on the table and allow only ‘M’ or ‘F’ for the column GENDER. Write
the following SQL queries :
Table created.
b. Show that the above constraint has been applied using USER CONSTRAINTS
table
SQL>select owner, table_name, constraint_type from user_constraint
where table_name='STUDENT';
OWNER TABLE_NAME C
------------------------------ ------------------------------ -
SCOTT STUDENT P
Integrity constraints can be dropped if the constraint is no longer needed. This can be achieved by
the ALTER table using the DROP clause.
Example:
a.Drop primary key constraint from student
SQL> alter table student drop primary
key; Table altered.
COURS MAX(TOTAL)
----- ----------
bca 235
bbm 210
mca 165
3 rows selected
The HAVING cluse is used in conjunction with the group by clause. It imposes a
condition on the group by clause, which further filters the groups created by the group by clause.
Each column specification specified in the having clause must occur in the list of columns
mentioned in the group by clause.
Example:
a.List the course with more than 1 student.
SQL> select course from student
2 group by course
3 having count(*)>1;
COURSE
bca
mca
Syntax:
SELECT column-list
FROM table_name [WHERE condition]
[ORDER BY column1 [, column2, .. columnN] [DESC]];
Example:
NAME TOTAL
-------------------- ----------
Tom 100
Gita 145
Sita 165
Shyam 210
Sriram 235
5 rows selected
NAME M1
-------------------- ----------
Sriram 70
Shyam 60
Sita 50
Gita 40
Tom 30
5 rows selected
does not exist, it returns false. The EXISTS operator ensures that the search in the inner query
terminates when at least one match is found. The NOT EXISTS operator enables to test whether
a value retrieved by the outer query is not a part of the result set of the values retrieved by the
inner query.
Examples:
Consider the information in the following tables
SQL> select * from employ;
EMPNO ENAME SAL DEPTNO
E001 Raja 6000 D002
E002 Rani 7000 D001
E003 Jaya 5000 D003
E004 Ranbir 8000 D001
E005 Rajni 4000 D004
E006 Sita 5500 D003
6 rows selected.
SQL> select * from depart;
DNO DNAME LOC
D001 accounts chennai
D002 research mumbai
D003 HRD bangalore
D004 EDP hyderabad
D005 Inventory Goa
4 rows selected
a. Display the names of employees who are working in Chennai
SQL> select ename from employ
2 where deptno in (select dno from depart where loc='chennai');
ENAME
---------------
Rani
Ranbir
2 rows selected
b. Display the location where Sita is working
SQL> select loc from depart
2 where dno=(select deptno from employ where ename='Sita');
LOC
---------------
Bangalore
c. List the employee number, employee name, salary and average salary of the
department whose salary is more than the average salary in the
department(inline view)
SQL> select a.empno,a.ename,a.sal,b.avgsal
d. List the employee names, salary who are drawing maximum salary in each
department
(correlated subquery)
SQL> select ename,deptno,sal from employ a
2 where sal = (select max(sal) from employ where deptno=a.deptno);
DNO DNAME
---- ---------------
D005 inventory
f. List the employee names who are working in accounts department
SQL> select ename from employ a
2 where exists (select dname from depart where dno=a.deptno and
dname='accounts');
ENAME
---------------
Ranbir
Rani
8.15 Joins
There are occasions where we need to retrieve data from multiple tables. This is achieved in
SQL using joins. Tables are joined on columns that have same data type and data width in the
tables. The tables are related with the help of primary key and foreign keys of the table. The
different types of joins are
• INNER JOIN
DBMS and Oracle 80
Srinivas Institute of Management Studies II Semester BCA
• OUTER JOIN
• CROSS JOIN
• SELF JOIN
INNER JOIN – These joins are also called equi joins. They are known as equi joins because the
where clause compares two columns using the = operator. It is the most commonly used
operator. It returns all the rows from both the tables where there is a match.
Example:
a. Display the names of employees and the department in which they work
SQL> select ename,dname from employ, depart
2 where employ.deptno=depart.dno;
ENAME DNAME
--------------- ---------------
Raja research
Rani accounts
Jaya HRD
Ranbir accounts
Rajni EDP
Sita HRD
6 rows selected.
ENAME
---------------
Jaya
Sita
OUTER JOIN – This type of join can be used in selecting rows from both the tables regardless
of whether the tables have common values or not. NULL values are appended in the result set
where the data is missing. For left outer join use a (+) to the left condition and for right outer
join use a (+) to the right condition.
Syntax for Left outer join
SELECT table1.column, table2.column
FROM table1t1, table2 t2
WHERE t1.column(+)=t2.column;
Syntax for Right outer join
SELECT table1.column, table2.column
ENAME DNAME
--------------- ---------------
Raja research
Rani accounts
Jaya HRD
Ranbir accounts
Rajni EDP
Sita HRD
inventory 7 rows
selected.
b.Display the employee name and department using right outer join SQL>
select ename, dname
2 from employ e, depart d
3 where e.deptno=d.dno(+);
ENAME DNAME
--------------- ---------------
Ranbir accounts
Rani accounts
Raja research
Sita HRD
Jaya HRD
Rajni EDP
Gita
7 rows selected.
CROSS JOIN – A cross join returns the Cartesian product. This means that the join combines every
row from the left table with every row in the right table.
Example:
SQL> select * from sam1;
ENO ENAME
---- ----------
E001 janani
E002 jahnavi
PNO PNAME
---- ----------
P001 soap
P002 shampoo
a.Illustrate a cross join operation on sam1 and sam2
SQL> select eno,ename,pno,pname
2 from sam1 cross join sam2;
SELF JOIN – A self-join is one where the same table is involved in the join operation
Example:
a.Display the employee names and salary who earn more than Sita
SQL> select e1.ename,e1.sal
2 from employ e1, employ e2
3* where (e1.sal>e2.sal) and (e2.ename='Sita');
ENAME SAL
--------------- ----------
Raja 6000
Rani 7000
Ranbir 8000
Union Clause:
Multiple queries can be put together and their output can be combined using the union clause.
The union clause merges the output of two or more queries into a single set of rows. Here, the
number of columns and the data type of the columns must the same in all the select statements
used in the query.
Intersect Clause:
Multiple queries can be put together and their output can be combined using the intersect
clause. It outputs only the rows produced by both the queries intersected. The output in the
intersect clause will include only those rows that are retrieved common to both the queries. Here,
the number of columns and the data type of the columns must the same in all the select
statements used in the query.
DBMS and Oracle 83
Srinivas Institute of Management Studies II Semester BCA
Minus Clause:
Multiple queries can be put together and their output can be combined using the minus clause.
The minus clause outputs the rows produced by the first query, after filtering the rows retrieved
by the second query. Here, the number of columns and the data type of the columns must the
same in all the select statements used in the query.
Revoking Privileges:
Privileges once given can be denied to the user using the REVOKE command. The object owner
can revoke privileges granted to another user.
Syntax:
GRANT <object privileges>
ON <object name>
FROM <user name>;
Assignment
Short Answers (2 marks)
1. Give syntax and example for the following commands in SQL:
CREATE, INSERT, SELECT, ALTER, UPDATE, RENAME, DROP
2. Give the syntax use of functions INTCAP(), POWER(), ROUND().
3. Explain any four data types that a table in Oracle can hold.
4. How to sort a table in increasing and decreasing order? Explain with example.
5. What are the two levels of constraints? Give examples.
6. Write a note on pattern matching using % and _ in the LIKE clause.
7. What is sub query? Explain with example.
8. How do you define foreign key at column level and table level?
DBMS and Oracle 84
Srinivas Institute of Management Studies II Semester BCA
• PL/SQL sends the entire block of SQL code to oracle engine. As the entire block of SQL
code is passed to Oracle engine at one time for execution, all the changes made to the data
in the table are done or undone in one go.
• PL/SQL facilitates the displaying of user-friendly messages when errors are encountered
• PL/SQL allows declaration and use of variables in blocks of code. The variables are used to
store intermediate results of a query for later processing
• PL/SQL all sorts of calculations can be done efficiently and quickly
• Applications written in PL/SQL are portable to any computer hardware system and
operating system
Example: DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
/
Output:
Hello, World!
BEGIN
SQL statement executor
Procedural Statements;
SQL statements;
EXCEPTIONS
SQL statements;
END;
Variables:
A variable in PL/SQL is a named variable. A variable name must begin with a character and can be
followed by a maximum of 29 characters. Reserved words cannot be used as variable names unless
enclosed within double quotes. A blank space cannot be embedded in a variable name. variable
names are not case sensitive. Variables are separated from each other by a comma. Values can be
assigned to variables in two ways:
1. Using the assignment operator :=
2. Selecting or fetching table data values into variables
Constants:
A constant is declared in the same way as how a variable is declared. The only difference is that
we use a keyword constant and a value is assigned to it immediately. Thereafter no further
assignments can be made.
Logical Comparisons:
Comparisons in PL/SQL can be made using Boolean expressions. A Boolean expression
consists of variables separated by relational operators{<,>,<=,>=,<>}. A logical expression is a
combination of two or more Boolean expressions separated by logical operators{AND,OR,
NOT}. A boolean expression always evaluates to TRUE, FALSE or NULL
Comments:
A comment in PL/SQL can be written in two ways:
1. It can begin with a double hyphen(--). Here, the entire line can be treated as a
comment.
2. A group of lines can be enclosed between /* and */. All the lines will be ignored
for processing Example:
a. --Single line comment
b. /* This is
a comment*/
Radius: 9.5
Circumference: 59.69
Area: 283.53
2) IF condition THEN
statement 1;
ELSE
statement 2;
END IF;
Example: SQL>
ed samif.sql set
serveroutput on
declare x
number(2); y
number(2); begin
x:=&x; y:=&y; if
x>y then
dbms_output.put_line (x || 'is bigger');
else
dbms_output.put_line (y || 'is
bigger'); end if; end;
Output:
Enter value for x:
35 old 5: x:=&x;
new 5: x:=35;
Enter value for y:
25 old 6: y:=&y;
new 6: y:=25;
35is bigger
PL/SQL procedure successfully completed.
Simple Loop:
A Simple Loop is used when a set of statements is to be executed at least once before the
loop terminates. An EXIT condition must be specified in the loop, otherwise the loop will get into
an infinite number of iterations. When the EXIT condition is satisfied the process exits from the
loop.
Output:
Even numbers from 1 to 10 are:
2
4
6
8
10
PL/SQL procedure successfully completed.
While loop:
A WHILE LOOP is used when a set of statements has to be executed as long as a
condition is true. The condition is evaluated at the beginning of each iteration. The iteration
continues until the condition becomes false.
hoWHILE <condition>
LOOP statements;
END LOOP;
Example:
set serveroutput on
declare
pi constant number(5,2):=3.14;
r number(2);
c number(5,2);
begin
r:=3; while
r<=7 loop
c:=2*pi*r;
insert into circle values(r,c);
r:=r+1; end
loop;
end;
Output:
SQL> @samwhile.sql;
PL/SQL procedure successfully completed.
RADIUS CIRCUM
---------- ----------
3 18.84
4 25.12
5 31.4
6 37.68
7 43.96
FOR Loop
A FOR LOOP is used to execute a set of statements for a predetermined number of times.
Iteration occurs between the start and end integer values given. The counter is always
incremented by 1. The loop exits when the counter reachs the value of the end integer.
Example:
set serveroutput on
declare
i number; n
number;
f number:=1;
begin
n:=&n;
for i in 1..n
loop
f:=f*i;
end loop;
dbms_output.put_line('Factorial is '|| f); end;
Output:
Enter value for n: 5 old
6: n:=&n; new 6:
n:=5;
Factorial is 120
• Rollback
Closing Transactions – A transaction can be closed using either a commit or rollback
statement. By using these statements, table data can be changes or all the changes made to the
table data can be undone
COMMIT – A commit ends the current transaction and makes permanent any changes made to
the table data during a transaction. Syntax: commit;
SAVEPOINT – It marks and saves the current point in the processing of a transaction. When a
savepoint is used with a rollback statement, parts of the transaction can be undone. An active
savepoint is one that is specified since the last COMMIT or ROLLBACK.
Syntax:
savepoint <savepointname>;
ROLLBACK – A rollback does exactly the opposite of COMMIT. It ends the transaction but
undoes any changes made during the transaction. Rollback can be fired at the SQL prompt with
or without savepoint clause.
Syntax:
rollback [work] [to [savepoint]<savepointname>];
Assignment
Short Answers (2 marks)
1. What are the limitations of SQL?
2. How do you write comments in PL/SQL?
3. What is the purpose of GOTO statement in PL/SQL
4. Give the syntax of for loop in PL/SQL
5. Give the syntax of simple if in PL/SQL 6.Give the syntax of if-else in PL/SQL
7. What is an Oracle transaction?
8. What is the purpose of commit in PL/SQL?
9. What is the purpose of rollback in PL/SQL?
10. What is the purpose of savepoint in PL/SQL?
Long answers(4 or more marks)
1. Explain the advantages of PL/SQL.
2. Give syntax of IF and explain with example.
3. Explain PL/SQL block structure with example.
4. Explain if-else statement in PL/SQL with an example.
5. Explain loop statement in PL/SQL with an example.
6. Explain while statement in PL/SQL with an example.
7. Explain for statement in PL/SQL with an example.
CHAPTER 10
CURSORS
10.1 Introduction:
The Oracle engine uses a work area for its internal processing in order to execute an SQL
statement. This work area is private to SQL operations and is called a Cursor. The data that is
stored in the cursor is called the Active Data Set. The size of the cursor in the memory is the
size required to hold the number of rows in the active data set. Oracle has a predefined area in
the main memory set aside, within which cursors are opened. . A cursor contains information on
a select statement and the rows of data accessed by it. A cursor can hold more than one row, but
can process only one row at a time
Cursors are classified depending on the circumstances under which they are opened. Both
implicit and explicit cursors have the same functionality, but they differ in the way they are
accessed
Example: Consider the PL/SQL Block that uses implicit cursor attributes as shown below:
/*increase the salary of all employees by 1000*/
DECLARE var_rows number(5);
BEGIN
UPDATE employ
SET salary = salary + 1000;
IF SQL%NOTFOUND THEN
dbms_output.put_line('None of the salaries where updated');
ELSIF SQL%FOUND THEN
var_rows := SQL%ROWCOUNT;
dbms_output.put_line('Salaries for ' || var_rows || 'employees are updated');
END IF;
END;
Output:
Salaries for 7employees are updated
PL/SQL procedure successfully completed.
In the above example we are creating a cursor ‘emp_cur’ on a query which returns the
records of all the employees with salary greater than 5000.
Opening a cursor – Opening a cursor executes a query and creates an active data set that
contains all rows which meet the search criteria of the query. An open statement retrieves the
records from the table and places the records in the cursor Syntax:
OPEN cursor_name;
Fetching records from the cursor – The fetch statement retrieves the rows from the active data
set into the memory variables declared in the PL/SQL block one row at a time. Each time a fetch
statement is executed, the cursor pointer is advances to the next row in the active data set.
Syntax:
FETCH cursor-name INTO variable list;
Closing a cursor – The close statement disables the cursor and the active data set becomes
undefined. This will release the memory occupied by the cursor and the active data set.
Syntax:
CLOSE cursor-name;
Example:
/*Display employee name and salary whose salary is more than 6000*/
SET SERVEROUTPUT ON
DECLARE
emp_rec employ%rowtype;
CURSOR emp_cur IS
SELECT *
FROM employ
WHERE sal > 6000;
BEGIN
OPEN emp_cur;
FETCH emp_cur INTO emp_rec;
dbms_output.put_line (emp_rec.ename || ' ' || emp_rec.sal);
CLOSE emp_cur;
END;
/
Output:
SQL> @EXPCUR.SQL
Gita 7000
PL/SQL procedure successfully completed.
Example:
/*To display all employees whose salary is greater than 9000*/
SET SERVEROUTPUT ON
DECLARE
CURSOR emp_cur IS
SELECT *
FROM employ
WHERE sal > 9000;
BEGIN
for emp_rec in emp_cur
loop
dbms_output.put_line (emp_rec.ename || ' ' || emp_rec.sal);
end loop;
END;
/
Output:
Rani 10000
Ranbir 11000
PL/SQL procedure successfully completed.
Example:
/*DISPLAY DETAILS OF STUDENT WITH ROLLNUMBER */
SET SERVEROUTPUT ON
DECLARE
cursor c(no number) is select * from student
where rollno = no; tmp
student%rowtype;
BEGIN
FOR tmp IN c(14)
LOOP
dbms_output.put_line('ROLLNO: '||tmp.rollno);
dbms_output.put_line('STUDENT_Name: '||tmp.name);
dbms_output.put_line('TOTAL: '||tmp.total);
dbms_output.put_line('COURSE: '||tmp.course);
END Loop;
END;
/
Output:
SQL> @PARCUR.SQL
ROLLNO: 14
STUDENT_Name: Gita
TOTAL: 145
COURSE: bca
Assignment
Short Answers (2 marks)
1. Define a cursor in PL/SQL
2. Give the syntax of declaring a cursor
3. List the commands used to work with explicit cursors
Long answers(4 or more marks)
1. What is CURSOR? Explain all explicit cursor attributes.
2. Explain all the implicit cursor attributes.
3. Explain the working of implicit cursor with an example
4. Explain the working of explicit cursor with an example 5.Explain the commands necessary
to work with cursors?
6. Explain parameterized cursors with an example
7. Explain cursor for loop with an example
CHAPTER 11 ERROR
HANDLING IN PL/SQL
Introduction:
When an SQL statement fails, the Oracle engine is the first to recognize this as an
exception condition. The oracle engine immediately tries to handle the exception and resolve it.
This is done by raising a built-in exception handler. An exception handler is nothing but a code
block in memory that will attempt to resolve the current exception condition. The oracle engine
can recognize every exception condition that occurs in the memory. To handle very common and
repetitive exception conditions, the oracle engine uses Named Exception Handlers.
PL/SQL Errors are pre-defined and are automatically raised by Oracle whenever an error is
encountered. Each error is assigned a unique number and a message. In PL/SQL, a warning or
error condition is called an exception. Exceptions can be internally defined (by the run-time
system) or user defined. Examples of internally defined exceptions include division by zero and
out of memory. Some common internal exceptions have predefined names, such as
ZERO_DIVIDE and STORAGE_ERROR. The other internal exceptions can be given names.
When an error occurs, an exception is raised. That is, normal execution stops and control
transfers to the exception-handling part of your PL/SQL block or subprogram. Internal
exceptions are raised implicitly (automatically) by the run-time system. User-defined exceptions
must be raised explicitly by RAISE statements, which can also raise predefined exceptions. To
handle raised exceptions, you write separate routines called exception handlers. Syntax:
EXCEPTION
WHEN<Exception Name> THEN
<User Defined Action to be carried out>
Syntax:
DECLARE
<Exception Name> EXCEPTION
PRAGMA EXCEPTION_INIT(<Exception Name>,<Error Code>);
BEGIN
…..
EXCEPTION
WHEN<Exception Name> THEN
<Action>
END;
Example:
SET SERVEROUTPUT
ON DECLARE myex
EXCEPTION; i
NUMBER;
BEGIN
FOR i IN (SELECT * FROM student)
LOOP
IF i.rollno = 15 THEN
RAISE myex;
END IF;
END LOOP;
EXCEPTION
WHEN myex THEN
dbms_output.put_line('ROLLNO is Filled Already');
END;
/
Output:
SQL> @USEREX.SQL
ROLLNO is Filled Already
PL/SQL procedure successfully completed.
DBMS and Oracle 104
Srinivas Institute of Management Studies II Semester BCA
Assignment
Short Answers (2 marks)
1. What do you mean by an exception handlers?
2. List any two oracle named exceptions.
3. Give the syntax of dealing with exception in PL/SQL.
Long answers(4 or more marks)
1. Explain user defined exceptions for business rule validation with an example.
2. Explain user named exception handlers
3. Explain exception handling in PL/SQL
12.1 Introduction:
Stored Procedures and functions are PL/SQL database objects that are stored in the Oracle
database. They can be invoked or called by any PL/SQL block that appears within an
application. Before a procedure or function is stored, the oracle engine parses and compiles the
procedure/function. Oracle engine performs the following steps automatically while creating a
procedure or function
• Compiles the procedure or function
• Stores the procedure or function in the database
The oracle engine compiles the PL/SQL block. If errors occur during the compilation of
procedure or function, an invalid procedure or function gets created. The oracle engine displays
the message after creation of that the procedure or function was created with compilation errors.
The compilation process does not display any errors. These errors can be viewed by giving the
following statement at the SQL prompt
SQL> SELECT * FROM USER_ERRORS;
Example:
SQL> ed proc1.sql
/*procedure */
CREATE or REPLACE PROCEDURE pro1(no in number,temp out student%rowtype)
IS
BEGIN
SELECT * INTO temp FROM student WHERE rollno = no;
END;
/
SQL> @proc1;
Procedure created.
SQL> ed sqlproc.sql
/*PL-SQL code for implementing procedure*/
SET SERVEROUTPUT ON
DECLARE temp student
%rowtype; no
number :=&no; BEGIN
pro1(no,temp);
dbms_output.put_line(temp.rollno||' '||
temp.name||' '||
temp.total);
END;
/
Output:
SQL> @sqlproc.sql; Enter
value for no: 12 old 3:
no number :=&no; new 3:
no number :=12; 12 Sriram
235
PL/SQL procedure successfully completed.
12.4 Functions:
A function is a named PL/SQL Block which is similar to a procedure. The major difference
between a procedure and a function is, a function must always return a value, but a procedure
may or may not return a value. Here, return type in the header section defines the return type of
the function. The return data type can be any of the oracle data type like varchar, number etc.
Syntax for creating a function:
CREATE OR REPLACE FUNCTION <function_name>
(<Argument> {IN }<data type>…)
RETURN return_datatype;
IS
Declaration_section
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;
Example:
SQL> ED STUDFUN.SQL
/*create a function*/
CREATE or REPLACE FUNCTION STUDFUN(no in number) RETURN varchar2
IS
name varchar2(20);
BEGIN
select name into name from student where rollno = no;
return name;
END;
SQL> @STUDFUN.SQL;
Function created.
SQL> ed plfun.sql
/*PL-SQL block to call the function*/
SET SERVEROUTPUT
ON DECLARE no
number :=&no; name
varchar2(20); BEGIN
name := studfun(no);
dbms_output.put_line('Name:'||' '||name);
END;
Output:
SQL> @plfun.sql;
Enter value for no: 12 old 2:
no number :=&no; new 2:
no number :=12;
Name: Sriram
Assignment
Short Answers (2 marks)
1. What do you mean by a stored procedure?
2. What do you mean by a function in PL/SQL?
3. Differentiate between function and procedure.
4. Give the syntax of creating a function in PL/SQL.
5. Give the syntax of creating a procedure in PL/SQL.
6. What are the ways in which you can pass parameters to procedures in PL/SQL?
Introduction:
A package is an Oracle object, which holds other objects within it. PL/SQL packages are
schema objects that groups logically related procedures, functions, constants, variables and
cursors. It is a way of creating generic, encapsulated and reusable code. A package once written
and debugged is compiled and stored in Oracle’s system tables held in Oracle database.
Packages contain PL/SQL blocks of code, which have been written to perform some process
entirely on their own. These PL/SQL blocks do not require any input from other PL/SQL blocks
of code.
The specification is the interface to the package. It just DECLARES the types, variables,
constants, exceptions, cursors, and subprograms that can be referenced from outside the package.
In other words, it contains all information about the content of the package, but excludes the
code for the subprograms. All objects placed in the specification are called public objects. Any
subprogram not in the package specification but coded in the package body is called a private
object.
Package specification contains
• Name of the package
• Names of the data types of any arguments
• This declaration is local to the database and global to the package The syntax for
package specification is as follows:
CREATE PACKAGE <package-specification-name> IS
<function declaration>
<procedure declaration >
END<package-specification-name>;
SQL> ed sampkg
CREATE or REPLACE PACKAGE pkg1
AS
PROCEDURE janpro1
(no in number);
FUNCTION janfun1
(no in number)
RETURN number;
END pkg1;
/
SQL> @sampkg;
Package created.
END pkg1;
/
SQL> @pkgbody;
Package body created.
SET SERVEROUTPUT ON
DECLARE no number :=
&no;
m number;
BEGIN pkg1.janpro1(no); m :=
pkg1.janfun1(no);
dbms_output.put_line('Total: ' || m);
END;
/
SQL> @plpkg;
Enter value for no: 12 old 2:
no number := &no;
new 2: no number := 12;
Student Name:Sriram
Course Name:bca
Total: 235
Assignment:
Short Answers(2 marks)
1. Define a package in PL/SQL
2. What are the components available in the package specification of PL/SQL
3. Give the syntax of a package specification
4. Give the syntax of creating a package body
Long Answers(4 marks and above)
1. What are the advantages of packages
2. How do you work with packages in PL/SQL? Explain with an example
3. Explain with an example the working of package specification
called database triggers. Triggers are standalone because they are fired implicitly by the Oracle
engine.
Trigger Restriction
A trigger restriction specifies a Boolean expression that must be TRUE for a trigger to
fire. It is an option available for triggers that are fired for each row. Its function is to
conditionally control the execution of a trigger. A trigger restriction is specified using the
WHEN clause
Trigger Action
A trigger action is the PL/SQL code to be executed when a triggering statement is encountered
and any trigger restriction evaluates to TRUE. For row triggers, the statements in the PL/SQL
block have access to the column values of the current row being processed
Row trigger – A row trigger is fired each time a row in a table is affected by the triggering
statement. For example, if an update statement modifies multiple rows in a table, a row trigger is
fired once for each row affected by the update statement. If no rows are affected, the trigger is
not executed at all. Row triggers should be used when some processing is required whenever a
triggering statement affects a single row in a table.
Statement trigger – A statement trigger is fired once on behalf of the triggering statement,
independent of the number of rows being affected by the trigger. Statement triggers are used
when a triggering statement affects the rows in the table but the processing is independent of the
number of rows affected.
Example:
/*Create a trigger to insert the names of employees in CAPITALS*/
SQL> ed samtrg
CREATE or REPLACE TRIGGER trg1
BEFORE
INSERT ON employ
for each row
BEGIN
:new.ename := upper(:new.ename);
END;
/
SQL> @samtrg;
Trigger created.
2 values('&empno','&ename',&sal,'&deptno');
Enter value for empno: E008
Enter value for ename: ranjit
Enter value for sal: 7000 Enter value for deptno:
D004 old 2:
values('&empno','&ename',&sal,'&deptno')
new 2: values('E008','ranjit',7000,'D004')
1 row created.
Output:
SQL> select ename from employ;
ENAME
---------------
Gita
Raja
Rani
Jaya
Ranbir
Rajni
Sita
RANJIT
8 rows selected.
Example:
CREATE or REPLACE TRIGGER trg2
AFTER
DELETE ON employ
for each row
BEGIN
IF :old.empno = 'E001' THEN
raise_application_error(-20015, 'Do Not Delete this Row');
END IF;
END;
/
Output:
SQL>delete from emp1 where eno = 1;
Error Code: 20015
Error Name: Do Not Delete this Row
Assignment
Short Questions (2 marks)
15.1 Introduction
Indexes are auxiliary access structures that are used to speed up the retrieval of records in
response to certain search conditions. The index structures are additional files on disk that
provide secondary access paths, which provide alternative ways to access the records without
affecting the physical placement of records in the primary data file on disk. They enable efficient
access to records based on the indexing fields that are used to construct the index. Basically, any
field of the file can be used to create an index and multiple indexes on different fields – as well
as indexes on multiple fields—can be constructed on the same file. To find a record or records in
the data file based on a search condition on an indexing field, the index is searched, which leads
to pointers to one or more disk blocks in the data file where the required records are located. The
different types of single-level ordered indexes – primary, secondary, and clustering index.
A primary index is specified on the ordering key field of an ordered file of records. Ordering
key field is used to physically order the file records on disk, and every record has a unique value
for that field. If the ordering field is not a key field—that is, if numerous records in the file can
have the same value for the ordering field – another type of index, called a clustering index, can
be used. The data file is called a clustered file. In the latter case, a file can have at most one
physical ordering field, so it can have at most one primary index or one clustering index, but not
both. A third type of index, called a secondary index, can be specified on any nonordering field
of a file. A data file can have several secondary indexes in addition to its primary access method.
Note: Answer any ten questions from Part A and anyone full question from each Unit of Part B.
PART A
PART B
UNIT-I
UNIT-II
UNIT-III
UNIT-IV
8. a) Explain the PL/SQL block structure with an example.
b) Explain the conditional statements in PL/SQL with examples.
c) What is a Trigger? Explain the types of Trigger. (5+5+5)
9. a) With syntax and example explain any two looping statements in PL/SQL.
b) What is a function? How do you create a function? Explain.
c) What are the advantages of PL/SQL. (5+5+5)