Complete Dbms Notes English
Complete Dbms Notes English
Course :-BCA
Class :- BCA 2nd Year
Subject :- DBMS
Unit :- I-II-III-IV-V
By Anand Harsha 1
Contents
Unit-I ..................................................................................................................................................... 11
DATA: .................................................................................................................................................... 11
INFORMATION: ..................................................................................................................................... 11
ADVANTAGES OF THE DBMS: ................................................................................................................. 11
DISADVANTAGES OF DATABASE ............................................................................................................ 13
Data abstraction .................................................................................................................................... 13
Data model............................................................................................................................................ 15
Hierarchical Model ............................................................................................................................ 15
Features of a Hierarchical Model ................................................................................................... 16
Advantages of Hierarchical Model.................................................................................................. 16
Disadvantages of Hierarchical Model ............................................................................................. 16
Network Model ..................................................................................................................................... 16
Features of a Network Model ........................................................................................................ 17
Advantages of Network Model....................................................................................................... 17
Disadvantages of Network Model .................................................................................................. 18
Entity-Relationship Model ..................................................................................................................... 18
Features of ER Model ........................................................................................................................ 19
Advantages of ER Model .................................................................................................................... 19
Disadvantages of ER Model................................................................................................................ 19
Relational Model ................................................................................................................................... 19
Features of Relational Model ............................................................................................................. 20
Advantages of Relational Model ........................................................................................................ 20
Disadvantages of Relational Model .................................................................................................... 20
Data Independence ............................................................................................................................... 21
Logical Data Independence ................................................................................................................ 21
Physical Data Independence .............................................................................................................. 21
Data definition language ....................................................................................................................... 22
Data manipulation language .................................................................................................................. 22
DATABASE ADMINISTRATOR.................................................................................................................. 22
The responsibilities of a DBA.............................................................................................................. 22
USERS IN DBMS ..................................................................................................................................... 23
By Anand Harsha 2
Users are of 4 types: .......................................................................................................................... 23
1. Application programmers........................................................................................................... 23
2. End Users: .................................................................................................................................. 23
3. Database Administrator (DBA): .................................................................................................. 23
4. System Analyst........................................................................................................................... 24
Overall structure ................................................................................................................................... 24
Internal level: .................................................................................................................................... 25
Conceptual level: ............................................................................................................................... 25
External level: .................................................................................................................................... 25
Difference between file system and dbms(DBMS vs file system) ............................................................ 26
SCHEMA ............................................................................................................................................ 27
INSTANCES ........................................................................................................................................ 27
ENTITY RELATIONSHIP MODEL & BASIC CONCEPTS: ............................................................................... 28
ENTITY: .............................................................................................................................................. 28
TYPES OF ENTITY: .............................................................................................................................. 28
ATRIBUTE: ......................................................................................................................................... 28
TYPES OF ATTRIBUTES: .......................................................................................................................... 29
Simple attribute:................................................................................................................................ 29
Single-valued attribute: ..................................................................................................................... 29
Multi-value attributes: ....................................................................................................................... 29
Stored attribute: ................................................................................................................................ 29
Derived attribute: .............................................................................................................................. 30
RELATIONSHIP: .................................................................................................................................. 30
MAPPING CONSTRAINTS / CARDINALITY:............................................................................................... 30
KEYS: ..................................................................................................................................................... 31
Unit-II .................................................................................................................................................... 32
E-R DIAGRAM (ERD):.............................................................................................................................. 32
The elements of an ERD are: .............................................................................................................. 32
Creating an E-R DIAGRAM includes: ................................................................................................... 33
DESIGN OF AN E-R DATABASE SCHEMA: ................................................................................................ 33
REDUCTION OF E-R SCHEMA TO TABLE: ................................................................................................. 34
Reduce the ER diagram to relation table solved exercise................................................................ 34
By Anand Harsha 3
How to reduce an ER diagram to tables? Reduction of ERD to relation schema, Convert Entity
Relationship diagram to set of tables, ERD to relation schema examples, mapping ER diagram to
relational tables................................................................................................................................. 34
Reduce (convert) the following ER diagram to relational schema.............................................. 35
Generalization, Specialization and Aggregation in ER Model .................................................................. 38
Generalization ................................................................................................................................... 38
Specialization .................................................................................................................................... 39
Aggregation ....................................................................................................................................... 40
Unit IIIrd ................................................................................................................................................. 41
Oracle Architecture ............................................................................................................................... 41
Oracle instance: ................................................................................................................................. 41
Oracle database:................................................................................................................................ 42
User and server processes: ................................................................................................................ 42
Connecting to an Oracle Instance – Creating a Session .......................................................................... 43
Physical Structure – Database Files ........................................................................................................ 44
Memory Management and Memory Structures ................................................................................. 45
Oracle Database Memory Management ............................................................................................ 46
System Global Area ............................................................................................................................... 47
Program Global Area (PGA)................................................................................................................ 50
· Private SQL Area: ................................................................................................................... 51
Automatic Shared Memory Management .......................................................................................... 52
Library Cache ................................................................................................................................. 55
· Private SQL Area: ................................................................................................................... 56
Data Dictionary Cache ....................................................................................................................... 56
Buffer Caches .................................................................................................................................... 58
Database Buffer Cache ...................................................................................................................... 58
Redo Log Buffer ................................................................................................................................. 61
Large Pool ...................................................................................................................................... 62
Java Pool........................................................................................................................................ 63
Streams Pool ................................................................................................................................. 63
Processes .......................................................................................................................................... 63
PMON............................................................................................................................................ 66
By Anand Harsha 4
SMON ............................................................................................................................................ 67
DBWn (also called DBWR in earlier Oracle Versions) ...................................................................... 68
LGWR ............................................................................................................................................ 69
CKPT .............................................................................................................................................. 70
Unit – IVth .............................................................................................................................................. 73
SQL .................................................................................................................................................... 73
SQL DML and DDL .............................................................................................................................. 73
Basic Data Types ................................................................................................................................ 74
The CREATE TABLE Command:............................................................................................................... 75
Rules for Creating Tables ................................................................................................................... 76
Inserting Data into Tables ...................................................................................................................... 76
Viewing Data in the Tables .................................................................................................................... 77
Filtering Table Data ............................................................................................................................... 78
Selected Columns and All Rows ......................................................................................................... 78
Selected Rows and All Columns ......................................................................................................... 79
Selected Columns and Selected Rows ................................................................................................ 80
Eliminating Duplicate Rows when using a SELECT statement.............................................................. 81
Sorting Data in a Table........................................................................................................................... 81
DELETE Operations ................................................................................................................................ 83
Specific row(s) from a table ........................................................................................................... 83
All the rows from a table................................................................................................................ 83
Remove of ALL Rows.......................................................................................................................... 84
UPDATING THE CONTENTS OF A TABLE .............................................................................................. 84
ALL the rows from a table. ............................................................................................................. 84
A select set of rows from a table. ................................................................................................... 84
Updating all rows............................................................................................................................... 84
Updating Records Conditionally ......................................................................................................... 85
MODIFYING THE STRUCTURE OF TABLES............................................................................................ 86
Restrictions on the ALTER TABLE........................................................................................................ 86
ALTER TABLE Command can perform..................................................................................................... 86
Adding New Columns......................................................................................................................... 87
Dropping A Column from a Table. ...................................................................................................... 87
By Anand Harsha 5
RENAMING TABLES................................................................................................................................ 88
TRUNCATING TABLES............................................................................................................................. 89
DESTROYING TABLES ............................................................................................................................. 89
COMMIT and ROLLBACK ........................................................................................................................ 90
Commit ............................................................................................................................................. 90
Rollback............................................................................................................................................. 90
Difference between DELETE and DROP. ................................................................................................. 90
Difference between DELETE and TRUNCATE. ......................................................................................... 90
Difference between CHAR and VARCHAR............................................................................................... 91
CHAR ............................................................................................................................................. 91
VARCHAR....................................................................................................................................... 91
DATA CONSTRINTS ................................................................................................................................ 91
Primary Key Constraint ...................................................................................................................... 92
Foreign Key Constraint....................................................................................................................... 92
Unique Key Constraint ....................................................................................................................... 92
CHECK Constraint .............................................................................................................................. 93
NOT NULL Constraint ......................................................................................................................... 93
Arithmetic Operators............................................................................................................................. 93
Range Searching (BETWEEN) ................................................................................................................. 98
LIKE ................................................................................................................................................... 98
IN ...................................................................................................................................................... 99
NOT IN............................................................................................................................................. 100
Column Aliases(Renaming Columns) in Oracle: .................................................................................... 100
to add column aliases to your sql queries. ....................................................................................... 100
ORACLE FUNCTIONS ............................................................................................................................ 100
a) SQL Aggregate / Group Functions ................................................................................................ 101
b) SQL String Functions .................................................................................................................... 103
Date Conversion Functions .............................................................................................................. 106
SET OPERATORS and JOINS .................................................................................................................. 107
Union Clause ................................................................................................................................... 109
Intersect Clause ............................................................................................................................... 110
Minus Clause ................................................................................................................................... 111
By Anand Harsha 6
JOINS................................................................................................................................................... 112
INNER Join ....................................................................................................................................... 114
OUTER Join ...................................................................................................................................... 114
OUTER JOIN : ................................................................................................................................... 115
CROSS Join....................................................................................................................................... 116
INNER JOIN: ..................................................................................................................................... 117
LEFT JOIN: .................................................................................................................................... 117
RIGHT JOIN: ................................................................................................................................. 117
FULL JOIN: ................................................................................................................................... 117
CARTESIAN JOIN: ......................................................................................................................... 117
Unit - V ................................................................................................................................................ 118
Introduction to PL/SQL ........................................................................................................................ 118
Features of PL/SQL .......................................................................................................................... 118
Advantages of PL/SQL ...................................................................................................................... 118
PL/SQL Block Structure ....................................................................................................................... 119
The 'Hello World' Example ........................................................................................................... 120
The PL/SQL Identifiers ................................................................................................................. 120
The PL/SQL Delimiters................................................................................................................. 120
The PL/SQL Comments ............................................................................................................... 122
PL/SQL Program Units ................................................................................................................. 122
Data Types .......................................................................................................................................... 123
PL/SQL Scalar Data Types and Subtypes ................................................................................. 123
PL/SQL Numeric Data Types and Subtypes .............................................................................. 124
PL/SQL Character Data Types and Subtypes............................................................................ 126
PL/SQL Boolean Data Types....................................................................................................... 127
PL/SQL Datetime and Interval Types.......................................................................................... 127
PL/SQL Large Object (LOB) Data Types.................................................................................... 128
NULLs in PL/SQL.......................................................................................................................... 129
PL/SQL Variables ................................................................................................................................. 129
Variable Declaration in PL/SQL ................................................................................................... 129
Initializing Variables in PL/SQL ................................................................................................... 130
Variable Scope in PL/SQL ........................................................................................................... 131
By Anand Harsha 7
Assigning SQL Query Results to PL/SQL Variables.................................................................. 131
PL/SQL Constants and Literals ............................................................................................................. 133
Declaring a Constant .................................................................................................................... 133
The PL/SQL Literals ..................................................................................................................... 134
PL/SQL Operators ................................................................................................................................ 135
Arithmetic Operators..................................................................................................................... 135
Relational Operators..................................................................................................................... 136
Comparison Operators ................................................................................................................. 137
Logical Operators.......................................................................................................................... 137
PL/SQL Operator Precedence ..................................................................................................... 138
PL/SQL conditions................................................................................................................................ 139
PL/SQL Loops....................................................................................................................................... 141
Labeling a PL/SQL Loop .................................................................................................................... 142
The Loop Control Statements .......................................................................................................... 143
PL/SQL Strings ..................................................................................................................................... 143
Declaring String Variables............................................................................................................ 144
PL/SQL String Functions and Operators .................................................................................... 145
Example 1 .................................................................................................................................... 147
Example 2 .................................................................................................................................... 148
PL/SQL Arrays ...................................................................................................................................... 149
Creating a Varray Type..................................................................................................................... 149
Example 1 .................................................................................................................................... 150
Example 2 .................................................................................................................................... 151
PL/SQL PROCEDURES ........................................................................................................................... 152
Parts of a PL/SQL Subprogram ................................................................................................... 152
Creating a Procedure ................................................................................................................... 153
Example....................................................................................................................................... 153
Executing a Standalone Procedure ............................................................................................. 154
Deleting a Standalone Procedure ............................................................................................... 154
Parameter Modes in PL/SQL Subprograms ............................................................................... 154
IN & OUT Mode Example 1 .......................................................................................................... 155
IN & OUT Mode Example 2 .......................................................................................................... 156
By Anand Harsha 8
Methods for Passing Parameters ................................................................................................ 156
Positional Notation ...................................................................................................................... 156
Named Notation .......................................................................................................................... 157
Mixed Notation............................................................................................................................ 157
PL/SQL FUNCTIONS ............................................................................................................................. 157
Creating a Function.......................................................................................................................... 157
Example....................................................................................................................................... 158
Calling a Function ............................................................................................................................ 158
Example....................................................................................................................................... 159
PL/SQL Recursive Functions ............................................................................................................. 160
PL/SQL Cursors .................................................................................................................................... 161
Implicit Cursors ............................................................................................................................. 161
Example....................................................................................................................................... 162
Explicit Cursors ................................................................................................................................ 163
Declaring the Cursor..................................................................................................................... 163
Opening the Cursor ...................................................................................................................... 163
Fetching the Cursor ...................................................................................................................... 164
Closing the Cursor ........................................................................................................................ 164
Example....................................................................................................................................... 164
PL/SQL Exceptions ............................................................................................................................... 165
Syntax for Exception Handling ......................................................................................................... 165
Example....................................................................................................................................... 165
Raising Exceptions ........................................................................................................................... 166
User-defined Exceptions .................................................................................................................. 166
Example....................................................................................................................................... 166
Pre-defined Exceptions .................................................................................................................... 167
PL/SQL Triggers ................................................................................................................................... 169
Benefits of Triggers ...................................................................................................................... 169
Creating Triggers ............................................................................................................................. 170
Example....................................................................................................................................... 171
Triggering a Trigger.......................................................................................................................... 172
PL/SQL Package ................................................................................................................................... 172
By Anand Harsha 9
Package Specification ...................................................................................................................... 172
Package Body .................................................................................................................................. 173
Using the Package Elements ............................................................................................................ 173
Example....................................................................................................................................... 174
The Package Specification ............................................................................................................ 174
Creating the Package Body........................................................................................................... 175
Using The Package ....................................................................................................................... 175
PL/SQL Transactions ............................................................................................................................ 176
Starting and Ending a Transaction .................................................................................................... 176
Committing a Transaction ................................................................................................................ 177
Rolling Back Transactions................................................................................................................. 178
Savepoints ................................................................................................................................... 178
Automatic Transaction Control ........................................................................................................ 179
PL/SQL Date and Time ......................................................................................................................... 179
Field Values for Datetime and Interval Data Types ........................................................................... 179
The Datetime Data Types and Functions .......................................................................................... 180
DATE............................................................................................................................................ 180
TIMESTAMP ................................................................................................................................. 180
TIMESTAMP WITH TIME ZONE ..................................................................................................... 181
TIMESTAMP WITH LOCAL TIME ZONE .......................................................................................... 181
Examples ..................................................................................................................................... 183
The Interval Data Types and Functions............................................................................................. 183
Interval Functions ........................................................................................................................ 183
References .......................................................................................................................................... 185
Question Paper ................................................................................................................................... 186
Assignments to Students ..................................................................................................................... 188
By Anand Harsha 10
Unit-I
DATA:
Data is a collection of facts, figures and statistics related to an object. For example: Students fill an
admission form when they get admission in college. The form consists of raw facts about the students.
These raw facts are student's name, father name, address etc. The purpose of collecting this data is to
maintain the records of the students during their study period in the college.
INFORMATION:
Processed data is called information. OR The manipulated and processed form of data is called
information. For example: Data collected from census is used to generate different type of information.
The government can use it to determine the literacy rate in the country. Government can use the
information in important decision to improve literacy rate.
1. Improved data sharing: The DBMS helps create an environment in which end users have better access
to more and better-managed data. Such access makes it possible for end users to respond quickly to
changes in their environment.
2. Improved data security: The more users access the data, the greater the risks of data security
breaches. Corporations invest considerable amounts of time, effort, and money to ensure that
corporate data are used properly. A DBMS provides a framework for better enforcement of data privacy
and security policies.
3. Data integration: Wider access to well-managed data promotes an integrated view of the
organization’s operations and a clearer view of the big picture. It becomes much easier to see how
actions in one segment of the company affect other segments.
By Anand Harsha 11
4. Minimized data inconsistency: Data inconsistency exists when different versions of the same data
appear in different places. For example, data inconsistency exists when a company’s sales department
stores a sales representative’s name as “Bill Brown” and the company’s personnel department stores
that same person’s name as “William G. Brown,” or when the company’s regional sales office shows the
price of a product as $45.95 and its national sales office shows the same product’s price as $43.95. The
probability of data inconsistency is greatly reduced in a properly designed database.
5. Improved data access: The DBMS makes it possible to produce quick answers to ad hoc queries. From
a database perspective, a query is a specific request issued to the DBMS for data manipulation—for
example, to read or update the data. Simply put, a query is a question, and an ad hoc query is a spur-of-
the-moment question. The DBMS sends back an answer (called the query result set) to the application.
For example, end users, when dealing with large amounts of sales data, might want quick answers to
questions (ad hoc queries) such as: - What was the dollar volume of sales by product during the past six
months? - What is the sales bonus figure for each of our salespeople during the past three months? -
How many of our customers have credit balances of $3,000 or more?
6. Improved decision making: Better-managed data and improved data access make it possible to
generate better-quality information, on which better decisions are based. The quality of the information
generated depends on the quality of the underlying data. Data quality is a comprehensive approach to
promoting the accuracy, validity, and timeliness of the data. While the DBMS does not guarantee data
quality, it provides a framework to facilitate data quality
7. Increased end-user productivity: The availability of data, combined with the tools that transform data
into usable information, empowers end users to make quick, informed decisions that can make the
difference between success and failure in the global economy.
8. Controlling Data Redundancy: In non-database systems (traditional computer file processing), each
application program has its own files. In this case, the duplicated copies of the same data are created at
many places. In DBMS, all the data of an organization is integrated into a single database. The data is
recorded at only one place in the database and it is not duplicated. For example, the dean's faculty file
and the faculty payroll file contain several items that are identical. When they are converted into
database, the data is integrated into a single database so that multiple copies of the same data are
reduced to-single copy. In DBMS, the data redundancy can be controlled or reduced but is not removed
completely. Sometimes, it is necessary to create duplicate copies of the same data items in order to
relate tables with each other. By controlling the data redundancy, you can save storage space. Similarly,
it is useful for retrieving data from database using queries.
9. Backup and Recovery Procedures: In a computer file-based system, the user creates the backup of
data regularly to protect the valuable data from damaging due to failures to the computer system or
application program. It is a time consuming method, if volume of data is large. Most of the DBMSs
provide the 'backup and recovery' sub-systems that automatically create the backup of data and restore
data if required. For example, if the computer system fails in the middle (or end) of an update operation
By Anand Harsha 12
of the program, the recovery sub-system is responsible for making sure that the database is restored to
the state it was in before the program started executing.
DISADVANTAGES OF DATABASE
1. Increased costs: Database systems require sophisticated hardware and software and highly skilled
personnel. The cost of maintaining the hardware, software, and personnel required to operate and
manage a database system can be substantial. Training, licensing, and regulation compliance costs are
often overlooked when database systems are implemented.
2. Management complexity: Database systems interface with many different technologies and have a
significant impact on a company’s resources and culture. The changes introduced by the adoption of a
database system must be properly managed to ensure that they help advance the company’s objectives.
Given the fact that database systems hold crucial company data that are accessed from multiple
sources, security issues must be assessed constantly.
3. Maintaining currency: To maximize the efficiency of the database system, you must keep your system
current. Therefore, you must perform frequent updates and apply the latest patches and security
measures to all components. Because database technology advances rapidly, personnel training costs
tend to be significant. Vendor dependence. Given the heavy investment in technology and personnel
training, companies might be reluctant to change database vendors. As a consequence, vendors are less
likely to offer pricing point advantages to existing customers, and those customers might be limited in
their choice of database system components.
4. Frequent upgrade/replacement cycles: DBMS vendors frequently upgrade their products by adding
new functionality. Such new features often come bundled in new upgrade versions of the software.
Some of these versions require hardware upgrades. Not only do the upgrades themselves cost money,
but it also costs money to train database users and administrators to properly use and manage the new
features.
5. Appointing Technical Staff: The trained technical persons such as database administrator and
application programmers etc are required to handle the DBMS. You have to pay handsome salaries to
these persons. Therefore, the system cost increases.
Data abstraction
Database systems are made-up of complex data structures. To ease the user interaction with database,
the developers hide internal irrelevant details from users. This process of hiding irrelevant details from
user is called data abstraction.
By Anand Harsha 13
We have three levels of abstraction:
Physical level: This is the lowest level of data abstraction. It describes how data is actually stored
in database. You can get the complex data structure details at this level.
Logical level: This is the middle level of 3-level data abstraction architecture. It describes what data
is stored in database.
View level: Highest level of data abstraction. This level describes the user interaction with database
system.
Example: Let’s say we are storing customer information in a customer table. At physical level these
records can be described as blocks of storage (bytes, gigabytes, terabytes etc.) in memory. These details
are often hidden from the programmers.
At the logical level these records can be described as fields and attributes along with their data types,
their relationship among each other can be logically implemented. The programmers generally work at
this level because they are aware of such things about database systems.
At view level, user just interact with system with the help of GUI and enter the details at the screen,
they are not aware of how the data is stored and what data is stored; such details are hidden from
them.
By Anand Harsha 14
Data model
Data Model gives us an idea that how the final system will look like after its complete implementation. It
defines the data elements and the relationships between the data elements. Data Models are used to
show how data is stored, connected, accessed and updated in the database management system. Here,
we use a set of symbols and text to represent the information so that members of the organisation can
communicate and understand it. Though there are many data models being used nowadays but the
Relational model is the most widely used model. Apart from the Relational model, there are many other
types of data models about which we will study in details in this blog. Some of the Data Models in DBMS
are:
1. Hierarchical Model
2. Network Model
3. Entity-Relationship Model
4. Relational Model
Hierarchical Model
Hierarchical Model was the first DBMS model. This model organizes the data in the hierarchical tree
structure. The hierarchy starts from the root which has root data and then it expands in the form of a
tree adding child node to the parent node. This model easily represents some of the real-world
relationships like food recipes, sitemap of a website etc. Example: We can represent the relationship
between the shoes present on a shopping website in the following way:
By Anand Harsha 15
Features of a Hierarchical Model
1. One-to-many relationship: The data here is organized in a tree-like structure where the one-to-
many relationship is between the data types. Also, there can be only one path from parent to
any node. Example: In the above example, if we want to go to the node sneakers we only have
one path to reach there i.e. through men's shoes node.
2. Parent-Child Relationship: Each child node has a parent node but a parent node can have more
than one child node. Multiple parents are not allowed.
3. Deletion Problem: If a parent node is deleted then the child node is automatically deleted.
4. Pointers: Pointers are used to link the parent node with the child node and are used to navigate
between the stored data. Example: In the above example the 'shoes' node points to the two
other nodes 'women shoes' node and 'men's shoes' node.
Network Model
This model is an extension of the hierarchical model. It was the most popular model before the
relational model. This model is the same as the hierarchical model, the only difference is that a record
can have more than one parent. It replaces the hierarchical tree with a graph. Example: In the example
below we can see that node student has two parents i.e. CSE Department and Library. This was earlier
not possible in the hierarchical model.
By Anand Harsha 16
Features of a Network Model
1. Ability to Merge more Relationships: In this model, as there are more relationships so data is
more related. This model has the ability to manage one-to-one relationships as well as many-to-
many relationships.
2. Many paths: As there are more relationships so there can be more than one path to the same
record. This makes data access fast and simple.
3. Circular Linked List: The operations on the network model are done with the help of the circular
linked list. The current position is maintained with the help of a program and this position
navigates through the records according to the relationship.
The data can be accessed faster as compared to the hierarchical model. This is because the
data is more related in the network model and there can be more than one path to reach a
particular node. So the data can be accessed in many ways.
As there is a parent-child relationship so data integrity is present. Any change in parent record
is reflected in the child record.
By Anand Harsha 17
Disadvantages of Network Model
As more and more relationships need to be handled the system might get complex. So, a user
must be having detailed knowledge of the model to work with the model.
Any change like updation, deletion, insertion is very complex.
Entity-Relationship Model
Entity-Relationship Model or simply ER Model is a high-level data model diagram. In this model, we
represent the real-world problem in the pictorial form to make it easy for the stakeholders to
understand. It is also very easy for the developers to understand the system by just looking at the ER
diagram. We use the ER diagram as a visual tool to represent an ER Model. ER diagram has the
following three components:
By Anand Harsha 18
In the above diagram, the entities are Teacher and Department. The attributes of Teacher entity are
Teacher_Name, Teacher_id, Age, Salary, Mobile_Number. The attributes of entity Department entity
are Dept_id, Dept_name. The two entities are connected using the relationship. Here, each teacher
works for a department.
Features of ER Model
Graphical Representation for Better Understanding: It is very easy and simple to understand
so it can be used by the developers to communicate with the stakeholders.
ER Diagram: ER diagram is used as a visual tool for representing the model.
Database Design: This model helps the database designers to build the database and is widely
used in database design.
Advantages of ER Model
Simple: Conceptually ER Model is very easy to build. If we know the relationship between the
attributes and the entities we can easily build the ER Diagram for the model.
Effective Communication Tool: This model is used widely by the database designers for
communicating their ideas.
Easy Conversion to any Model: This model maps well to the relational model and can be easily
converted relational model by converting the ER model to the table. This model can also be
converted to any other model like network model, hierarchical model etc.
Disadvantages of ER Model
No industry standard for notation: There is no industry standard for developing an ER model.
So one developer might use notations which are not understood by other developers.
Hidden information: Some information might be lost or hidden in the ER model. As it is a high-
level view so there are chances that some details of information might be hidden.
Relational Model
Relational Model is the most widely used model. In this model, the data is maintained in the form of a
two-dimensional table. All the information is stored in the form of row and columns. The basic
structure of a relational model is tables. So, the tables are also called relations in the relational
model. Example: In this example, we have an Employee table.
By Anand Harsha 19
Features of Relational Model
Tuples: Each row in the table is called tuple. A row contains all the information about any
instance of the object. In the above example, each row has all the information about any
specific individual like the first row has information about John.
Attribute or field: Attributes are the property which defines the table or relation. The values
of the attribute should be from the same domain. In the above example, we have different
attributes of the employee like Salary, Mobile_no, etc.
Simple: This model is more simple as compared to the network and hierarchical model.
Scalable: This model can be easily scaled as we can add as many rows and columns we want.
Structural Independence: We can make changes in database structure without changing the
way to access the data. When we can make changes to the database structure without
affecting the capability to DBMS to access the data we can say that structural independence
has been achieved.
Hardware Overheads: For hiding the complexities and making things easier for the user this
model requires more powerful hardware computers and data storage devices.
Bad Design: As the relational model is very easy to design and use. So the users don't need to
know how the data is stored in order to access it. This ease of design can lead to the
development of a poor database which would slow down if the database grows.
But all these disadvantages are minor as compared to the advantages of the relational model. These
problems can be avoided with the help of proper implementation and organization.
By Anand Harsha 20
Data Independence
A database system normally contains a lot of data in addition to users’ data. For example, it stores data
about data, known as metadata, to locate and retrieve data easily. It is rather difficult to modify or
update a set of metadata once it is stored in the database. But as a DBMS expands, it needs to change
over time to satisfy the requirements of the users. If the entire data is dependent, it would become a
tedious and highly complex job.
Metadata itself follows a layered architecture, so that when we change data at one layer, it does not
affect the data at another level. This data is independent but mapped to each other.
By Anand Harsha 21
Data definition language
DDL(Data Definition Language) : DDL or Data Definition Language actually consists of the SQL
commands that can be used to define the database schema. It simply deals with descriptions of the
database schema and is used to create and modify the structure of database objects in the database.
Examples of DML:
INSERT – is used to insert data into a table.
UPDATE – is used to update existing data within a table.
DELETE – is used to delete records from a database table.
DATABASE ADMINISTRATOR
the people responsible for managing databases are called database administrators. Each database
administrator, dubbed DBA for the sake of brevity may be engaged in performing various database
manipulation tasks such as archiving, testing, running, security control etc. all related to the
environmental side of the databases.
1. Designing the logical and physical schemas, as well as widely-used portions of the external schema.
4. Database tuning: The DBA is responsible for evolving the database, in particular the conceptual and
physical schemas to ensure adequate performance as user requirements change.
By Anand Harsha 22
USERS IN DBMS
Users are of 4 types:
2. End users
4. System Analyst
1. Application programmers
or Ordinary users: These users write application programs to interact with the database. Application
programs can be written in some programming language such a COBOL, PL/I, C++, JAVA or some higher
level fourth generation language. Such programs access the database by issuing the appropriate
request, typically a SQL statement to DBMS.
2. End Users:
End users are the users, who use the applications developed. End users need not know about the
working, database design, the access mechanism etc. They just use the system to get their task done.
End users are of two types:
a) Direct users
b) Indirect users
a) Direct users: Direct users are the users who se the computer, database system directly, by following
instructions provided in the user interface. They interact using the application programs already
developed, for getting the desired result. E.g. People at railway reservation counters, who directly
interact with database.
b) Indirect users: Indirect users are those users, who desire benefit form the work of DBMS indirectly.
They use the outputs generated by the programs, for decision making or any other purpose. They are
just concerned with the output and are not bothered about the programming part.
Database Administrator (DBA) is the person which makes the strategic and policy decisions regarding
the data of the enterprise, and who provide the necessary technical support for implementing these
decisions. Therefore, DBA is responsible for overall control of the system at a technical level. In database
environment, the primary resource is the database itself and the secondary resource is the DBMS and
related software administering these resources is the responsibility of the Database Administrator
(DBA).
By Anand Harsha 23
4. System Analyst:
System Analyst determines the requirement of end users, especially naive and parametric end users
and develops specifications for transactions that meet these requirements. System Analyst plays a major
role in database design, its properties; the structure prepares the system requirement statement, which
involves the feasibility aspect, economic aspect, technical aspect etc. of the system.
Overall structure
By Anand Harsha 24
Internal level:
It is the lowest level of data abstraction that deals with the physical representation of the database on
the computer and thus, is also known as physical level. It describes how the data is physically stored and
organized on the storage medium. At this level, various aspects are considered to achieve optimal
runtime performance and storage space utilization. These aspects include storage space allocation
techniques for data and indexes, access paths such as indexes, data compression and encryption
techniques, and record placement.
Conceptual level:
This level of abstraction deals with the logical structure of the entire database and it is also known as
logical level. It describes what data is stored in the database, the relationships among the data and
complete view of the user’s requirements without any concern for the physical implementation. It hides
the complexity of physical storage structures. The conceptual view is the overall view of the database
and it includes all the information that is going to be represented in the database.
External level:
It is the highest level of abstraction that deals with the user’s view of the database and it is also known
as view level. Most of the users and application programs do not require the entire data stored in the
database. The external level describes a part of the database for a particular group of users. It permits
By Anand Harsha 25
users to access data in a way that is customized according to their needs, so that the same data can be
seen by different users in different ways at the same time. It provides a powerful and flexible security
mechanism by hiding the parts of the database from certain users, as the user is not aware of existence
of any attributes that are missing from the view.
File system is a collection of data. Any DBMS is a collection of data and user is
management with the file system, user has to not required to write the procedures for
write the procedures. managing the database.
File system gives the details of the data DBMS provides an abstract view of data
representation and Storage of data. that hides the details.
By Anand Harsha 26
Concurrent access to the data in the file
system has many problems like : Reading the DBMS takes care of Concurrent access
file while other form of locking. deleting some using some form of locking.
information, updating some information
SCHEMA
A schema is a collection of named objects. Schemas are generally stored in a data dictionary. Although a
schema is defined in text database language, the term is often used to refer to a graphical depiction of
the database structure. In relational database technology, schemas provide a logical classification of
objects in the database. Some of the objects that a schema may contain include tables, views, aliases,
indexes, triggers, and structured types.
INSTANCES
The data in the database at a particular moment of time is called an instance or a database state. In a
given instance, each schema construct has its own current set of instances. Many instances or database
states can be constructed to correspond to a particular database schema. Every time we update (i.e.,
insert, delete or modify) the value of a data item in a record, one state of the database changes into
another state. The following figure shows an instance of the ITEM relation in a database schema.
By Anand Harsha 27
ENTITY RELATIONSHIP MODEL & BASIC CONCEPTS:
It is a semantic data model that is used for the graphical representation of the conceptual database
design. Entity relationship model defines the conceptual view of database. It works around real world
entity and association among them. At view level, ER model is considered well for designing databases.
The Entity Relationship (ER) model consists of different types of entities. The existence of an entity may
depends on the existence of one or more other entities, such an entity is said to be existence
dependent. Entities whose existence not depending on any other entities is termed as not existence
dependent. Entities based on their characteristics are classified as follows.
ENTITY:
A real-world thing either animate or inanimate that can be easily identifiable and distinguishable, called
entity. Entities are represented by means of rectangles. Rectangles are named with the entity set they
represent.
TYPES OF ENTITY:
Strong entity: An entity set that has a primary key is called as Strong entity set. Strong entity
represented by rectangle which is shown below.
Weak entity: An entity set that does not have sufficient attributes to form a primary key is termed as a
weak entity set. Weak entity represented by double rectangle which is shown below.
ATRIBUTE:
By Anand Harsha 28
Attributes are properties of entities. Attributes are represented by means of ellipse. Every ellipse
represents one attribute and is directly connected to its entity (rectangle). For example the employee is
the entity and employee’s name, age, address, salary and job etc are the attribute. Attribute is
represented by ellipse.
TYPES OF ATTRIBUTES:
Simple attribute:
Simple attribute consists of a single atomic value. A simple attribute cannot be subdivided. For example
the attributes age, sex etc is simple attributes. Composite attribute: A composite attribute is an attribute
that can be further subdivided. For example the attribute ADDRESS can be subdivided into street, city,
state, and zip code.
Single-valued attribute:
A single valued attribute can have only a single value. For example a person can have only one 'date of
birth', 'age' etc. That is a single valued attributes can have only single value. But it can be simple or
composite attribute. That is 'date of birth' is a composite attribute; 'age' is a simple attribute. But both
are single valued attributes.
Multi-value attributes:
Multivalve attributes can have multiple values. For instance a person may have multiple phone
numbers, multiple degrees etc. Multivalve attributes are shown by a double line connecting to the entity
in the ER diagram.
Stored attribute:
By Anand Harsha 29
The value for the derived attribute is derived from the stored attribute. For example 'Date of birth' of a
person is a stored attribute. The value for the attribute 'AGE' can be derived by subtracting the 'Date of
Birth'(DOB) from the current date. Stored attribute supplies a value to the related attribute.
Derived attribute:
An attribute that’s value is derived from a stored attribute. Example: age, and it’s value is derived from
the stored attribute Date of Birth. It is represented by dotted ellipse.
RELATIONSHIP:
The association among entities is called relationship. For example, employee entity has relation
works_at with department. Another example is for student who enrolls in some course. Works_at and
Enrolls are called relationship. Relationship is represented by diamond box.
Example: Student (entity type) is related to Department (entity type) by MajorsIn (relationship type).
By Anand Harsha 30
One-to-One:
Only one entity of the first set is related to only one entity of the second set. Example A teacher teaches
a student. Only one teacher is teaching only one student.
One-to-Many:
Only one entity of the first set is related to multiple entities of the second set. Example A teacher
teaches students. Only one teacher is teaching many students.
Many-to-One:
Multiple entities of the first set are related to multiple entities of the second set. Example Teachers
teach a student. Many teachers are teaching only one student.
Many-to-Many:
Multiple entities of the first set is related to multiple entities of the second set. Example 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.
KEYS:
A key is an attribute of a table which helps to identify a row. There can be many different types of keys:
Super Key or Candidate Key:
It is such an attribute of a table that can uniquely identify a row in a table. Generally they contain
unique values and can never contain NULL values. There can be more than one super key or candidate
By Anand Harsha 31
key in a table Example within a STUDENT table Roll and Mobile No. can both serve to uniquely identify a
student.
Primary Key:
It is one of the candidate keys that are chosen to be the identifying key for the entire table. Example
although there are two candidate keys in the STUDENT table, the college would obviously use Roll as the
primary key of the table.
Alternate Key:
This is t1he candidate key which is not chosen as the primary key of the table. They are named so
because although not the primary key, they can still identify a row.
Composite Key:
Sometimes one key is not enough to uniquely identify a row. Example in a single class Roll is enough to
find a student but in the entire school merely searching by the Roll is not enough because there could be
10 classes in the school and each one of them may contain a certain roll no 5. To uniquely identify the
student we have to say something like “class VII, roll no 5”. So a combination of two or more attributes
is combined to create a unique combination of values such as Class + Roll.
Foreign Key:
Sometimes we may have to work with an attribute that does not have a primary key of its own. To
identify its rows, we have to use the primary attribute of a related table. Such a copy of another related
table’s primary key is called foreign key
Unit-II
A real-world thing either animate or inanimate that can be easily identifiable and distinguishable.
Attributes:
By Anand Harsha 32
Relationships:
1. Determine the purpose of the database - This helps prepare for the remaining steps.
2. Find and organize the information required - Gather all of the types of information to record in the
database, such as product name and order number.
3. Divide the information into tables - Divide information items into major entities or subjects, such as
Products or Orders. Each subject then becomes a table.
4. Turn information items into columns - Decide what information needs to be stored in each table.
Each item becomes a field, and is displayed as a column in the table. For example, an Employees table
might include fields such as Last Name and Hire Date.
5. Specify primary keys - Choose each table’s primary key. The primary key is a column, or a set of
columns, that is used to uniquely identify each row. An example might be Product ID or Order ID.
6. Set up the table relationships - Look at each table and decide how the data in one table is related to
the data in other tables. Add fields to tables or create new tables to clarify the relationships, as
necessary.
By Anand Harsha 33
7. Refine the design - Analyze the design for errors. Create tables and add a few records of sample data.
Check if results come from the tables as expected. Make adjustments to the design, as needed. 8. Apply
the normalization rules - Apply the data normalization rules to see if tables are structured correctly.
Make adjustments to the tables
1. Strong Entity Sets: It is common practice for the table to have the same name as the entity set. There
is one column for each attribute.
2. Weak Entity Sets: There is one column for each attribute, plus the attribute(s) the form the primary
key of the strong entity set that the weak entity set depends upon.
3. Relationship Sets: We represent a relationship with a table that includes the attributes of each of the
primary keys plus any descriptive attributes (if any). There is a problem that if one of the entities in the
relationship is a weak entity set. There would be no unique information in the relationship table and
therefore may be omitted. Another problem can occur if there is an existence dependency. In that case
you can combine the two tables.
4. Multivalve Attributes: When an attribute is multivalve, remove the attribute from the table and
create a new table with the primary key and the attribute, but each value will be a separate row.
5. Generalization: Create a table for the higher-level entity set. For each lower-level entity set, create a
table with the attributes for that specialization and include the primary key from the higher-level entity
set.
By Anand Harsha 34
Reduce (convert) the following ER diagram to relational schema
By Anand Harsha 36
Student_ID is the foreign key refers STUDENT table
By Anand Harsha 37
Generalization, Specialization and Aggregation in ER Model
Prerequisite
– Introduction of ER Model
Generalization, Specialization and Aggregation in ER model are used for data abstraction in which
abstraction mechanism is used to hide details of a set of objects.
Generalization
Generalization is the process of extracting common properties from a set of entities and create a
generalized entity from it. It is a bottom-up approach in which two or more entities can be generalized
to a higher level entity if they have some attributes in common. For Example, STUDENT and FACULTY
can be generalized to a higher level entity called PERSON as shown in Figure 1. In this case, common
attributes like P_NAME, P_ADD become part of higher entity (PERSON) and specialized attributes like
S_FEE become part of specialized entity (STUDENT).
By Anand Harsha 38
Specialization
In specialization, an entity is divided into sub-entities based on their characteristics. It is a top-down
approach where higher level entity is specialized into two or more lower level entities. For Example,
EMPLOYEE entity in an Employee management system can be specialized into DEVELOPER, TESTER etc.
as shown in Figure 2. In this case, common attributes like E_NAME, E_SAL etc. become part of higher
entity (EMPLOYEE) and specialized attributes like TES_TYPE become part of specialized entity (TESTER).
By Anand Harsha 39
Aggregation
An ER diagram is not capable of representing relationship between an entity and a relationship which
may be required in some scenarios. In those cases, a relationship with its corresponding entities is
aggregated into a higher level entity. For Example, Employee working for a project may require some
machinery. So, REQUIRE relationship is needed between relationship WORKS_FOR and entity
MACHINERY. Using aggregation, WORKS_FOR relationship with its entities EMPLOYEE and PROJECT is
aggregated into single entity and relationship REQUIRE is created between aggregated entity and
MACHINERY.
By Anand Harsha 40
Unit IIIrd
Oracle Architecture
Oracle server: An Oracle server includes an Oracle Instance and an Oracle database.
· An Oracle database includes several different types of files: datafiles, control files, redo log files and
archive redo log files. The Oracle server also accesses parameter files and password files.
o Still another is to ensure the database can be recovered if there is a software/hardware failure.
· The database server must manage large amounts of data in a multi-user environment.
· The server must deliver high performance. This generally means fast response times.
Oracle instance:
By Anand Harsha 41
· The first component set is the set of background processes (PMON, SMON, RECO, DBW0, LGWR, CKPT,
D000 and others).
o These will be covered later in detail – each background process is a computer program.
o These processes perform input/output and monitor other Oracle processes to provide good performance
and database reliability.
· The second component set includes the memory structures that comprise the Oracle instance.
o When an instance starts up, a memory structure called the System Global Area (SGA) is allocated.
· An Oracle Instance provides access to one and only one Oracle database.
Oracle database:
An Oracle database consists of files.
· Sometimes these are referred to as operating system files, but they are actually database files that
store the database information that a firm or organization needs in order to operate.
· The redo log files are used to recover the database in the event of application program failures,
instance failures and other minor failures.
· The archived redo log files are used to recover the database if a disk fails.
· Other files not shown in the figure include:
o The required parameter file that is used to specify parameters for configuring an Oracle instance when it
starts up.
o The optional password file authenticates special users of the database – these are termed privileged
users and include database administrators.
o Alert and Trace Log Files – these files store information about errors and actions taken that affect the
configuration of the database.
This figure from the Oracle Database Administration Guide provides another way of viewing the SGA.
By Anand Harsha 42
Connecting to an Oracle Instance – Creating a Session
By Anand Harsha 43
System users can connect to an Oracle database through SQLPlus or through an application program like
the Internet Developer Suite (the program becomes the system user). This connection enables users to
execute SQL statements.
The act of connecting creates a communication pathway between a user process and an Oracle
Server. As is shown in the figure above, the User Process communicates with the Oracle Server through
a Server Process. The User Process executes on the client computer. The Server Process executes on
the server computer, and actually executes SQL statements submitted by the system user.
The figure shows a one-to-one correspondence between the User and Server Processes. This is called
a Dedicated Server connection. An alternative configuration is to use a Shared Server where more than
one User Process shares a Server Process.
Sessions: When a user connects to an Oracle server, this is termed a session. The User Global Area is
session memory and these memory structures are described later in this document. The session starts
when the Oracle server validates the user for connection. The session ends when the user logs out
(disconnects) or if the connection terminates abnormally (network failure or client computer failure).
A user can typically have more than one concurrent session, e.g., the user may connect using SQLPlus
and also connect using Internet Developer Suite tools at the same time. The limit of concurrent session
connections is controlled by the DBA.
If a system users attempts to connect and the Oracle Server is not running, the system user receives
the Oracle Not Available error message.
As was noted above, an Oracle database consists of physical files. The database itself has:
· Datafiles – these contain the organization's actual data.
· Redo log files – these contain a chronological record of changes made to the database, and enable
recovery when failures occur.
By Anand Harsha 44
· Control files – these are used to synchronize all database activities and are covered in more detail in a
later module.
o The init.ora file (also called the PFILE) is a static parameter file. It contains parameters that specify how
the database instance is to start up. For example, some parameters will specify how to allocate memory
to the various parts of the system global area.
o The spfile.ora is a dynamic parameter file. It also stores parameters to specify how to startup a
database; however, its parameters can be modified while the database is running.
· Password file – specifies which *special* users are authenticated to startup/shut down an Oracle
Instance.
· Archived redo log files – these are copies of the redo log files and are necessary for recovery in an
online, transaction-processing environment in the event of a disk failure.
By Anand Harsha 45
Oracle Database Memory Management
· These values are stored in the init.ora file for each database.
o Database redistributes memory as needed between the SGA and the instance PGA.
o DBA can optionally set an aggregate target size for the PGA or managing PGA work areas individually.
o Instead of setting the total memory size, the DBA sets many initialization parameters to manage
components of the SGA and instance PGA individually.
If you create a database with Database Configuration Assistant (DBCA) and choose the basic installation
option, then automatic memory management is the default.
· System Global Area (SGA) – this is allocated when an Oracle Instance starts up.
· Program Global Area (PGA) – this is allocated when a Server Process starts up.
By Anand Harsha 46
· User Global Area (UGA) – this is allocated when a user connects to create a session.
The SGA is a read/write memory area that stores information shared by all database processes and by
all users of the database (sometimes it is called the Shared Global Area).
o This information includes both organizational data and control information used by the Oracle Server.
o The size of the SGA can be established by a DBA by assigning a value to the parameter SGA_MAX_SIZE in
the parameter file—this is an optional parameter.
The SGA is allocated when an Oracle instance (database) is started up based on values specified in the
initialization parameter file (either PFILE or SPFILE).
· Java Pool
· Streams Pool
o Library Cache
· Other structures (for example, lock and latch management, statistical data)
· Large Pool
By Anand Harsha 47
The SHOW SGA SQL command will show you the SGA memory allocations.
· This is a recent clip of the SGA for the DBORCL database at SIUE.
· In order to execute SHOW SGA you must be connected with the special privilege SYSDBA (which is
only available to user accounts that are members of the DBA Linux group).
Early versions of Oracle used a Static SGA. This meant that if modifications to memory management
were required, the database had to be shutdown, modifications were made to the init.ora parameter
file, and then the database had to be restarted.
Oracle 11g uses a Dynamic SGA. Memory configurations for the system global area can be made
without shutting down the database instance. The DBA can resize the Database Buffer Cache and
Shared Pool dynamically.
Several initialization parameters are set that affect the amount of random access memory dedicated to
the SGA of an Oracle Instance. These are:
· SGA_MAX_SIZE: This optional parameter is used to set a limit on the amount of virtual
memory allocated to the SGA – a typical setting might be 1 GB; however, if the value
for SGA_MAX_SIZE in the initialization parameter file or server parameter file is less than the sum the
memory allocated for all components, either explicitly in the parameter file or by default, at the time the
instance is initialized, then the database ignores the setting for SGA_MAX_SIZE. For optimal
performance, the entire SGA should fit in real memory to eliminate paging to/from disk by the operating
system.
· DB_CACHE_SIZE: This optional parameter is used to tune the amount memory allocated to the
Database Buffer Cache in standard database blocks. Block sizes vary among operating systems. The
DBORCL database uses 8 KB blocks. The total blocks in the cache defaults to 48 MB on LINUX/UNIX
and 52 MB on Windows operating systems.
· LOG_BUFFER: This optional parameter specifies the number of bytes allocated for the Redo Log
Buffer.
· SHARED_POOL_SIZE: This optional parameter specifies the number of bytes of memory allocated to
shared SQL and PL/SQL. The default is 16 MB. If the operating system is based on a 64
bit configuration, then the default size is 64 MB.
By Anand Harsha 48
· LARGE_POOL_SIZE: This is an optional memory object – the size of the Large Pool defaults to zero. If
the init.ora parameter PARALLEL_AUTOMATIC_TUNING is set to TRUE, then the default size is
automatically calculated.
The size of the SGA cannot exceed the parameter SGA_MAX_SIZE minus the combination of the size of
the additional parameters, DB_CACHE_SIZE, LOG_BUFFER, SHARED_POOL_SIZE, LARGE_POOL_SIZE,
and JAVA_POOL_SIZE.
Memory is allocated to the SGA as contiguous virtual memory in units termed granules. Granule size
depends on the estimated total size of the SGA, which as was noted above, depends on the
SGA_MAX_SIZE parameter. Granules are sized as follows:
Granules are assigned to the Database Buffer Cache, Shared Pool, Java Pool, and other memory
structures, and these memory components can dynamically grow and shrink. Using contiguous memory
improves system performance. The actual number of granules assigned to one of these memory
components can be determined by querying the database view named V$BUFFER_POOL.
Granules are allocated when the Oracle server starts a database instance in order to provide memory
addressing space to meet the SGA_MAX_SIZE parameter. The minimum is 3 granules: one each for the
fixed SGA, Database Buffer Cache, and Shared Pool. In practice, you'll find the SGA is allocated much
more memory than this. The SELECT statement shown below shows a current_size of 1,152 granules.
FROM v$buffer_pool;
By Anand Harsha 49
DEFAULT 8192 560 576 71244
For additional information on the dynamic SGA sizing, enroll in Oracle's Oracle11g Database
Performance Tuning course.
A PGA is:
· a nonshared memory region that contains data and control information exclusively for use by an Oracle
process.
· One PGA exists for each Server Process and each Background Process. It stores data and control
information for a single Server Process or a single Background Process.
· It is allocated when a process is created and the memory is scavenged by the operating system when
the process terminates. This is NOT a shared part of memory – one PGA to each process only.
· The collection of individual PGAs is the total instance PGA, or instance PGA.
· Database initialization parameters set the size of the instance PGA, not individual PGAs.
The Program Global Area is also termed the Process Global Area (PGA) and is a part of memory
allocated that is outside of the Oracle Instance.
By Anand Harsha 50
The content of the PGA varies, but as shown in the figure above, generally includes the following:
· Private SQL Area: Stores information for a parsed SQL statement – stores bind variable values and
runtime memory allocations. A user session issuing SQL statements has a Private SQL Area that may be
By Anand Harsha 51
associated with a Shared SQL Area if the same SQL statement is being executed by more than one
system user. This often happens in OLTP environments where many users are executing and using the
same application program.
o Dedicated Server environment – the Private SQL Area is located in the Program Global Area.
o Shared Server environment – the Private SQL Area is located in the System Global Area.
· Session Memory: Memory that holds session variables and other session information.
· SQL Work Areas: Memory allocated for sort, hash-join, bitmap merge, and bitmap create types of
operations.
o Oracle 9i and later versions enable automatic sizing of the SQL Work Areas by setting
the WORKAREA_SIZE_POLICY = AUTO parameter (this is the default!) and PGA_AGGREGATE_TARGET =
n (where n is some amount of memory established by the DBA). However, the DBA can let the Oracle
DBMS determine the appropriate amount of memory.
Prior to Oracle 10G, a DBA had to manually specify SGA Component sizes through the initialization
parameters, such as SHARED_POOL_SIZE, DB_CACHE_SIZE, JAVA_POOL_SIZE, and LARGE_POOL_SIZE
parameters.
Automatic Shared Memory Management enables a DBA to specify the total SGA memory available
through the SGA_TARGET initialization parameter. The Oracle Database automatically distributes this
memory among various subcomponents to ensure most effective memory utilization.
sga_target=1610612736
By Anand Harsha 52
With automatic SGA memory management, the different SGA components are flexibly sized to adapt to
the SGA available.
Setting a single parameter simplifies the administration task – the DBA only specifies the amount of SGA
memory available to an instance – the DBA can forget about the sizes of individual components. No out
of memory errors are generated unless the system has actually run out of memory. No manual tuning
effort is needed.
The SGA_TARGET initialization parameter reflects the total size of the SGA and includes memory for the
following components:
Fixed SGA and other internal allocations needed by the Oracle Database instance
The log buffer
The shared pool
The Java pool
The buffer cache
The keep and recycle buffer caches (if specified)
Nonstandard block size buffer caches (if specified)
The Streams Pool
If SGA_TARGET is set to a value greater than SGA_MAX_SIZE at startup, then the SGA_MAX_SIZE value
is bumped up to accommodate SGA_TARGET.
When you set a value for SGA_TARGET, Oracle Database 11g automatically sizes the most commonly
configured components, including:
There are a few SGA components whose sizes are not automatically adjusted. The DBA must specify the
sizes of these components explicitly, if they are needed by an application. Such components are:
By Anand Harsha 53
The granule size that is currently being used for the SGA for each component can be viewed in the
view V$SGAINFO. The size of each component and the time and type of the last resize operation
performed on each component can be viewed in the view V$SGA_DYNAMIC_COMPONENTS.
Shared-Pool
The Shared Pool is a memory structure that is shared by all system users.
· It caches various types of program data. For example, the shared pool stores parsed SQL, PL/SQL code,
system parameters, and data dictionary information.
· The shared pool is involved in almost every operation that occurs in the database. For example, if a
user executes a SQL statement, then Oracle Database accesses the shared pool.
· The variable component grows and shrinks depending on the demands placed on memory size by
system users and application programs.
By Anand Harsha 54
Memory can be allocated to the Shared Pool by the parameter SHARED_POOL_SIZE in the parameter
file. The default value of this parameter is 8MB on 32-bit platforms and 64MB on 64-bit platforms.
Increasing the value of this parameter increases the amount of memory reserved for the shared pool.
You can alter the size of the shared pool dynamically with the ALTER SYSTEM SET command. An
example command is shown in the figure below. You must keep in mind that the total memory
allocated to the SGA is set by the SGA_TARGET parameter (and may also be limited by
the SGA_MAX_SIZE if it is set), and since the Shared Pool is part of the SGA, you cannot exceed the
maximum size of the SGA. It is recommended to let Oracle optimize the Shared Pool size.
The Shared Pool stores the most recently executed SQL statements and used data definitions. This is
because some system users and application programs will tend to execute the same SQL statements
often. Saving this information in memory can improve system performance.
Library Cache
Memory is allocated to the Library Cache whenever an SQL statement is parsed or a program unit is
called. This enables storage of the most recently used SQL and PL/SQL statements.
If the Library Cache is too small, the Library Cache must purge statement definitions in order to have
space to load new SQL and PL/SQL statements. Actual management of this memory structure is through
a Least-Recently-Used (LRU) algorithm. This means that the SQL and PL/SQL statements that are oldest
and least recently used are purged when more storage space is needed.
· Shared SQL: This stores/shares the execution plan and parse tree for SQL statements, as well as
PL/SQL statements such as functions, packages, and triggers. If a system user executes an identical
statement, then the statement does not have to be parsed again in order to execute the statement.
By Anand Harsha 55
· Private SQL Area: With a shared server, each session issuing a SQL statement has a private SQL area
in its PGA.
o Each user that submits the same statement has a private SQL area pointing to the same shared SQL area.
o Many private SQL areas in separate PGAs can be associated with the same shared SQL area.
o This figure depicts two different client processes issuing the same SQL statement – the parsed solution is
already in the Shared SQL Area.
By Anand Harsha 56
The Data Dictionary Cache is a memory structure that caches data dictionary information that has been
recently used.
· Information accessed includes user account information, datafile names, table descriptions, user
privileges, and other information.
The database server manages the size of the Data Dictionary Cache internally and the size depends on
the size of the Shared Pool in which the Data Dictionary Cache resides. If the size is too small, then the
data dictionary tables that reside on disk must be queried often for information and this will slow down
performance.
The Server Result Cache holds result sets and not data blocks. The server result cache contains the SQL
query result cache and PL/SQL function result cache, which share the same infrastructure.
· Using the cache results for future queries tends to improve performance.
· For example, suppose an application runs the same SELECT statement repeatedly. If the results are
cached, then the database returns them immediately.
· In this way, the database avoids the expensive operation of rereading blocks and recomputing results.
· Without caching, 1000 calls of a function at 1 second per call would take 1000 seconds.
By Anand Harsha 57
· With caching, 1000 function calls with the same inputs could take 1 second total.
· Good candidates for result caching are frequently invoked functions that depend on relatively static
data.
Buffer Caches
A number of buffer caches are maintained in memory in order to improve system response time.
The Database Buffer Cache is a fairly large memory object that stores the actual data blocks that are
retrieved from datafiles by system queries and other data manipulation language commands.
When Database Smart Flash Cache (flash cache) is enabled, part of the buffer cache can reside in the
flash cache.
· This buffer cache extension is stored on a flash disk device, which is a solid state storage device that
uses flash memory.
· The database can improve performance by caching buffers in flash memory instead of reading from
magnetic disk.
· Database Smart Flash Cache is available only in Solaris and Oracle Enterprise Linux.
· The first look is in the Database Buffer Cache to determine if the requested information happens to
already be located in memory – thus the information would not need to be retrieved from disk and this
would speed up performance.
By Anand Harsha 58
· If the information is not in the Database Buffer Cache, the Server Process retrieves the information
from disk and stores it to the cache.
· Keep in mind that information read from disk is read a block at a time, NOT a row at a time, because a
database block is the smallest addressable storage space on disk.
Database blocks are kept in the Database Buffer Cache according to a Least Recently Used (LRU)
algorithm and are aged out of memory if a buffer cache block is not used in order to provide space for
the insertion of newly needed database blocks.
· Unused - a buffer is available for use - it has never been used or is currently unused.
· Clean - a buffer that was used earlier - the data has been written to disk.
· Dirty - a buffer that has modified data that has not been written to disk.
· Free (unpinned).
The write list (also called a write queue) holds dirty buffers – these are buffers that hold that data that
has been modified, but the blocks have not been written back to disk.
The LRU list holds unused, free clean buffers, pinned buffers, and free dirty buffers that have not yet
been moved to the write list. Free clean buffers do not contain any useful data and are available for
use. Pinned buffers are currently being accessed.
By Anand Harsha 59
When an Oracle process accesses a buffer, the process moves the buffer to the most recently used
(MRU) end of the LRU list – this causes dirty buffers to age toward the LRU end of the LRU list.
When an Oracle user process needs a data row, it searches for the data in the database buffer cache
because memory can be searched more quickly than hard disk can be accessed. If the data row is
already in the cache (a cache hit), the process reads the data from memory; otherwise a cache
miss occurs and data must be read from hard disk into the database buffer cache.
Before reading a data block into the cache, the process must first find a free buffer. The process
searches the LRU list, starting at the LRU end of the list. The search continues until a free buffer is found
or until the search reaches the threshold limit of buffers.
Each time a user process finds a dirty buffer as it searches the LRU, that buffer is moved to the write list
and the search for a free buffer continues.
When a user process finds a free buffer, it reads the data block from disk into the buffer and moves the
buffer to the MRU end of the LRU list.
If an Oracle user process searches the threshold limit of buffers without finding a free buffer, the
process stops searching the LRU list and signals the DBWn background process to write some of the dirty
buffers to disk. This frees up some buffers.
By Anand Harsha 60
Redo Log Buffer
The Redo Log Buffer memory object stores images of all changes made to database blocks.
· Database blocks typically store several table rows of organizational data. This means that if a single
column value from one row in a block is changed, the block image is stored. Changes include INSERT,
UPDATE, DELETE, CREATE, ALTER, or DROP.
By Anand Harsha 61
· LGWR writes redo sequentially to disk while DBWn performs scattered writes of data blocks to disk.
o Because LGWR enable users to avoid waiting for DBWn to complete its slow writes, the database delivers
better performance.
The Redo Log Buffer as a circular buffer that is reused over and over. As the buffer fills up, copies of the
images are stored to the Redo Log Files that are covered in more detail in a later module.
Large Pool
The Large Pool is an optional memory structure that primarily relieves the memory burden placed on
the Shared Pool. The Large Pool is used for the following tasks if it is allocated:
· Allocating space for session memory requirements from the User Global Area where a Shared Server is
in use.
· Transactions that interact with more than one database, e.g., a distributed database scenario.
o RMAN uses this only if the BACKUP_DISK_IO = n and BACKUP_TAPE_IO_SLAVE = TRUE parameters are
set.
o If the Large Pool is too small, memory allocation for backup will fail and memory will be allocated from
the Shared Pool.
The Large Pool size is set with the LARGE_POOL_SIZE parameter – this is not a dynamic parameter. It
does not use an LRU list to manage memory.
By Anand Harsha 62
Java Pool
The Java Pool is an optional memory object, but is required if the database has Oracle Java installed and
in use for Oracle JVM (Java Virtual Machine).
· The size is set with the JAVA_POOL_SIZE parameter that defaults to 24MB.
· The Java Pool is used for memory allocation to parse Java commands and to store data associated with
Java commands.
· Storing Java code and data in the Java Pool is analogous to SQL and PL/SQL code cached in the Shared
Pool.
Streams Pool
This pool stores data and control structures to support the Oracle Streams feature of Oracle Enterprise
Edition.
· If STEAMS_POOL_SIZE is not set or is zero, the size of the pool grows dynamically.
Processes
· User Process: Starts when a database user requests to connect to an Oracle Server.
· Server Process: Establishes the Connection to an Oracle Instance when a User Process requests
connection – makes the connection for the User Process.
Client Process
By Anand Harsha 63
In order to use Oracle, you must connect to the database. This must occur whether you're using
SQLPlus, an Oracle tool such as Designer or Forms, or an application program. The client process is also
termed the user process in some Oracle documentation.
Server Process
By Anand Harsha 64
A Server Process is the go-between for a Client Process and the Oracle Instance.
· Dedicated Server environment – there is a single Server Process to serve each Client Process.
· Shared Server environment – a Server Process can serve several User Processes, although with some
performance reduction.
Background Processes
As is shown here, there are both mandatory, optional, and slave background processes that are started
whenever an Oracle Instance starts up. These background processes serve all system users. We will
cover mandatory process in detail.
By Anand Harsha 65
· Process Monitor Process (PMON)
Optional Processes
· Others
This query will display all background processes running to serve a database:
SELECT PNAME
FROM V$PROCESS
ORDER BY PNAME;
PMON
By Anand Harsha 66
Examples include the dropping of a user connection due to a network failure or the abnormal
termination (ABEND) of a user application program.
It cleans up the database buffer cache and releases resources that were used by a failed user
process.
It does the tasks shown in the figure below.
SMON
By Anand Harsha 67
If an Oracle Instance fails, all information in memory not written to disk is lost. SMON is responsible for
recovering the instance when the database is started up again. It does the following:
Rolls forward to recover data that was recorded in a Redo Log File, but that had not yet been
recorded to a datafile by DBWn. SMON reads the Redo Log Files and applies the changes to the
data blocks. This recovers all transactions that were committed because these were written to
the Redo Log Files prior to system failure.
Opens the database to allow system users to logon.
Rolls back uncommitted transactions.
SMON also does limited space management. It combines (coalesces) adjacent areas of free space in the
database's datafiles for tablespaces that are dictionary managed.
The Database Writer writes modified blocks from the database buffer cache to the datafiles.
By Anand Harsha 68
One database writer process (DBW0) is sufficient for most systems.
A DBA can configure up to 20 DBWn processes (DBW0 through DBW9 and DBWa through DBWj)
in order to improve write performance for a system that modifies data heavily.
The initialization parameter DB_WRITER_PROCESSES specifies the number of DBWn processes.
The purpose of DBWn is to improve system performance by caching writes of database blocks from
the Database Buffer Cache back to datafiles.
Blocks that have been modified and that need to be written back to disk are termed "dirty
blocks."
The DBWn also ensures that there are enough free buffers in the Database Buffer Cache to
service Server Processes that may be reading data from datafiles into the Database Buffer Cache
Performance improves because by delaying writing changed database blocks back to disk, a
Server Process may find the data that is needed to meet a User Process request already residing
in memory!
DBWn writes to datafiles when one of these events occurs that is illustrated in the figure below.
LGWR
The Log Writer (LGWR) writes contents from the Redo Log Buffer to the Redo Log File that is in use.
These are sequential writes since the Redo Log Files record database modifications based on the
actual time that the modification takes place.
By Anand Harsha 69
LGWR actually writes before the DBWn writes and only confirms that a COMMIT operation has
succeeded when the Redo Log Buffer contents are successfully written to disk.
LGWR can also call the DBWn to write contents of the Database Buffer Cache to disk.
The LGWR writes according to the events illustrated in the figure shown below.
CKPT
The Checkpoint (CPT) process writes information to update the database control files and headers of
datafiles.
A checkpoint identifies a point in time with regard to the Redo Log Files where instance
recovery is to begin should it be necessary.
It can tell DBWn to write blocks to disk.
A checkpoint is taken at a minimum, once every three seconds.
By Anand Harsha 70
Think of a checkpoint record as a starting point for recovery. DBWn will have completed writing all
buffers from the Database Buffer Cache to disk prior to the checkpoint, thus those records will not
require recovery. This does the following:
Ensures modified data blocks in memory are regularly written to disk – CKPT can call the DBWn
process in order to ensure this and does so when writing a checkpoint record.
Reduces Instance Recovery time by minimizing the amount of work needed for recovery since
only Redo Log File entries processed since the last checkpoint require recovery.
Causes all committed data to be written to datafiles during database shutdown.
By Anand Harsha 71
By Anand Harsha 72
Unit – IVth
SQL
• SQL stands for Structured Query Language
Some database systems require a semicolon at the end of each SQL statement.
A table is database object that holds user data. Each column of the table will have specified data type
bound to it. Oracle ensures that only data, which is identical to the datatype of the column, will be
stored within the column.
The Data Definition Language (DDL) and the Data Manipulation Language (DML).
It is a set of SQL commands used to create, modify and delete database structure
but not data. It also define indexes (keys), specify links between tables, and
By Anand Harsha 73
It is the area of SQL that allows changing data within the database. The query
It is the component of SQL statement that control access to data and to the
By Anand Harsha 74
The CREATE TABLE Command:
The CREATE TABLE command defines each column of the table uniquely. Each
column has a minimum of three attributes, name, datatype and size(i.e column
width).each table column definition is a single clause in the create table syntax.
Each table column definition is separated from the other by a comma. Finally, the
By Anand Harsha 75
SQL statement is terminated with a semi colon.
Syntax:
(<columnName1> <Datatype>(<size>),
Example:
(Regno NUMBER(3),
Name VARCHAR(20),
Gender CHAR,
Dob DATE,
Course CHAR(5));
be manipulated later.
When inserting a single row of data into the table, the insert operation:
By Anand Harsha 76
Loads the values passed(by the SQL insert) into the columns specified.
Syntax:
Values(<expression1>,<expression2>...);
Example:
VALUES(101,’Varsh G Kalyan’,’F’,’20-Sep-1985’,’BCA’);
Or you can use the below method to insert the data into table.
Whenever you work on the data which has data types like
to view what has been inserted. The SELECT SQL verb is used to achieve this. The
SELECT command is used to retrieve rows selected from one or more tables.
By Anand Harsha 77
SELECT * FROM gktab;
required each time. Hence, SQL provides a method of filtering table data that is
not required.
Syntax
Example
By Anand Harsha 78
Selected Rows and All Columns
The WHERE clause is used to extract only those records that fulfill a specified
criterion.
When a WHERE clause is added to the SQL query, the Oracle engine compares
each record in the table with condition specified in the WHERE clause. The Oracle
engine displays only those records that satisfy the specified condition.
Syntax
When specifying a condition in the WHERE clause all standard operators such as
Example-1:
By Anand Harsha 79
Example-2:
When a WHERE clause is added to the SQL query, the Oracle engine compares
each record in the table with condition specified in the WHERE clause. The Oracle
engine displays only those records that satisfy the specified condition.
Syntax
WHERE <condition>;
Example-1:
Example-2:
List the student’s Regno, Name, Gender for the Course BBM.
By Anand Harsha 80
SELECT Regno, Name, Gender FROM gktab WHERE Course=’BBM’;
The DISTINCT clause allows removing duplicates from the result set. The
The DISTINCT clause scans through the values of the column/s specified and
Syntax
FROM <Tablename>;
Example:
By Anand Harsha 81
from the table will be sorted in either ascending or descending order depending
Syntax
The ORDER BY clause sorts the result set based on the column specified. The
Example-1:
Example-2:
By Anand Harsha 82
DELETE Operations
The DELETE command deletes rows from the table that satisfies the condition
provided by its WHERE clause, and returns the number of records deleted.
Syntax:
Example:
1 rows deleted
By Anand Harsha 83
In the above table, the Regno 103 is deleted from the table
Example
6 rows deleted
no rows selected
Once the table is deleted, use Rollback to undo the above operations.
By Anand Harsha 84
Syntax:
UPDATE tablename
6 rows updated
In the above table, the course is changed to BCA for all the rows in the table.
Syntax:
UPDATE tablename
WHERE Condition;
Example:
Update gktab table by changing the course BCA to BBM for Regno 102.
1 rows updated
By Anand Harsha 85
SELECT * FROM gktab;
ALTER TABLE works by making a temporary copy of the original table. The
alteration is performed on the copy, then the original table is deleted and the new
one is renamed. While ALTER TABLE is executing, the original table is still
By Anand Harsha 86
Modifying Existing Columns.
ADD(NewColumnname1 Datatype(size),
NewColumnname2 Datatype(size).....);
You can also use DESC gktab, to see the new column added to table.
Syntax:
By Anand Harsha 87
ALTER TABLE gktab DROP COLUMN Phno;
The table is altered, the column Phno is removed from the table.
You can also use DESC gktab, to see the column removed from the table.
Syntax:
MODIFY(Columnname Newdatatype(Newsize));
Example:
DESC gktab;
RENAMING TABLES
Oracle allows renaming of tables. The rename operation is done atomically, which
means that no other thread can access any of the tables while the rename process
is running.
By Anand Harsha 88
Syntax
TRUNCATING TABLES
TRUNCATE command deletes the rows in the table permanently.
Syntax:
The number of deleted rows are not returned. Truncate operations drop and re-
create the table, which is much faster than deleting rows one by one.
Example:
DESTROYING TABLES
Sometimes tables within a particular database become obsolete and need to be
discarded. In such situation using the DROP TABLE statement with table name
Syntax:
Example:
If a table is dropped all the records held within and the structure of the table is
By Anand Harsha 89
COMMIT and ROLLBACK
Commit
Commit command is used to permanently save any transaction into database.
SQL> commit;
Rollback
Rollback is used to undo the changes made by any command but only before a
commit is done. We can't Rollback data which has been committed in the database
with the help of the commit keyword or DDL Commands, because DDL commands
SQL> Rollback;
DELETE operation you need to COMMIT or ROLLBACK the transaction to make the
The DROP command removes a table from the database. All the tables' rows,
indexes and privileges will also be removed. The operation cannot be rolled back.
DELETE operation you need to COMMIT or ROLLBACK the transaction to make the
TRUNCATE removes all rows from a table. The operation cannot be rolled back.
By Anand Harsha 90
Difference between CHAR and VARCHAR.
CHAR
1. Used to store fixed length data.
2. The maximum characters the data type can hold is 255 characters.
VARCHAR
1. Used to store variable length data.
2. The maximum characters the data type can hold is up to 4000 characters.
DATA CONSTRINTS
Oracle permits data constraints to be attached to table column via SQL syntax that checks data for
integrity prior storage. Once data constraints are part of a table column construct, the oracle database
engine checks the data being entered into a table column against the data constraints. If the data passes
this check, it is stored in the table column, else the data is rejected. Even if a single column of the record
being entered into the table fails a constraint, the entire record is rejected and not stored in the table.
Both CREATE TABLE and ALTER TABLE SQL verbs can be used to write SQL sentences that attach
constraints to a table column. The constraints are a keyword. The constraint is rules that restrict the
values for one or more columns in a table. The Oracle Server uses constraints to prevent invalid data
entry into tables. The constraints store the validate data and without constraints we can just store
invalid data. The constraints are an important part of the table.
By Anand Harsha 91
Primary Key Constraint
A primary key can consist of one or more columns on a table. Primary key constraints define a column or
series of columns that uniquely identify a given row in a table. Defining a primary key on a table is
optional and you can only define a single primary key on a table. A primary key constraint can consist of
one or many
columns (up to 32). When multiple columns are used as a primary key, they are called a composite key.
Any column that is defined as a primary key column is automatically set with a NOT NULL status. The
Primary key constraint can be applied at column level and table level.
By Anand Harsha 92
key. A unique constraint defines a column, or series of columns, that must be
unique in value. The UNIQUE constraint can be applied at column level and table
level.
CHECK Constraint
Business Rule validation can be applied to a table column by using CHECk constraint. CHECK constraints
must be specified as a logical expression that evaluates either to TRUE or FALSE.
The CHECK constraint ensures that all values in a column satisfy certain conditions. Once defined, the
database will only insert a new row or update an existing row if the new value satisfies the CHECK
constraint. The CHECK constraint is used to ensure data quality. A CHECK constraint takes substantially
longer to execute as compared to NOT NULL, PRIMARY KEY, FOREIGN KEY or UNIQUE. The CHECK
constraint can be applied at column level and table level.
Example on Constraints
Arithmetic Operators
Oracle allows arithmetic operators to be used while viewing records from a table or
By Anand Harsha 93
while performing data manipulation operations such as insert, updated and delete.
These are:
+ Addition
- Subtraction
/ Division
* Multiplication
() Enclosed Operations
By Anand Harsha 94
Special Note
By Anand Harsha 95
The DUAL table is a special one-row, one-column table present by default in
Logical Operators
Operators Description
OR :-For the row to be selected at least one of the conditions must be true.
By Anand Harsha 96
AND :-For a row to be selected all the specified conditions must be true.
For example: if you want to find the names of employees who are working either
For example: To find the names of the employee whose salary between10000 to
By Anand Harsha 97
For example: If you want to find out the names of the employee who do not
The lower value must be coded first. The two values in between the range must be linked with the
keyword AND. The BETWEEN operator can be used with both character and numeric data types.
However, the data types cannot be mixed.
For example: Find the names of the employee whose salary between10000 and
LIKE
The LIKE predicate allows comparison of one string value with another string value, which is not
identical. this is achieved by using wild characters. Two wild characters that are available are:
By Anand Harsha 98
_ allows to match on a single character.
IN
The IN operator is used when you want to compare a column with more than one value. It is similar to
an OR condition.
For example: If you want to find the names of company located in the city
By Anand Harsha 99
NOT IN
The NOT IN operator is opposite to IN.
For example: If you want to find the names of company located in the other city
ORACLE FUNCTIONS
Oracle functions serve the purpose of manipulating data items and returning a result. Functions are also
capable of accepting user-supplied variables or constants and operating on them. Such variables or
constants are called arguments. Any number of arguments( or no arguments at all) can be passed to a
function in the following format.
Function_Name(arguments1,arguments2.....)
Oracle functions can be clubbed together depending upon whether they operate on a single row or a
group of rows retrieved from a table. Accordingly, functions can be classified as follows:
Group Functions(Aggregate Functions): Function that act on a set of values are called group
functions.
a) COUNT()
c) MAX()
d) MIN()
e) SUM()
SQL string functions are used primarily for string manipulation. The following table details the important
string functions:
operators are:
UNION
UNION ALL
INTERSECT
MINUS
Union Clause
UNION is used to combine the result of two or more SELECT statements. However
it will eliminate duplicate rows from its result set. In case of UNION, number of
columns in all the query must be same and datatype must be same in both the
Intersect Clause
Intersect is used to combine two SELECT statements, but it only returns the records which are common
from both SELECT statement. In case of intersect the number of columns in all the query and datatype
must be same.
INNER
OUTER(LEFT,RIGHT,FULL)
CROSS
For example: If you want to display the product information for each order the query will be as given
below
OUTER Join
OUTER join condition returns all rows from both tables which satisfy the join condition along with rows
which do not satisfy the join condition from one of the tables. The sql outer join operator in Oracle is (+)
and is used on one side of the join condition only.
NOTE: If the (+) operator is used in the left side of the join condition it is equivalent to left outer join. If
used on the right side of the join condition it is equivalent to right outer join.
OUTER JOIN :
Outer Join retrieves Either, the matched rows from one table and all rows in the
other table Or, all rows in all tables (it doesn't matter whether or not there is a
match).
This join returns all the rows from the left table in conjunction with the matching rows from the right
table. If there are no columns matching in the right table, it returns NULL values.
This join returns all the rows from the right table in conjunction with the matching rows from the left
table. If there are no columns matching in the left table, it returns NULL values.
CROSS Join
It is the Cartesian product of the two tables involved. It will return a table with consists of records which
combines each row from the first table with each row of the second table. The result of a CROSS JOIN
will not make sense in most of the situations. Moreover, we won’t need this at all (or needs the least, to
be precise).
LEFT JOIN: returns all rows from the left table, even if there are no matches in the right table.
RIGHT JOIN: returns all rows from the right table, even if there are no matches in the left table.
FULL JOIN: returns rows when there is a match in one of the tables. SELF JOIN: is used to join a table to
itself as if the table were two tables, temporarily renaming at least one table in the SQL statement.
CARTESIAN JOIN: returns the Cartesian product of the sets of records from the two or more joined
tables.
Introduction to PL/SQL
PL/SQL is a combination of SQL along with the procedural features of programming languages. It was
developed by Oracle Corporation in the early 90's to enhance the capabilities of SQL. PL/SQL is one of
three key programming languages embedded in the Oracle Database, along with SQL itself and Java. This
tutorial will give you great understanding on PL/SQL to proceed with Oracle database and other
advanced RDBMS concepts.
The PL/SQL programming language was developed by Oracle Corporation in the late 1980s as
procedural extension language for SQL and the Oracle relational database. Following are certain
notable facts about PL/SQL −
PL/SQL is a completely portable, high-performance transaction-processing language.
PL/SQL provides a built-in, interpreted and OS independent programming environment.
PL/SQL can also directly be called from the command-line SQL*Plus interface.
Direct call can also be made from external programming language calls to database.
PL/SQL's general syntax is based on that of ADA and Pascal programming language.
Apart from Oracle, PL/SQL is available in TimesTen in-memory database and IBM DB2.
Features of PL/SQL
PL/SQL has the following features −
Advantages of PL/SQL
PL/SQL has the following advantages −
SQL is the standard database language and PL/SQL is strongly integrated with SQL. PL/SQL
supports both static and dynamic SQL. Static SQL supports DML operations and transaction
control from PL/SQL block. In Dynamic SQL, SQL allows embedding DDL statements in PL/SQL
blocks.
PL/SQL allows sending an entire block of statements to the database at one time. This reduces
network traffic and provides high performance for the applications.
Declarations
1
This section starts with the keyword DECLARE. It is an optional section and defines all
variables, cursors, subprograms, and other elements to be used in the program.
Executable Commands
2 This section is enclosed between the keywords BEGIN and END and it is a mandatory
section. It consists of the executable PL/SQL statements of the program. It should have
at least one executable line of code, which may be just a NULL command to indicate that
nothing should be executed.
Exception Handling
3
This section starts with the keyword EXCEPTION. This optional section
contains exception(s) that handle errors in the program.
Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within other PL/SQL
blocks using BEGIN and END. Following is the basic structure of a PL/SQL block −
DECLARE
<declarations section>
BEGIN
Delimiter Description
% Attribute indicator
. Component selector
, Item separator
= Relational operator
; Statement terminator
:= Assignment operator
|| Concatenation operator
** Exponentiation operator
.. Range operator
DECLARE
-- variable declaration
message varchar2(20):= 'Hello, World!';
BEGIN
/*
* PL/SQL executable statement(s)
*/
dbms_output.put_line(message);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Hello World
PL/SQL block
Function
Package
Package body
Procedure
Trigger
Type
Type body
Scalar
1
Single values with no internal components, such as a NUMBER,
DATE, or BOOLEAN.
Composite
3
Data items that have internal components that can be accessed individually. For
example, collections and records.
4 Reference
Pointers to other data items.
1 Numeric
Numeric values on which arithmetic operations are performed.
2 Character
Alphanumeric values that represent single characters or strings of characters.
4 Datetime
Dates and times.
PL/SQL provides subtypes of data types. For example, the data type NUMBER has a
subtype called INTEGER. You can use the subtypes in your PL/SQL program to make
the data types compatible with data types in other programs while embedding the
PL/SQL code in another program, such as a Java program.
PLS_INTEGER
1
Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32
bits
BINARY_INTEGER
2
Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32
bits
3 BINARY_FLOAT
Single-precision IEEE 754-format floating-point number
4 BINARY_DOUBLE
Double-precision IEEE 754-format floating-point number
NUMBER(prec, scale)
5
Fixed-point or floating-point number with absolute value in range 1E-130 to (but not
including) 1.0E126. A NUMBER variable can also represent 0
7 DECIMAL(prec, scale)
IBM specific fixed-point type with maximum precision of 38 decimal digits
8 NUMERIC(pre, secale)
Floating type with maximum precision of 38 decimal digits
DOUBLE PRECISION
9
ANSI specific floating-point type with maximum precision of 126 binary digits
(approximately 38 decimal digits)
FLOAT
10
ANSI and IBM specific floating-point type with maximum precision of 126 binary
digits (approximately 38 decimal digits)
11 INT
ANSI specific integer type with maximum precision of 38 decimal digits
12 INTEGER
ANSI and IBM specific integer type with maximum precision of 38 decimal digits
13 SMALLINT
ANSI and IBM specific integer type with maximum precision of 38 decimal digits
REAL
14
Floating-point type with maximum precision of 63 binary digits (approximately 18
decimal digits)
1 CHAR
Fixed-length character string with maximum size of 32,767 bytes
2 VARCHAR2
Variable-length character string with maximum size of 32,767 bytes
RAW
3
Variable-length binary or byte string with maximum size of 32,767 bytes, not
interpreted by PL/SQL
4 NCHAR
Fixed-length national character string with maximum size of 32,767 bytes
5 NVARCHAR2
Variable-length national character string with maximum size of 32,767 bytes
6 LONG
Variable-length character string with maximum size of 32,760 bytes
LONG RAW
7
Variable-length binary or byte string with maximum size of 32,760 bytes, not
interpreted by PL/SQL
9 UROWID
Universal row identifier (physical, logical, or foreign row identifier)
SQL statements
Built-in SQL functions (such as TO_CHAR)
PL/SQL functions invoked from SQL statements
MONTH 01 to 12 0 to 11
MINUTE 00 to 59 0 to 59
NULLs in PL/SQL
PL/SQL NULL values represent missing or unknown data and they are not an integer, a character, or
any other specific data type. Note that NULL is not the same as an empty data string or the null
character value '\0'. A null can be assigned but it cannot be equated with anything, including itself.
PL/SQL Variables
we will discuss Variables in Pl/SQL. A variable is nothing but a name given to a storage area that our
programs can manipulate. Each variable in PL/SQL has a specific data type, which determines the size
and the layout of the variable's memory; the range of values that can be stored within that memory
and the set of operations that can be applied to the variable.
The name of a PL/SQL variable consists of a letter optionally followed by more letters, numerals, dollar
signs, underscores, and number signs and should not exceed 30 characters. By default, variable names
are not case-sensitive. You cannot use a reserved PL/SQL keyword as a variable name.
PL/SQL programming language allows to define various types of variables, such as date time data types,
records, collections, etc. which we will cover in subsequent chapters. For this chapter, let us study only
basic variable types.
DECLARE
a integer := 10;
b integer := 20;
c integer;
f real;
BEGIN
c := a + b;
dbms_output.put_line('Value of c: ' || c);
f := 70.0/3.0;
dbms_output.put_line('Value of f: ' || f);
END;
/
When the above code is executed, it produces the following result −
Value of c: 30
Value of f: 23.333333333333333333
DECLARE
-- Global variables
num1 number := 95;
num2 number := 85;
BEGIN
dbms_output.put_line('Outer Variable num1: ' || num1);
dbms_output.put_line('Outer Variable num2: ' || num2);
DECLARE
-- Local variables
num1 number := 195;
num2 number := 185;
BEGIN
dbms_output.put_line('Inner Variable num1: ' || num1);
dbms_output.put_line('Inner Variable num2: ' || num2);
END;
END;
/
When the above code is executed, it produces the following result −
Outer Variable num1: 95
Outer Variable num2: 85
Inner Variable num1: 195
Inner Variable num2: 185
Table Created
The following program assigns values from the above table to PL/SQL variables using the SELECT INTO
clause of SQL −
DECLARE
c_id customers.id%type := 1;
c_name customers.name%type;
c_addr customers.address%type;
c_sal customers.salary%type;
BEGIN
SELECT name, address, salary INTO c_name, c_addr, c_sal
FROM customers
WHERE id = c_id;
dbms_output.put_line
('Customer ' ||c_name || ' from ' || c_addr || ' earns ' || c_sal);
END;
/
we will discuss constants and literals in PL/SQL. A constant holds a value that once declared, does not
change in the program. A constant declaration specifies its name, data type, and value, and allocates
storage for it. The declaration can also impose the NOT NULL constraint.
Declaring a Constant
A constant is declared using the CONSTANT keyword. It requires an initial value and does not allow that
value to be changed. For example −
Numeric Literals
Character Literals
String Literals
BOOLEAN Literals
Date and Time Literals
The following table provides examples from all these categories of literal values.
Numeric Literals
2 Character Literals
'A' '%' '9' ' ' 'z' '('
String Literals
3 'Hello, world!'
'Tutorials Point'
'19-NOV-12'
4 BOOLEAN Literals
TRUE, FALSE, and NULL.
DECLARE
message varchar2(30):= 'That''s tutorialspoint.com!';
BEGIN
dbms_output.put_line(message);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
That's tutorialspoint.com!
PL/SQL Operators
we will discuss operators in PL/SQL. An operator is a symbol that tells the compiler to perform specific
mathematical or logical manipulation. PL/SQL language is rich in built-in operators and provides the
following types of operators −
Arithmetic operators
Relational operators
Comparison operators
Logical operators
String operators
Here, we will understand the arithmetic, relational, comparison and logical operators one by one. The
String operators will be discussed in a later chapter − PL/SQL - Strings.
Arithmetic Operators
Following table shows all the arithmetic operators supported by PL/SQL. Let us assume variable
A holds 10 and variable B holds 5, then −
Show Examples
Relational Operators
Relational operators compare two expressions or values and return a Boolean result. Following table
shows all the relational operators supported by PL/SQL. Let us assume variable A holds 10 and variable
B holds 20, then −
Show Examples
Checks if the values of two operands are equal or not, if yes then (A = B) is not
=
condition becomes true. true.
!=
Checks if the values of two operands are equal or not, if values are (A != B) is
<> not equal then condition becomes true. true.
~=
Checks if the value of left operand is greater than the value of right (A > B) is not
>
operand, if yes then condition becomes true. true.
Checks if the value of left operand is less than the value of right (A < B) is true.
<
operand, if yes then condition becomes true.
Checks if the value of left operand is greater than or equal to the (A >= B) is not
>=
value of right operand, if yes then condition becomes true. true.
<= Checks if the value of left operand is less than or equal to the value (A <= B) is
Comparison Operators
Comparison operators are used for comparing one expression to another. The result is always
either TRUE, FALSE or NULL.
Show Examples
The LIKE operator compares a character, If 'Zara Ali' like 'Z% A_i' returns a
string, or CLOB value to a pattern and returns Boolean true, whereas, 'Nuha Ali'
LIKE
TRUE if the value matches the pattern and like 'Z% A_i' returns a Boolean
FALSE if it does not. false.
The IN operator tests set membership. x IN If x = 'm' then, x in ('a', 'b', 'c')
IN (set) means that x is equal to any member of returns Boolean false but x in ('m',
set. 'n', 'o') returns Boolean true.
Logical Operators
Following table shows the Logical operators supported by PL/SQL. All these operators work on Boolean
operands and produce Boolean results. Let us assume variable A holds true and variable B holds false,
then −
Show Examples
Called the logical AND operator. If both the operands are true then (A and B) is
and
condition becomes true. false.
Called the logical NOT Operator. Used to reverse the logical state of not (A and B)
not its operand. If a condition is true then Logical NOT operator will is true.
make it false.
Operator Operation
** exponentiation
+, - identity, negation
*, / multiplication, division
AND conjunction
OR inclusion
PL/SQL conditions
we will discuss conditions in PL/SQL. Decision-making structures require that the programmer specify
one or more conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and optionally, other statements
to be executed if the condition is determined to be false.
Following is the general form of a typical conditional (i.e., decision making) structure found in most of
the programming languages –
IF - THEN statement
1
The IF statement associates a condition with a sequence of statements enclosed by the
keywords THEN and END IF. If the condition is true, the statements get executed and if
the condition is false or NULL then the IF statement does nothing.
IF-THEN-ELSE statement
IF-THEN-ELSIF statement
3
It allows you to choose between several alternatives.
Case statement
Like the IF statement, the CASE statement selects one sequence of statements to
4 execute.
However, to select the sequence, the CASE statement uses a selector rather than
multiple Boolean expressions. A selector is an expression whose value is used to select
one of several alternatives.
nested IF-THEN-ELSE
6
You can use one IF-THEN or IF-THEN-ELSIF statement inside another IF-THEN or IF-THEN-
ELSIF statement(s).
PL/SQL provides the following types of loop to handle the looping requirements. Click the following
links to check their detail.
1
In this loop structure, sequence of statements is enclosed between the LOOP and the
END LOOP statements. At each iteration, the sequence of statements is executed and
then control resumes at the top of the loop.
DECLARE
i number(1);
j number(1);
BEGIN
<< outer_loop >>
FOR i IN 1..3 LOOP
<< inner_loop >>
FOR j IN 1..3 LOOP
dbms_output.put_line('i is: '|| i || ' and j is: ' || j);
END loop inner_loop;
END loop outer_loop;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
i is: 1 and j is: 1
i is: 1 and j is: 2
i is: 1 and j is: 3
i is: 2 and j is: 1
i is: 2 and j is: 2
i is: 2 and j is: 3
i is: 3 and j is: 1
i is: 3 and j is: 2
i is: 3 and j is: 3
EXIT statement
1
The Exit statement completes the loop and control passes to the statement immediately
after the END LOOP.
CONTINUE statement
2
Causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.
GOTO statement
3
Transfers control to the labeled statement. Though it is not advised to use the GOTO
statement in your program.
PL/SQL Strings
The string in PL/SQL is actually a sequence of characters with an optional size specification. The
characters could be numeric, letters, blank, special characters or a combination of all. PL/SQL offers
three kinds of strings −
Fixed-length strings − In such strings, programmers specify the length while declaring the
string. The string is right-padded with spaces to the length so specified.
Variable-length strings − In such strings, a maximum length up to 32,767, for the string is
specified and no padding takes place.
Character large objects (CLOBs) − These are variable-length strings that can be up to 128
terabytes.
PL/SQL strings could be either variables or literals. A string literal is enclosed within quotation marks.
For example,
'This is a string literal.' Or 'hello world'
DECLARE
name varchar2(20);
company varchar2(30);
introduction clob;
choice char(1);
BEGIN
name := 'John Smith';
company := 'Infotech';
introduction := ' Hello! I''m John Smith from Infotech.';
choice := 'y';
IF choice = 'y' THEN
dbms_output.put_line(name);
dbms_output.put_line(company);
dbms_output.put_line(introduction);
END IF;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
John Smith
Infotech
Hello! I'm John Smith from Infotech.
1 ASCII(x);
Returns the ASCII value of the character x.
2 CHR(x);
Returns the character with the ASCII value of x.
3 CONCAT(x, y);
Concatenates the strings x and y and returns the appended string.
4 INITCAP(x);
Converts the initial letter of each word in x to uppercase and returns that string.
6 INSTRB(x);
Returns the location of a string within another string, but returns the value in bytes.
7 LENGTH(x);
Returns the number of characters in x.
8 LENGTHB(x);
Returns the length of a character string in bytes for single byte character set.
9 LOWER(x);
Converts the letters in x to lowercase and returns that string.
11 LTRIM(x [, trim_string]);
Trims characters from the left of x.
12 NANVL(x, value);
Returns value if x matches the NaN special value (not a number), otherwise x is returned.
NLS_INITCAP(x);
13
Same as the INITCAP function except that it can use a different sort method as specified
by NLSSORT.
NLS_LOWER(x) ;
14
Same as the LOWER function except that it can use a different sort method as specified
by NLSSORT.
NLS_UPPER(x);
15
Same as the UPPER function except that it can use a different sort method as specified
by NLSSORT.
NLSSORT(x);
16
Changes the method of sorting the characters. Must be specified before any NLS
function; otherwise, the default sort will be used.
17 NVL(x, value);
Returns value if x is null; otherwise, x is returned.
21 RTRIM(x [, trim_string]);
Trims x from the right.
22 SOUNDEX(x) ;
Returns a string containing the phonetic representation of x.
23 Returns a substring of x that begins at the position specified by start. An optional length
for the substring may be supplied.
SUBSTRB(x);
24
Same as SUBSTR except that the parameters are expressed in bytes instead of characters
for the single-byte character systems.
26 UPPER(x);
Converts the letters in x to uppercase and returns that string.
Example 1
DECLARE
greetings varchar2(11) := 'hello world';
BEGIN
dbms_output.put_line(UPPER(greetings));
dbms_output.put_line(INITCAP(greetings));
When the above code is executed at the SQL prompt, it produces the following result −
HELLO WORLD
hello world
Hello World
h
d
World
ello World
2
Example 2
DECLARE
greetings varchar2(30) := '......Hello World.....';
BEGIN
dbms_output.put_line(RTRIM(greetings,'.'));
dbms_output.put_line(LTRIM(greetings, '.'));
dbms_output.put_line(TRIM( '.' from greetings));
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
......Hello World
PL/SQL Arrays
we will discuss arrays in PL/SQL. The PL/SQL programming language provides a data structure called
the VARRAY, which can store a fixed-size sequential collection of elements of the same type. A varray is
used to store an ordered collection of data, however it is often better to think of an array as a
collection of variables of the same type.
All varrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
An array is a part of collection type data and it stands for variable-size arrays. We will study other
collection types in a later chapter 'PL/SQL Collections'.
Each element in a varray has an index associated with it. It also has a maximum size that can be
changed dynamically.
The basic syntax for creating a VARRAY type within a PL/SQL block is −
TYPE varray_type_name IS VARRAY(n) of <element_type>
For example −
Example 1
The following program illustrates the use of varrays −
DECLARE
type namesarray IS VARRAY(5) OF VARCHAR2(10);
type grades IS VARRAY(5) OF INTEGER;
names namesarray;
marks grades;
total integer;
BEGIN
names := namesarray('Kavita', 'Pritam', 'Ayan', 'Rishav', 'Aziz');
marks:= grades(98, 97, 78, 87, 92);
total := names.count;
dbms_output.put_line('Total '|| total || ' Students');
FOR i in 1 .. total LOOP
dbms_output.put_line('Student: ' || names(i) || '
Marks: ' || marks(i));
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Total 5 Students
Student: Kavita Marks: 98
Student: Pritam Marks: 97
Student: Ayan Marks: 78
Student: Rishav Marks: 87
Student: Aziz Marks: 92
Example 2
Elements of a varray could also be a %ROWTYPE of any database table or %TYPE of any database table
field. The following example illustrates the concept.
We will use the CUSTOMERS table stored in our database as −
Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
Following example makes the use of cursor, which you will study in detail in a separate chapter.
DECLARE
CURSOR c_customers is
SELECT name FROM customers;
type c_list is varray (6) of customers.name%type;
name_list c_list := c_list();
counter integer :=0;
BEGIN
FOR n IN c_customers LOOP
counter := counter + 1;
name_list.extend;
name_list(counter) := n.name;
dbms_output.put_line('Customer('||counter ||'):'||name_list(counter));
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Customer(1): Ramesh
Customer(2): Khilan
Customer(3): kaushik
Customer(4): Chaitali
Customer(5): Hardik
Customer(6): Komal
PL/SQL PROCEDURES
we will discuss Procedures in PL/SQL. A subprogram is a program unit/module that performs a
particular task. These subprograms are combined to form larger programs. This is basically called the
'Modular design'. A subprogram can be invoked by another subprogram or program which is called
the calling program.
A subprogram can be created −
1 Declarative Part
It is an optional part. However, the declarative part for a subprogram does not start with
2 Executable Part
This is a mandatory part and contains statements that perform the designated action.
3 Exception-handling
This is again an optional part. It contains the code that handles run-time errors.
Creating a Procedure
A procedure is created with the CREATE OR REPLACE PROCEDURE statement. The simplified syntax for
the CREATE OR REPLACE PROCEDURE statement is as follows −
Where,
procedure-name specifies the name of the procedure.
[OR REPLACE] option allows the modification of an existing procedure.
The optional parameter list contains name, mode and types of the parameters. IN represents
the value that will be passed from outside and OUT represents the parameter that will be used
to return a value outside of the procedure.
procedure-body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone procedure.
Example
The following example creates a simple procedure that displays the string 'Hello World!' on the screen
when executed.
BEGIN
greetings;
END;
/
The above call will display −
Hello World
OUT
2 An OUT parameter returns a value to the calling program. Inside the subprogram, an
OUT parameter acts like a variable. You can change its value and reference the value
after assigning it. The actual parameter must be variable and it is passed by value.
IN OUT
An IN OUT parameter passes an initial value to a subprogram and returns an updated
3 value to the caller. It can be assigned a value and the value can be read.
The actual parameter corresponding to an IN OUT formal parameter must be a variable,
not a constant or an expression. Formal parameter must be assigned a value. Actual
parameter is passed by value.
DECLARE
a number;
b number;
c number;
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
IF x < y THEN
z:= x;
ELSE
z:= y;
END IF;
END;
BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
END;
When the above code is executed at the SQL prompt, it produces the following result −
Minimum of (23, 45) : 23
DECLARE
a number;
PROCEDURE squareNum(x IN OUT number) IS
BEGIN
x := x * x;
END;
BEGIN
a:= 23;
squareNum(a);
dbms_output.put_line(' Square of (23): ' || a);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Square of (23): 529
Positional notation
Named notation
Mixed notation
Positional Notation
In positional notation, you can call the procedure as −
findMin(a, b, c, d);
In positional notation, the first actual parameter is substituted for the first formal parameter; the
second actual parameter is substituted for the second formal parameter, and so on. So, a is substituted
for x, b is substituted for y, c is substituted for z and d is substituted for m.
Mixed Notation
In mixed notation, you can mix both notations in procedure call; however, the positional notation
should precede the named notation.
The following call is legal −
findMin(a, b, c, m => d);
However, this is not legal:
findMin(x => a, b, c, d);
PL/SQL FUNCTIONS
we will discuss the functions in PL/SQL. A function is same as a procedure except that it returns a value.
Therefore, all the discussions of the previous chapter are true for functions too.
Creating a Function
A standalone function is created using the CREATE FUNCTION statement. The simplified syntax for
the CREATE OR REPLACE PROCEDURE statement is as follows −
CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];
Where,
function-name specifies the name of the function.
[OR REPLACE] option allows the modification of an existing function.
The optional parameter list contains name, mode and types of the parameters. IN represents
the value that will be passed from outside and OUT represents the parameter that will be used
to return a value outside of the procedure.
The function must contain a return statement.
The RETURN clause specifies the data type you are going to return from the function.
function-body contains the executable part.
Example
The following example illustrates how to create and call a standalone function. This function returns
the total number of CUSTOMERS in the customers table.
We will use the CUSTOMERS table, which we had created in the PL/SQL Variables chapter −
Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
CREATE OR REPLACE FUNCTION totalCustomers
RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total
FROM customers;
RETURN total;
END;
/
When the above code is executed using the SQL prompt, it will produce the following result −
Function created.
Calling a Function
While creating a function, you give a definition of what the function has to do. To use a function, you
will have to call that function to perform the defined task. When a program calls a function, the
program control is transferred to the called function.
A called function performs the defined task and when its return statement is executed or when the last
end statement is reached, it returns the program control back to the main program.
To call a function, you simply need to pass the required parameters along with the function name and if
the function returns a value, then you can store the returned value. Following program calls the
function totalCustomers from an anonymous block –
When the above code is executed at the SQL prompt, it produces the following result −
Total no. of Customers: 6
Example
The following example demonstrates Declaring, Defining, and Invoking a Simple PL/SQL Function that
computes and returns the maximum of two values.
DECLARE
a number;
b number;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;
BEGIN
a:= 23;
b:= 45;
c := findMax(a, b);
dbms_output.put_line(' Maximum of (23,45): ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Maximum of (23,45): 45
DECLARE
num number;
factorial number;
BEGIN
num:= 6;
factorial := fact(num);
dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Factorial 6 is 720
Implicit cursors
Explicit cursors
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when
there is no explicit cursor for the statement. Programmers cannot control the implicit cursors and the
information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is associated
with this statement. For INSERT operations, the cursor holds the data that needs to be inserted. For
UPDATE and DELETE operations, the cursor identifies the rows that would be affected.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always has
attributes such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT. The SQL cursor has
additional attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed for use with
the FORALL statement. The following table provides the description of the most used attributes −
%FOUND
1
Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows or
a SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE.
%NOTFOUND
2 The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE
statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it
returns FALSE.
%ROWCOUNT
4
Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or
returned by a SELECT INTO statement.
Any SQL cursor attribute will be accessed as sql%attribute_name as shown below in the example.
Example
We will be using the CUSTOMERS table we had created and used in the previous chapters.
Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following program will update the table and increase the 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
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
6 customers selected
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+
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.
The syntax for creating an explicit cursor is −
CURSOR cursor_name IS select_statement;
Working with an explicit cursor includes the following steps −
CURSOR c_customers IS
SELECT id, name, address FROM customers;
OPEN c_customers;
CLOSE c_customers;
Example
Following is a complete example to illustrate the concepts of explicit cursors &minua;
DECLARE
c_id customers.id%type;
c_name customer.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
When the above code is executed at the 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
System-defined exceptions
User-defined exceptions
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
exception3-handling-statements
END;
Example
Let us write a code to illustrate the concept. We will be using the CUSTOMERS table we had created
and used in the previous chapters −
DECLARE
c_id customers.id%type := 8;
c_name customerS.Name%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN
When the above code is executed at the SQL prompt, it produces the following result −
No such customer!
Raising Exceptions
Exceptions are raised by the database server automatically whenever there is any internal database
error, but exceptions can be raised explicitly by the programmer by using the command RAISE.
Following is the simple syntax for raising an exception −
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;
You can use the above syntax in raising the Oracle standard exception or any user-defined exception. In
the next section, we will give you an example on raising a user-defined exception. You can raise the
Oracle standard exceptions in a similar way.
User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program. A user-
defined exception must be declared and then raised explicitly, using either a RAISE statement or the
procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.
The syntax for declaring an exception is −
DECLARE
my-exception EXCEPTION;
Example
The following example illustrates the concept. This program asks for a customer ID, when the user
enters an invalid ID, the exception invalid_id is raised.
EXCEPTION
WHEN ex_invalid_id THEN
dbms_output.put_line('ID must be greater than zero!');
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Enter value for cc_id: -6 (let's enter a value -6)
old 2: c_id customers.id%type := &cc_id;
new 2: c_id customers.id%type := -6;
ID must be greater than zero!
Pre-defined Exceptions
PL/SQL provides many pre-defined exceptions, which are executed when any database rule is violated
by a program. For example, the predefined exception NO_DATA_FOUND is raised when a SELECT INTO
statement returns no rows. The following table lists few of the important pre-defined exceptions −
Oracle
Exception SQLCODE Description
Error
PL/SQL Triggers
we will discuss Triggers in PL/SQL. 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 −
A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
A database definition (DDL) statement (CREATE, ALTER, or DROP).
A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).
Triggers can be defined on the table, view, schema, or database with which the event is associated.
Benefits of Triggers
Triggers can be written for the following purposes −
Creating Triggers
The syntax for creating a trigger is −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
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 −
When the above code is executed at the SQL prompt, it produces the following result −
Trigger created.
The following points need to be considered here −
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.
The 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
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 −
UPDATE customers
SET salary = salary + 500
WHERE id = 2;
When a record is updated in the CUSTOMERS table, the above create
trigger, display_salary_changes will be fired and it will display the following result −
Old salary: 1500
New salary: 2000
Salary difference: 500
PL/SQL Package
we will discuss the Packages in PL/SQL. Packages are schema objects that groups logically related
PL/SQL types, variables, and subprograms.
A package will have two mandatory parts −
Package specification
Package body or definition
Package Specification
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.
When the above code is executed at the SQL prompt, it produces the following result −
Package created.
Package Body
The package body has the codes for various methods declared in the package specification and other
private declarations, which are hidden from the code outside the package.
The CREATE PACKAGE BODY Statement is used for creating the package body. The following code
snippet shows the package body declaration for the cust_sal package created above. I assumed that we
already have CUSTOMERS table created in our database as mentioned in the PL/SQL -
Variables chapter.
DECLARE
code customers.id%type := &cc_id;
When the above code is executed at the SQL prompt, it prompts to enter the customer ID and when
you enter an ID, it displays the corresponding salary as follows −
Enter value for cc_id: 1
Salary: 3000
Example
The following program provides a more complete package. We will use the CUSTOMERS table stored in
our database with the following records −
Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 3000.00 |
| 2 | Khilan | 25 | Delhi | 3000.00 |
| 3 | kaushik | 23 | Kota | 3000.00 |
| 4 | Chaitali | 25 | Mumbai | 7500.00 |
| 5 | Hardik | 27 | Bhopal | 9500.00 |
| 6 | Komal | 22 | MP | 5500.00 |
+----+----------+-----+-----------+----------+
-- Removes a customer
PROCEDURE delCustomer(c_id customers.id%TYPE);
--Lists all customers
PROCEDURE listCustomer;
END c_package;
/
When the above code is executed at the SQL prompt, it creates the above package and displays the
following result −
PROCEDURE listCustomer IS
CURSOR c_customers is
SELECT name FROM customers;
TYPE c_list is TABLE OF customers.Name%type;
name_list c_list := c_list();
counter integer :=0;
BEGIN
FOR n IN c_customers LOOP
counter := counter +1;
name_list.extend;
name_list(counter) := n.name;
dbms_output.put_line('Customer(' ||counter|| ')'||name_list(counter));
END LOOP;
END listCustomer;
END c_package;
/
The above example makes use of the nested table. We will discuss the concept of nested table in the
next chapter.
When the above code is executed at the SQL prompt, it produces the following result −
Package body created.
PL/SQL Transactions
we will discuss the transactions in PL/SQL. A database transaction is an atomic unit of work that may
consist of one or more related SQL statements. It is called atomic because the database modifications
brought about by the SQL statements that constitute a transaction can collectively be either
committed, i.e., made permanent to the database or rolled back (undone) from the database.
A successfully executed SQL statement and a committed transaction are not same. Even if an SQL
statement is executed successfully, unless the transaction containing the statement is committed, it
can be rolled back and all changes made by the statement(s) can be undone.
Committing a Transaction
A transaction is made permanent by issuing the SQL command COMMIT. The general syntax for the
COMMIT command is −
COMMIT;
For example,
COMMIT;
Savepoints
Savepoints are sort of markers that help in splitting a long transaction into smaller units by setting
some checkpoints. By setting savepoints within a long transaction, you can roll back to a checkpoint if
required. This is done by issuing the SAVEPOINT command.
The general syntax for the SAVEPOINT command is −
SAVEPOINT < savepoint_name >;
For example
UPDATE CUSTOMERS
SET SALARY = SALARY + 1000;
ROLLBACK TO sav1;
UPDATE CUSTOMERS
SET SALARY = SALARY + 1000
WHERE ID = 7;
UPDATE CUSTOMERS
SET SALARY = SALARY + 1000
WHERE ID = 8;
COMMIT;
ROLLBACK TO sav1 − This statement rolls back all the changes up to the point, where you had marked
savepoint sav1.
After that, the new changes that you make will start.
DATE
TIMESTAMP
TIMESTAMP WITH TIME ZONE
TIMESTAMP WITH LOCAL TIME ZONE
The Interval data types are −
MONTH 01 to 12 0 to 11
HOUR 00 to 23 0 to 23
MINUTE 00 to 59 0 to 59
DATE
It stores date and time information in both character and number datatypes. It is made of information
on century, year, month, date, hour, minute, and second. It is specified as −
TIMESTAMP
It is an extension of the DATE data type. It stores the year, month, and day of the DATE datatype, along
with hour, minute, and second values. It is useful for storing precise time values.
1 ADD_MONTHS(x, y);
Adds y months to x.
2 LAST_DAY(x);
Returns the last day of the month.
3 MONTHS_BETWEEN(x, y);
Returns the number of months between x and y.
4 NEXT_DAY(x, day);
Returns the datetime of the next day after x.
5 NEW_TIME;
Returns the time/day value from a time zone specified by the user.
6 ROUND(x [, unit]);
Rounds x.
7 SYSDATE();
Returns the current datetime.
8 TRUNC(x [, unit]);
CURRENT_TIMESTAMP();
1
Returns a TIMESTAMP WITH TIME ZONE containing the current session time along with
the session time zone.
FROM_TZ(x, time_zone);
3
Converts the TIMESTAMP x and the time zone specified by time_zone to a TIMESTAMP
WITH TIMEZONE.
4 LOCALTIMESTAMP();
Returns a TIMESTAMP containing the local time in the session time zone.
SYSTIMESTAMP();
5
Returns a TIMESTAMP WITH TIME ZONE containing the current database time along with
the database time zone.
SYS_EXTRACT_UTC(x);
6
Converts the TIMESTAMP WITH TIMEZONE x to a TIMESTAMP containing the date and
time in UTC.
7 TO_TIMESTAMP(x, [format]);
Converts the string x to a TIMESTAMP.
8 TO_TIMESTAMP_TZ(x, [format]);
Examples
The following code snippets illustrate the use of the above functions −
Example 1
Output −
08/31/2012 5:25:34 PM
Example 2
Output −
31-08-2012 05:26:14
Example 3
Output −
8/31/2012 5:26:55.347000 PM
Interval Functions
S.No Function Name & Description
2 NUMTOYMINTERVAL(x, interval_unit);
Converts the number x to an INTERVAL YEAR TO MONTH.
3 TO_DSINTERVAL(x);
Converts the string x to an INTERVAL DAY TO SECOND.
4 TO_YMINTERVAL(x);
Converts the string x to an INTERVAL YEAR TO MONTH.
1. What is Tuple?
2. Define Database Model.
3. Differentiate between entity and entity set.
4. Difference between File organization and DBMS.
5. List Union compatible rules.
6. List Role of Database administrator.
7. What is Foreign Key.
8. Draw PL/SQL block of code and explain in short.
9. What are database languages list them with example.
10. Explain Views in oracle.
11. What is Tuple?
12. Define Database Model.
13. Differentiate between entity and entity set.
14. Difference between File organization and DBMS.
15. List Role of Database administrator.
16. List the types of Attributes.
17. Draw an ER diagram for a College.
18. What are database languages list them?
19. Write down advantages of DBMS
20. What are the disadvantages of DBMS.?
2. 5 questions of 7 Marks
3. 3 questions of 10 Marks
1. a) Explain Oracle Architecture.
b) Draw an E-R Diagram for College like organization.
4. a). Create a PL/SQL block of code to find total number of records in a table.
b). Write a query to Apply a check Constraint on product table so that all the product
number should
a. While loop
b. For loop
c. Simple loop
Q3- Write a program in PL/SQL to find the largest among three given numbers.
Q5- Write a program in PL/SQL to check whether the given character is vowel or not
Hint: vowel = a, e, i, o, u
Q.6- Write a PL/SQL block of code to retrieve record for a given key value of a table.
Q.7-Write a PL/SQL block of code to print grade for a given percentage using if...eslif...end if statement.
Q.11- Create a PL/SQL code of block to store radius and area of a circle in a table for the given radius
3,4,5,6,7
Q.13- Create a statement trigger applied on product table and store values in product_check table;
Q.14- Create a row level Trigger applied on product table and store values in product_check table.