Professional Documents
Culture Documents
CHAPTER 1
Chapter 2
Chapter 3
Page 1
Contents
CHAPTER 4
FUNCTIONS
FUNCTIONS.............................................................................................................51
SINGLE ROW FUNCTION.........................................................................................51
GROUP FUNCTIONS.................................................................................................54
Chapter 5
Chapter 6
Chapter 7
Introduction to PL/SQL
INTRODUCTION TO PL/SQL...................................................................................80
ADVANTAGES OF PL/SQL......................................................................................80
PL/SQL ARCHITECTURE........................................................................................80
PL/SQL BLOCK STRUCTURE..................................................................................81
NAMED AND ANONYMOUS BLOCK.........................................................................81
Page 2
Contents
CONDITIONAL AND ITERATIVE CONTROL ...............................................................82
IF THEN...........................................................................................................82
IF THENELSE...............................................................................................83
IF THENELSIF.............................................................................................83
LOOPEND LOOP.............................................................................................84
WHILELOOP....................................................................................................85
FORLOOP.........................................................................................................85
SQL WITHIN PL/SQL.............................................................................................86
WRITING A PL/SQL CODE......................................................................................86
COMPOSITE DATA TYPES........................................................................................87
PL/SQL RECORDS..................................................................................................87
RECORD ASSIGNMENT............................................................................................87
PL/SQL TABLES..................................................................................................88
Chapter 8
PL/SQL - II
CURSOR MANAGEMENT IN PL/SQL......................................................................92
IMPLICIT CURSOR...................................................................................................92
EXPLICIT CURSOR..................................................................................................92
USING CURSOR.......................................................................................................92
EXPLICIT CURSOR ATTRIBUTES...............................................................................94
FOR UPDATE CLAUSE WITHIN CURSOR............................................................94
WHERE CURRENT OF CLAUSE..........................................................................95
CURSOR WITH PARAMETER..................................................................................95
CURSOR FOR LOOP...........................................................................................96
CURSOR FOR LOOP USING A QUERY................................................................96
EXCEPTION, ERRORS, AND PL/SQL.......................................................................97
EXCEPTION HANDLING IN PL/SQL........................................................................97
EXCEPTION PROPAGATION....................................................................................100
Chapter 9
Advanced Pl/SQL
SUB-PROGRAMS IN PL/SQL.................................................................................105
ADVANTAGES OF SUB-PROGRAMS.......................................................................105
PROCEDURE..........................................................................................................105
CALLING A PROCEDURE.......................................................................................106
ACTUAL VS. FORMAL PARAMETER......................................................................106
ARGUMENT MODES..............................................................................................106
FUNCTIONS...........................................................................................................108
STORED PACKAGE................................................................................................109
ADVANTAGES OF PACKAGE...................................................................................110
CREATING A PACKAGE BODY:...............................................................................110
DROPPING PROCEDURES, FUNCTION AND PACKAGE............................................111
DATABASE TRIGGER.............................................................................................112
Chapter 10
Page 3
Contents
FUNCTIONS AND PROCEDURES OF UTL_FILE PACKAGE.....................................118
Chapter 11
Chapter 12
Using Lobs
LARGE OBJECTS (LOB).......................................................................................132
CREATING TABLE WITH LOBS..............................................................................132
INSERTING VALUES ON THE TABLE.......................................................................132
UPDATING LOB VALUES.......................................................................................133
DATA MANIPULATION IN LOBS...........................................................................133
WORKING WITH DBMS_LOB PACKAGE..............................................................134
Chapter 13
Collections in Oracle
COLLECTIONS.......................................................................................................139
NESTED TABLES...................................................................................................139
CREATING TABLE USING NESTED TABLE..............................................................139
DML OPERATIONS ON NESTED TABLE.................................................................140
NESTED TABLE IN PL/SQL..................................................................................140
VARRAYS............................................................................................................141
CREATING VARRAYS..........................................................................................141
DML OPERATIONS WITH VARRAYS....................................................................142
VARRAYS IN PL/SQL.........................................................................................142
SIMILARITIES AND DIFFERENCES BETWEEN NESTED TABLE AND VARRAYS.....143
Appendix A
Appendix B
Appendix C
Project
Page 4
Page No : 144
Page No : 145
Page No : 146
Page No : 149
Chapter 1
Snapshots
Page 5
Objectives
Page 6
Introduction to DBMS
A programmers productivity tool
Good User Interface
Powerful Database Structure
Advancement of Data Manipulations
Use of 4 GL Tools
A discipline towards data independence
Logical Data Independence
Physical Data Independence
Data View
External View
Conceptual View
Internal View
Concept of DBMS
A Database is a collection of interrelated data from which some information can be extracted. A
database is designed and built for a specific purpose, keeping in mind the needs of the
Page 8
Database Models
Hierarchical
Network
Relational
Hierarchical Model
This model was introduced in the Information Management System ( IMS ) developed by IBM
in 1968. This model is like a hierarchical tree structure, used to construct a hierarchy of records
in the form of nodes and branches. The data elements present in the structure have a ParentChild relationship. A parent unit may have many child units, but a child is restricted to have only
one parent. This leads to the repetition of same child record for different parents.
The drawbacks of this model are:
1. The hierarchical structure is not flexible enough to represent all the relationship proportions
which occur in the real world.
2. It can not demonstrate the over all data model for the enterprise because of the nonavailability of actual data at the time of designing the data model.
3. It can not represent the Many-to-Many relationship.
4. The hierarchical model is used only when the concerned data has a clearly hierarchical
character with a single root, for example DOS directory structure.
Network Model
It is improvement on the hierarchical model. Here multiple parent-child relationships are used.
Rapid and easy access to data is possible in this model due to multiple access paths to the data
elements.
Transaction is maintained using pointers and tracing the pointers is the drawback of this design.
Relational Model
Data is organized in terms of rows and columns in a table known as relations.
The position of a row in a table is of no importance.
The intersection of a row and column must give a single value and not a set of values.
All values appearing in the columns are derived from the underlying schema.
Row must be unique.
Column name must be unique.
All column values are atomic.
Page 9
Sname
Agarwal
Patni
Chandra
Keshav
Sstatus
15
20
25
15
SCity
Delhi
Pune
Mumbai
Patna
Parts
Pcode
P01
P02
P03
P04
Pname
Screw
Nut
Bolt
Nut
Weight
8
16
20
16
Pcity
Delhi
Pune
Mumbai
Patna
Shipment
Scode
S01
S01
S02
S02
S03
Pcode
P01
P02
P03
P04
P01
Qty
150
200
250
100
300
Consider the tables shown in the sample database. In table Shipment, each supplier status has a
unique supplier code which uniquely identifies the entire row of the table and exactly one name,
and city. Likewise each part has a unique Pcode and exactly one name, size and city and at any
given time on more than one shipment exists for a given supplier/part combination.
The term Relation is used to describe these tables, which is more precise way of defining than
the traditional data processing term File or Table. Rows of such table are referred to as Tuples,
again a more precise definition than rows or records and columns are referred to as Attribute. In
relational data structure is that association between tuples are represented solely by data values in
columns.
External View
Conceptual View
Internal View
User Level
Admin Level
Hardware Level
Mapping to achieve logical
Mapping to achieve physical
Page 10
data independence
data independence
Information Representation
Guaranteed Access
Systematic Treatment of null values
Database Description rule
Comprehensive Data Sub-language
View Updating
High Level Insert, Update and Delete
Physical Data Independence
Logical Data Independence
The Distribution rule
Non-subversion
Integrity rule
E.F. Codd formulated 12 rules for RDBMS in 1970. In addition to the 12 rules, there exists a
rule, called rule ZERO, which states:
A relational system must be able to manage databases entirely through its relational capabilities.
Any DBMS that advices users to the some non-relational methods to achieve acceptable
performance should be interpreted as an apology by the vendor.
Information Representation
In the relational model all the information is explicitly and logically represented by the data
values in the tables. This means that even such information as table, view, column names etc.
Page 11
Guaranteed Access
This rule refers to the fact that the table can be taken as a storage structure and at the intersection
of each column and row there will necessarily be only one value of data (or null). Every value of
data must be logically addressable by using a combination of table name, primary key value and
column name.
Systematic Treatment of null values
In database management system null values are supported for the representation of missing and
in-applicable application. This support for null values must be consistent throughout the DBMS,
an independent of data types ( for example, a null value in Char field must mean the same as in
an Integer field ).
Database Description rule
A description of the database is stored and maintained the form of tables as is done while
defining the data. This allows the uses with appropriate authority to query such information in
same ways and using the same languages as they would any data in the database. This implies
that a data dictionary should be present within the RDBMS that is constructed of tables and / or
views that can be examined using the SQL.
Comprehensive Data Sub-language
The RDBMS must be completely manageable through its own extension of SQL, although some
systems still support SQL like language (e.g. INGRESS support QUEL). The SQL should
support data definition, views, data manipulation, integrity constraints, authorization, and
transaction boundary.
View Updating
It is a myth that all views that can be updated in theory, can also be updated by the system itself.
Though it is possible to create views with all sort of aggregate and virtual columns, it is
obviously not possible to update through some of them.
High Level Insert, Update and Delete
An RDBMS must do more than just be able to retrieve relational data sets. It has to be capable of
inserting, updating and deleting data as a relational set. A database can not be called relational, if
it uses a single record at time procedural technique when it comes to manipulating the data.
Physical Data Independence
User access to database, via monitors or application programs, must remain logically consistent
even when changes to the storage representation, or access methods to the data are changed.
Logical Data Independence
Application programs must be independent of the changes made to the base tables. This rule
allows many types of database design changes to be made dynamically, without the users being
Page 12
Database Designing
Requirement, formulation and analysis
Collection and documentation of requirement
Analysis of requirement
Conceptual design
Data Modeling
1st Level ER (Entity-Relationship) Modeling
nd
2 Level Normalization
Physical Model
Requirement, formulation and analysis
The objective of this phase to answer the following question:
What are user views of the data (Present and Future)?
What data elements are required in these user views?
What are the entities and their primary keys?
What are the operational requirements regarding security, integrity and response time?
Conceptual Design
The major step in conceptual design is to identify the entities and relationships that reflect the
organizations data. The objective of this step is to specify the conceptual structure of the data
and is often referred to as data modeling. The ER model, with an emphasis on the top-down
approach.
Data Modeling
Data modeling is achieved in two levels; the 1 st level builds the conceptual model of the data,
using ER modeling. The 2nd level organizes this model better, by removing redundancies, through
a process called normalization. The normalized model is then converted into the physical
database.
Physical Model
Page 14
Name
Introduction to RDBMS and Oracle
You create a physical model by using the logical model to assist in creating a database and
database objects to represents to entities and relationships. In the physical model, each entity
becomes a table, and attributes of the entity become columns of the table. The relationship
between the entities is part of one or more constraints between the tables. Physical
implementation might require you to combine, separate, or create completely new entities in
order to best realize the logical model. The unique identifiers of an entity become the primary
key of the table. You may create stored procedures, functions and triggers to enforce business
rules.
ER Diagram
Entity Relationship modeling is a technique for analysis and logical modeling of the system data
requirements. It uses three basic concepts, entities, their attributes and the relationship that exists
between the entities. It uses graphical notation for representing these.
Graphical notation for ER diagram
NAME
SYMBOL
Entity
Attribute
Relationship
FUNCTION
Data object in the system
uniquely identifiable by
identifier has attributes that
describe it.
Describes an entity
Relation
Entity
An entity is an object, place, person, concept, activity about which an enterprise records data. It
is an object which can have instances or occurrences. Each instance should be capable of being
uniquely identified. Each entity has certain properties or attributes associated with it and
operation applicable to it. Entity type and entity instance are two important term related to
entities. An entity type is a set of things which shares common properties. An entity type is
usually denoted in upper case. An entity instance is a specific individual thing. An entity instance
is usually denoted in lower case.
Example of entity type: STUDENT COURSE, COURSEWARE DEVELOPMENT TEAM etc.
Example of entity instance: sudipta, physics etc.
Attributes
Attributes are data element that describes an entity. If the attribute of an entity has more
attributes that describe it, then it is not an attribute of that entity, but another entity. Attributes can
either be listed next to the entities, or placed in circle and attached to the entity. Identifier is one
or more attributes of an entity or relation, whose value uniquely identifies the entities or
relationships.
Page 15
Page 16
Degree of relationship
ONE to ONE (1:1)
ONE to MANY(1:N)
MANY to MANY(N:N)
The degree of relationship indicates the link between two entities for a specified occurrence of
each. The degree of relationship is also called cardinality.
ONE to ONE
This relationship is one in which each occurrence of one entity is represented by single
occurrence in another entity. For example, consider an individual and that individuals social
security number: One person can have only one social security number, and a social security
number can belong to only one person.
Person
ONE to MANY
This relationship is one in which an occurrence of one entity may be represented by many
occurrence in another entity. An example is department and employees: One department has one
or more employees, and an employee belongs to only one department.
Department
Employee
MANY to MANY
This relationship in which an occurrence from one entity may be represented by one or more
occurrence in another entity, and an occurrence from second entity may be represented by one or
more occurrence in the first entity. The relationship between Doctor and Patient is an example: A
patient can visit many doctors, and a doctor can have many patients.
Doctor
Patient
Note: MANY to MANY relationship should not exists in RDBMS because they can not be
properly joined to represent a single row correctly. To solve this, create another entity that has a
ONE to MANY relationship with the first entity and a ONE to MANY relationship with the
second entity.
When you have established the relationship between entities, it is time to normalize the design.
Page 17
Normalization
Refinement of the ER Model.
Segregation of data over many entities or tables.
Normalized model converted to physical database tables.
Normalization is the process of refining the data model built by the ER Diagram. The
normalization technique, logically groups the data over a number of tables, with minimum
redundancy of data.
The goal of the relational data base design is to generate a set of relation scheme that allows us to
information with minimum redundancy of data and allow us to retrieve information easily and
efficiently.
The first step towards normalization is to convert the ER model into tables or relations. The next
step is to examine the tables for redundancy and if necessary, change them to non-redundant
forms. This non-redundant model is then converted to a database definition.
Supplier
Name
Agarwal
Patni
Chandra
Keshav
Bhushan
Menon
Supplier
Status
15
20
25
15
25
15
City
Supplier
Delhi
Pune
Mumbai
Patna
Kolkata
Guahati
Part
Code
101
102
103
102
104
102
Part
Name
Screw
Nut
Bolt
Nut
Bolt
Nut
500
250
250
300
50
200
Kolkata
Meerut
Ranchi
Silvasa
Pune
Patna
Page 18
Steps in normalization
First Normal Form (1NF)
Identify a repeating fields
Remove repeating groups to a separate table
Identify the keys for the table
Key the parent table is brought as part of the concatenated key of the second table
Second Normal Form (2NF)
Check if all fields is dependent on the whole key
Remove fields that depend on part of the key
Group partially-dependent fields as a separate table
Name the tables
Identify key(s) to the table(s)
Third Normal Form(3NF)
Remove fields that
Depend on other non-key attribute
Can be calculated or derived from logic
Group independent fields as separate tables, identify the key and name of the table
Invdate
12/08/97
12/08/97
16/08/97
16/08/97
16/08/97
Ordno
1
2
1
1
2
Chlno
1
1
1
1
1
Custno
C1
C1
C4
C1
C1
Custnm
Ashoke
Ashoke
Vipul
Ashoke
Ashoke
Itno
I1
I2
I3
I8
I2
Itdesc
Pepsi
Butter
Bread
Biscuit
Butter
Qty
2
1
1
2
4
Rate
8
22
12
22
22
Dis
Nil
Nil
Nil
Nil
Nil
Inval
16
22
12
44
88
Page 19
Page 20
Invdate
12/08/97
12/08/97
16/08/97
16/08/97
16/08/97
Ordno
1
2
1
1
2
Chlno
1
1
1
1
1
Custno
C1
C1
C4
C1
C1
Custnm
Ashoke
Ashoke
Vipul
Ashoke
Ashoke
Inval
16
22
12
44
88
Invoice Items
Invno
112
112
113
114
114
Itno
I1
I2
I3
I8
I2
Itdesc
Pepsi
Butter
Bread
Biscuit
Butter
Qty
2
1
1
2
4
Rate
8
22
12
22
22
Dis
Nil
Nil
Nil
Nil
Nil
Invdate
12/08/97
12/08/97
16/08/97
16/08/97
16/08/97
Ordno
1
2
1
1
2
Chlno
1
1
1
1
1
Custno
C1
C1
C4
C1
C1
Custnm
Ashoke
Ashoke
Vipul
Ashoke
Ashoke
Invoice Items
Invno
112
112
113
114
114
Itno
I1
I2
I3
I8
I2
Qty
2
1
1
2
4
Dis
Nil
Nil
Nil
Nil
Nil
Page 21
Inval
16
22
12
44
88
Itdesc
Pepsi
Butter
Bread
Biscuit
Butter
Rate
8
22
12
22
22
Invdate
12/08/97
12/08/97
16/08/97
16/08/97
16/08/97
Ordno
1
2
1
1
2
Chlno
1
1
1
1
1
Custno
C1
C1
C4
C1
C1
In_val
16
22
12
44
88
Customer Table
Custno Custnm
C1
Ashoke
C4
Vipul
Invoice Items
Invno
112
112
113
114
114
Itno
I1
I2
I3
I8
I2
Qty
2
1
1
2
4
Dis
Nil
Nil
Nil
Nil
Nil
Page 22
Itdesc
Pepsi
Butter
Bread
Biscuit
Butter
Rate
8
22
12
22
22
Varchar2(40)
Address_Type
Varchar2(12)
Varchar2(12)
Number(6)
Varchar2(40)
Varchar2(40)
Varchar2(5)
Now that the Address_Type is defined, it can be used in number of tables where addresses need
to be stored. This small example shows the reusability of objects.
Page 23
Features of Oracle
High transaction processing performance All the facilities for transaction and its recovery in
case of any failure are supported in Oracle for better performance of transaction processing.
Industry accepted standards All the recent technologies like object oriented technology and
distributed data processing are supported in Oracle .
Manageable Security Very strong security provisions are there inside Oracle to guard against
malicious users.
Large database support In supporting large database, Oracle is more reliable compared to any
other database packages.
Concurrent Processing More than one user can work simultaneously on the same database
without any interference.
Client/Server environment It supports client server technology i.e. the server contains the
main database and clients ( users ) can access the database to fetch and manage only that data for
which they are given the authorization.
Distributed database system Oracle supports distributed environment i.e. applications made
on different platforms and in different environments can exchange the data with the common
interface language called Interface Definition Language ( IDL ).
Portability Runtime models made inside Oracle environment can run without any changes on
other compatible platforms easily.
Compatibility It is compatible with all sorts of front ends although, Oracle has its own front
end but still Oracle database can be used with other front ends like Visual Basic, VC++ etc.
easily.
Page 24
Chapter 2
Snapshots
Introduction to SQL
Oracle Data Types
Starting SQL* Plus editor
Operators and Expressions
Querying DataBase Tables
RollUp Operation - Getting sub totals
Cube Operation - Getting cross tabs
Page 25
Introduction to SQL
Objectives
Page 26
Introduction to SQL
Introduction to SQL
BLOB
CLOB
BFILE
NUMBER
DATE
Page 27
RAW
LONG RAW
Introduction to SQL
Character Datatypes
Character datatypes are used to store alphanumeric data. When you define character data in
Oracle , you specify a length for the column, which is the maximum width of the column. In
Oracle you can have different type of datatype to store alphanumeric value:
CHAR(<size>) The CHAR datatype is a fixed-length character string having a maximum
length of size. Data stored in CHAR column is space-padded to fill the maximum length. The
size can range from a minimum of 1 to maximum of 2000 characters.
When you create a column using the CHAR datatype, the database will ensure that all data
placed in this column has the defined length. If data is shorter than the defined length, it is spacepadded on right to the specified length. If the data is longer, an error is raised.
VARCHAR(<size>) A VARCHAR datatype in Oracle is synonymous with the VARCHAR2
datatype.
VARCHAR2(<size>) The VARCHAR2 datatype is a variable-length alphanumeric string
having a maximum length of size bytes. VARCHAR2 variables only require the amount of space
needed to store the data. VARCHAR2 database columns can store up to 4000 bytes and
VARCHAR2 variables up to 32676 bytes. An empty VARCHAR2(2000) column takes up as
much room in the database as an empty VARCHAR2(2) column.
The default size of the CHAR datatype is 1. In VARCHAR2, you must always specify the size.
LONG The LONG datatype is a legacy datatype that will no longer be supported in the future.
It has been deprecated in favor of large object datatype. A LONG datatype column is of variable
length and can take up to 2GB. There are many restriction on the use of LONG columns and
variables. LONG columns can not appear in Where clause, Group By clause, Order By clause or
with the Distinct operator in Select statements.
Numeric Datatype
Numeric datatype are used to store negative and positive integers: fixed-point and floating-point
numbers with a precision of up to 38 digits. Specifying a number outside this range will raise an
error.
Number(<p>,<s>) The number datatype stores numbers with a precision of p digits and a
scale of s digits. The precision and the scale value are optional. Specifying the scale and
precision does not force all inserted values to be a fixed length. If the number exceeds the
precision, however, an Oracle error is returned. If the number exceed the scale, it is rounded to
the scale. If the scale is negative, the number is rounded to the left of the decimal. Basically, a
negative scale forces s number of zeros just to the left of the decimal.
Page 28
Introduction to SQL
Datatype
Number
Number(8)
Number(6)
Number(9,1)
Number(9,3)
Number(7,2)
Number(5,-2)
Number(5,-2)
Number(5,-4)
Number(*,1)
Stored Value
1234567.89
1234568
Numeric Error
1234567.9
Numeric Error
Numeric Error
1234600
1234500
1230000
1234567.9
Date Datatype
The Date datatype is used to store date and time information. This datatype can be converted to
other forms for viewing, and it has number of special functions and properties that makes date
manipulation and calculation simple. The Date datatype occupies a storage space of 7 bytes. The
following information is contained within each date datatype:
Century
Year
Month
Day
Hour
Minute
Second
The default format for Oracle Date datatype is DD-Mon-YY; this is the format shown whenever
a date is selected within SQL *Plus.
LOB Datatype
Large object datatypes store blocks of unstructured data, such as a binary file, a picture, or an
external file. A LOB can store data up to 4GB. The data may be stored in the database or in an
external file. LOB data maniputaion is done using the DBMS_LOB package.
Datatype Purpose
BLOB
Binary Large Object
CLOB
Character Large Object
BFILE
Binary File
Description
Can store up to 4GB of binary data in the database.
Can store up to 4GB of character data in the database.
Oracle converts the data into Unicode format and stores it
in the database.
Stores binary data up to 4GB in operating system files
outside of the database. The size of the binary file must
conform with operating system limitations on file size. A
BFILE column stores a file locator that points to an
external file containing the data. BFILE datatypes are
read-only; You can not modify them.
Page 29
Introduction to SQL
Note : There may be more than one LOB datatype column in a table, but there can be only one
LONG datatype column.
Other Datatypes
Oracle has RAW datatypes in addition to the character, numeric and date datatypes.
RAW RAW is unstructured, binary data that is not interpreted by the database. RAW columns
can be up to 2000 bytes long.
LONGRAW Like the LONG datatype, LONGRAW is a legacy datatype that has been
deprecated in favor of the LOB datatypes BLOB or BFILE. LONGRAWs can store up to 2GB of
unstructured data. LONGRAW data cannot be indexed, but RAW data can be indexed.
Literals
Literals are values that represent a fixed value. There are three types of literals values:
Text
Integer
Number
Text literals must be enclosed in single quotes; integer and number literals need not be. You can
use literals within many of the SQL functions, expressions and conditions.
Text The text literal must be enclosed in single quotation marks. Any character between the
quotation marks is considered part of the text value. Oracle treats all text literals as though they
were CHAR datatypes. The maximum length of a text literal is 2,000 characters. Single quotation
marks can be included in the literal text value by preceeding it with another single quotation
mark.
Here are some examples:
The quick brown fox
That mans suit is black
And I quote:This will never do.
Integer Integer literals can be any number of numerals, excluding a decimal separator and up
to 38 digits long.
Examples follow:
24
-456
Number Number literals can include scientific notation, as well as digits and the decimal
separator.
Here are some example:
24
-345.65
Page 30
Introduction to SQL
23E10
Step II : Double click or press <Enter> on the short cut shown above.
Step III : Provide the User Name, Password and Connect String in the dialog shown. The
Connect String is nothing but the Database name.
Page 31
Introduction to SQL
After providing the User Name, Password and Connect String click on the OK button. If all the
information you have provided is correct then you will get the following screen.
Column
names
DEPTNO
DNAME
LOC
Type(Size)
NUMBER(2)
VARCHAR2(20)
VARCHAR2(10)
Description
Department number
Department name
Location of the department
Page 32
Constraints
Primary Key
NOT NULL
NOT NULL
Introduction to SQL
Column
names
EMPNO
ENAME
JOB
MGR
HIREDATE
SAL
COMM
DEPTNO
Type(Size)
Description
NUMBER(4)
VARCHAR2(20)
VARCHAR2(10)
NUMBER(4)
DATE
NUMBER(9,2)
NUMBER(7,2)
NUMBER(2)
Employee number
Employee name
Designation
Respective managers EMPNO
Date of Joining
Basic Salary
Commission
Department number
Constraints
Primary Key
NOT NULL
NOT NULL
NOT NULL
NOT NULL
NOT NULL, Foreign
Key
Page 33
Introduction to SQL
Arithmetic Operators
Arithmetic operators operate on numeric datatypes.
Operator Purpose
+Unary operators: Use to represent positive or negative data item. For
positive items, the + is optional.
+
Addition: Use to add two data items or expressions.
Subtraction: Use to find the difference between two data items or
expressions.
*
Multiplication: Use to multiply two data items or expressions.
/
Division: Use to divide a data items or expression with another.
Example
-234.45
3+7
7-5
5 * 10
8/4
Concatenation Operator
This operator is used to concatenate or join two character ( text ) strings. The result of
concatenation is another character string. If one of the strings is NULL, the result is also NULL.
Concatenating a zero-length string( ) with another string results in a string, not a NULL. Two
vertical bars ( || ) are used as the concatenation operator. Here are a few examples:
Comparison Operator
Comparison operators compare two values or expression and give a Boolean result of TRUE,
FALSE, or NULL. Comparison operators are mainly used in the WHERE clause of the SQL
statement.
Operator
=
Purpose
Example
SELECT * FROM emp WHERE
ename=SCOTT;
SELECT * FROM emp WHERE
ename!=SCOTT;
Equality test
!=
<>
^=
<
Inequality test
>
>=
Page 34
Introduction to SQL
sal>=2000;
SELECT * FROM emp WHERE
sal<=2000;
<=
Operator
[NOT] IN
Purpose
Example
Equal to any member of test. If NOT is SELECT * FROM emp WHERE
used, evaluates to TRUE if the value is not deptno IN (10,20);
in the member list.
SELECT * FROM emp WHERE
deptno NOT IN (10,20);
Compares a value to each value in a list or SELECT * FROM emp WHERE
return by a query. Must be preceded by =, ! sal<=ANY(SELECT sal FROM
=, <, >, <=, >=. Evaluates to FALSE if the emp WHERE deptnp=10);
query returns no rows.
Compares a value to every value in a list or SELECT * FROM emp WHERE
return by a query. Must be preceded by =, ! sal<=ALL(500, 1200, 800);
=, <, >, <=, >=. Evaluates to TRUE if the
query returns no rows.
TRUE if value greater than or equal to a SELECT * FROM emp WHERE
and less than or equal to b. If NOT is used, sal BETWEEN 2000 AND 5000;
the result is the reverse.
TRUE is a sub query returns at least one SELECT * FROM emp WHERE
row.
deptno=10
AND
EXISTS(SELECT COUNT(*)
FROM emp WHERE deptno=10
GROUP BY deptno HAVING
COUNT(*) > 3);
Used for pattern matching. Wild card SELECT ename FROM emp
character % is used to match any string of WHERE ename=S%;
length zero or more characters and _ is used
to match any single character. Escape is
used to interpret % or _ literally.
The only operator used to test for NULL SELECT * FROM emp WHERE
values.
comm. IS NULL;
ANY
SOME
ALL
[NOT]
BETWEEN
a AND b
[NOT]
EXISTS
a [NOT]
LIKE b
[ESCAPE
char]
IS [NOT]
NULL
Logical Operators
Logical operators are used to combine the results of two comparison conditions to produce a
single result or to reverse the result of a single comparison.
Operator Purpose
NOT
Used to reverse the result. Evaluates to TRUE if
the operand is FALSE. Evaluates to FALSE if the
operand is TRUE. Returns NULL if the operand
is NULL.
AND
Evaluates to TRUE if both operands are TRUE.
Evaluates to FALSE if either operand is FALSE.
Otherwise returns NULL.
OR
Evaluates to TRUE if either operands are TRUE.
Page 35
Evaluates to FALSE if both operands are FALSE.
Otherwise returns NULL.
Example
SELECT * FROM emp
WHERE NOT (sal<1000);
SELECT * FROM emp
WHERE deptno=10 AND sal
>=2000;
SELECT * FROM emp
WHERE deptno=10 OR
deptno=30;
Introduction to SQL
Set Operators
Set operators are used to combine queries: Queries that combine the results of two queries. The
number of columns selected in both queries must be the same.
Operator
UNION
Purpose
Example
Returns all rows from either queries ; no SELECT job FROM emp
duplicate rows.
WHERE deptno=20 UNION
SELECT job FROM emp
WHERE deptno=30;
INTERSECT Returns distinct rows that are returned by both SELECT job FROM emp
the queries.
WHERE
deptno=20
INTERSECT SELECT job
FROM
emp
WHERE
deptno=30;
MINUS
Returns distinct rows that are returned by the 1st SELECT job FROM emp
query but not returned by the second.
WHERE deptno=20 MINUS
SELECT job FROM emp
WHERE deptno=30;
Expressions
An expression is a combination of one or more values, operators, and SQL functions that
evaluate to a value. An expression generally assumes the datatype of its components.
Expressions can appear in the following clauses:
Page 36
Introduction to SQL
Example:
SELECT * FROM emp;
In the above statement the * indicates all the columns.
SELECT empno, ename FROM emp;
The above statement will display all employees code and their name.
Conditional Retrieval of Rows
The WHERE clause is used along with the SELECT statement to specify the condition. When a
WHERE clause is present, the database program goes though the entire table one row at a time
and examines each row to determine if the condition is TRUE with respect to row. It is not
necessary for the columns used in the where clause to be present among those selected for
output.
Example:
SELECT * FROM emp WHERE deptno=20;
This will display all the details of employees belonging to the department 20.
SELECT empno,ename FROM emp WHERE deptno=20 OR deptno=30;
Displays codes and names for all the employees for department 20 as well as 30.
SELECT empno,ename FROM emp WHERE deptno=20 AND job=CLERK;
Displays codes and names for all those employee of department 20 whose designation is
CLERK.
SELECT empno,ename FROM emp WHERE deptno!=20;
Displays codes and names for all the employees except department 20.
SELECT empno,ename FROM emp WHERE IN(20,30);
Displays codes and names for all the employees for department 20 as well 30.
SELECT ename,sal FROM emp WHERE sal BETWEEN 1000 AND 5000;
Displays names and salary for the employees whose salary is ranges between 1000 to 5000.
DISTINCT clause with SELECT
The DISTINCT clause is used with SELECT to suppress duplicate values if any in a column.
Example:
SELECT DISTINCT job FROM emp;
This will displays the different job category available in the emp table.
Page 37
Introduction to SQL
Example:
SELECT ename,comm FROM emp WHERE comm. IS NULL;
Displays names and commisions for all the employees who are not eligible for getting
commission.
SELECT ename,comm FROM emp WHERE comm. IS NOT NULL;
Displays names and commisions for all the employees who are eligible for getting commission.
Matching a pattern from a table
The LIKE operator is used only with CHAR and VARCHAR2 to match a pattern. Wild card
character % is used to match any string of length zero or more characters and _ is used to match
any single character.
Example:
SELECT ename FROM emp WHERE ename LIKE S%;
Displays names of those employees whose name starts with S ( not s )
SELECT ename FROM emp WHERE ename LIKE _____;
Displays names of those employees whose name have exactly 5 characters
Using expression with columns
Example:
SELECT ename, sal, sal*.1 FROM emp;
Displays names, salary and PF amount of all the employees ( PF is calculated as 10% of salary).
We can provide an alias to the column sal*.1 as PF
SELECT ename, sal, sal*.1 PF FROM emp;
Page 38
Introduction to SQL
Page 39
Introduction to SQL
MAX : Determines the largest of all selected values of a columns. Note that DISTINCT and
ALL have no effect.
Example:
SELECT MAX( sal ) FROM emp;
Display the maximum salary payable to employee working with the company.
MIN : Determines the smallest of all selected values of a columns. Note that DISTINCT and
ALL have no effect.
Example:
SELECT MIN( sal ) FROM emp;
Display the minimum salary payable to employee working with the company.
AVG : Determines the average of all selected values of a columns.
Example:
SELECT AVG( sal ) FROM emp;
Display the average salary payable to employee working with the company.
Grouping the result of a query
The GROUP BY Clause is used to divide the rows in a table into smaller groups
The GROUP BY Clause is used with SELECT clause
SQL groups the result after it retrieves the rows from a table
Conditional retrieval of rows from a grouped result is possible with the HAVING clause
Example:
SELECT deptno,count( * ) FROM emp GROUP BY deptno;
Display the department number and number of employees in each department.
SELECT deptno, AVG(sal) FROM emp GROUP BY deptno HAVING COUNT(*) >3;
Display average salary for all departments employing more than five people.
Page 40
Introduction to SQL
Page 41
Chapter 3
Snapshots
Page 42
Objectives
Page 43
EQUI Join
When two tables are joined together using equality of values in one or more columns, they make
an Equi join. The prefixes are utilized to prevent ambiguity and the WHERE clause specifies the
columns being joined.
Example:
SELECT empno, ename, emp.deptno, dname
FROM emp, dept WHERE emp.deptno= dept.deptno ;
Displays the employee numbers, employee names, department numbers and department names.
CARTESIAN Join
A Cartesian join occurs when data is selected from two or more tables and there is no common
relation specified in the WHERE clause. If you do not specify a join condition for the tables
listed in the FROM clause, Oracle joins each row from the first table to every row in the second
table. If the first table has three rows and the second table has four rows, the result will have
twelve rows.
Example:
Consider the following tables:
Tab1: Holds the principal amount.
Tab2: Holds year and rate of interests.
Tab1
PRINCIPAL
1000
2000
3000
Tab2
YEAR RATE
1
10
2
11
3
11.5
4
12
Finding the possible combinations of calculation of amount, a Cartesian join of the tab1 and tab2
is required. The formula for calculation of amount is Principal*(1+(rate/100))year.
Page 44
YEAR
1
1
1
2
2
2
3
3
3
4
4
4
RATE
10
10
10
11
11
11
11.5
11.5
11.5
12
12
12
principal*POWER(1+(rate/100),year)
1100
2200
3300
1232.1
2464.2
3696.3
1386.1959
2772.3918
4158.5876
1573.5194
3174.0387
4720.5581
OUTER Join
Sometime you might want to see the data from one table, even if there is no corresponding row
in the joining table. Oracle provides the outer join mechanism for this. The + symbol surrounded
by parentheses denotes an Outer join in the query. Enter (+) beside the column name of a table,
where may not be corresponding row. The Outer join operator (+) can appear only in the
WHERE clause. If there are multiple join conditions between the tables, the Outer join operator
used against all of the conditions.
Example:
SELECT empno, ename, dept.deptno, dname, loc
FROM emp, dept WHERE emp.deptno (+)= dept.deptno;
Displays the list of employees working in each department. Displays the department information
even if no employee belongs to that department.
Rules to place the (+) operator
Page 45
SELF Join
A Self join joins a table to itself. The table name appears in the FORM clause twice, with
different alias names. The aliases are treated as two different tables, and they are joined as you
would join any other tables.
Example:
EMP table:
EMPNO
7839
7566
7876
7934
ENAME
KING
JONES
ADAMS
MILLER
..
MGR
7839
7788
7782
Consider the emp table shown above. Primary key of the emp table is empno. Details of each
employees manager is another row in the emp table whose empno is stored in mgr column of
some other row. So every employee except PRESIDENT has their manager. Therefore mgr is a
foreign key that reference empno. To list out the names of the manager with the employee record
you have to join emp table with itself.
SELECT worker.ename , manager.ename Manager
FROM emp worker, emp manager WHERE worker.mgr=manager.empno;
Where worker and manager are two aliases for the emp table and acts as a pseudo table.
EMPNO
7839
7566
7876
7934
ENAME
KING
JONES
ADAMS
MILLER
..
MGR
EMPNO
7839
7788
7782
7934
7839
7788
7782
ENAME
KING
SCOTT
CLARK
MILLER
..
MGR
7566
7839
7782
ENAME
SCOTT
FORD
ALLEN
WARD
JAMES
TURNER
MARTIN
MILLER
ADAMS
JONES
CLARK
BLAKE
SMITH
Manager
JONES
JONES
BLAKE
BLAKE
BLAKE
BLAKE
BLAKE
CLARK
SCOTT
KING
KING
KING
FORD
13 rows selected.
Description
Returns all unique rows selected by either query
Returns all rows, including duplicates selected by either queries
Returns unique rows selected by the first query but not the rows selected
by the second query
The two select statements may not contain an ORDER by clause, however, the final result of
the entire UNION operation can be ordered.
The number of columns retrieved by first select must be equal to number of columns
retrieved by second select.
The data types of columns retrieved by the select statements should be same.
The optional ORDER BY clause differs from the usual ORDER BY clause in a SELECT
statement because the columns used for ordering must be referenced by a number rather than
name. The reason that the columns must be referenced by number is the SQL does not
require that the column name retrieved by first select be identical to the columns names
retrieved by second select.
Sub Queries
A subquery is a query within a query. Typically, subqueries appear in the WHERE clause of the
SELECT statement. Oracle supports subqueries in the FROM clause and the HAVING clause. A
subquery answers the queries that have multiple parts; the subquery answer one part of the
question and the parent query answers the other part. You can have any number of subqueries
nested; Oracle does not place a limit.
Page 48
Correlated Subqueries
Oracle performs a correlated subquery when the subquery references a column from a table
referred to in the parent statement. A correlated subquery is evaluated once for each row
processed by the parent statement.
Example 1:
Considering the emp table and the incr table list the employee number and names, who have got
more than one increments.
SQL> select * from incr;
EMPNO
AMT
-------------- -----------7369
500
7499
300
7369
400
7654
600
7698
450
7499
340
6 rows selected.
Correlated,
Same column
Page 49
Page 50
Chapter 4
Snapshots
Functions
Single Row Function
Arithmetic Functions
Character Functions
Date Functions
General Functions
Group Functions
Page 51
Functions
Objectives
Page 52
Functions
Functions
Functions are programs that take zero or more arguments and return a single value. There are two
significant classes of function:
To test all the following functions you can work with the table called dual. This table has only
one column in its structure. The column name is dummy and it has only one row with a value x.
Arithmetic functions
ABS (x)
Absolute Value of x
CEIL (x)
FLOOR (x)
MOD (x,y)
POWER (x,y)
SIGN (x)
SQRT (x)
Character functions
Page 53
Functions
CHR (x)
ASCII (c)
INITCAP (s)
LOWER (s)
UPPER (s)
LPAD (s, x)
RPAD (s, x)
LTRIM (s)
RTRIM (s)
LENGTH (s)
Length of s
Date Functions
SYSDATE
ADD_MONTHS(d,n)
Returns the date of the last day of the month specified. The result will
be a date
NEXT_DAY(d,day)
Returns the date of next specified day of the week after the date d
Conversion functions
Page 54
Functions
TO_CHAR (number,
format)
Other functions
DECODE (s, search1,
Compares s with search1, search2, etc. and returns the corresponding
result1, search2, result2) result when there is a match.
NVL (s, expression)
USER
Page 55
Functions
Group Functions
Group function dont know how many arguments they will have to process until all the data
extracted and grouped into categories. To use an aggregate function, a GROUP BY clause must
be added to the SELECT statement. Group function do not process a null value and do not return
a null value.
AVG (col)
MAX (col)
MIN (col)
SUM (col)
COUNT (columns)
Page 56
Chapter 5
Snapshots
Page 57
Objectives
Page 58
Creating Tables
Syntax:
CREATE TABLE <table_name>
(
<column_name>
<datatype(size)>,
..
);
Example:
Create a table ITEM_MAST, which has the following columns:
Column Name
ITNO
ITNM
CLASS
QOH
RATE
Type
Number
Varchar2
Char
Number
Number
Size
4
20
1
5
8,2
Description
Item Number
Item Name
Category of item
Quantity On Hand
Item Unit Price
Page 59
Check
NOT NULL
Unique
Primary key
Foreign key
Default
Check Constraints
Check constraints require a specific Boolean condition on a column or set of columns to be true
or at least one of the column values to be NULL. Check constraints are enforce simple business
rules about the content of data in your tables. Check constraints cannot protect columns of
datatype LOB, object, nested table, VARRAY. If the check protects a single column, it can be
created inline with the column in the CREATE TABLE statement. A check constraint can also be
created or added as a table constraint. When it protects two or more columns, you must use the
table constraint syntax. The constraints name is optional and, if this name is not present, Oracle
will generate a unique name that begins with SYS_. You should not rely on system-generated
names for constraints.
Page 60
Page 61
2.
2.
Transaction table
CREATE TABLE ITEM_TRANS
(
ITNO Number(4) REFERENCE
ITEM_MUST(ITNO),
TRTP Char(1) CHECK ( TRTP IN ( P, S ),
TRDT DATE,
QTY Number(5),
);
TRTP Transaction Type. TRDT Date.
QTY Transaction quantity.
Page 62
Default Constraints
While inserting a row into a table without having values for every column, SQL must insert a
default value to fill in the excluded column(s), or the command will be rejected. The most
common default value is NULL. This can be used with columns not defined with a NOT NULL.
Example:
CREATE TABLE ITEM_MAST
(
ITNO
Number(4),
ITNM
Varchar2(20),
CLASS
Char(1),
QOH
Number(5) DEFAULT 100,
RATE
Number(8,2)
);
The table will be created with the specified columns and the rows retrieved by the SELECT
statement inserted into it.
If column specifications are given, the number of columns must equal the number of items in
the SELCET list.
Constraints information is inherited from the selected table.
Data type for the column cannot be specified.
Example 1:
CREATE TABLE ITEM_MAST2 AS SELECT ITNO,ITNM FROM ITEM_MAST;
Example 2:
CREATE TABLE ITEM_MAST3 ( ITNO, ITNAME) AS
SELECT ITNO,ITNM FROM ITEM_MAST;
Page 63
Maintaining of database objects involves creating, altering , deleting them from the database
Modifications are done using the ALTER statement
Deleting is done using the DROP statement
Alter Table
To change the definition of the table ALTER TABLE statement is used. The syntax for ALTER
TABLE statement is:
ALTER TABLE <table_name>
[ADD (<column_element> | <constraints>)]
[MODIFY (<column_element>)]
[DROP (<column_element> | <constraints>)]
ADD keyword is used to add column or constraints to the table. Constraints can be primary key,
check, references.
Example 1:
ADD a column ROL(ReOrderLevel) to the existing table ITEM_MAST.
ALTER TABLE item_mast ADD rol Number(3);
Example 2:
Modify the ITEM_MAST table, add a primary key constraint to ITNO. Assign the constraint
name as itnopk.
ALTER TABLE item_mast ADD CONSTRAINT itnopk PRIMARY KEY(itno);
Example 3:
Add constraint references to the column ITNO of the table ITEM_TRANS referring ITNO of
ITEM_MAST table.
ALTER TABLE item_trans ADD CONSTRAINT itnofk
FOREIGN KEY(itno) REFERENCES item_mast(itno);
Page 64
Data Type
Column Width
Constraints i.e. DEFAULT, NOT NULL and NULL
The type and/or size of a column can be changed, if every row for the column is NULL
A NOT NULL column may be added only to a table with no rows
An existing column can be modified to NOT NULL only if it has a non-NULL value in every
row
Views that references a table with SELECT * FROM will not work after a column has been
added to the table
The size of a column can only be increased
Example 1:
Modify the rate column of ITEM_MAST table to NOT NULL and increase its size to 10,2.
ALTER TABLE item_mast MODIFY rate Number(10,2) NOT NULL;
Dropping a column
You can drop a column that is of no use, or you can mark the column as not used and drop it
later. DROP COLUMN drops the column name specified from the table. You can provide more
than one column names separated by commas inside parenthesis. The indexes and constraints on
the column are also dropped. You must specify CASCADE CONSTRAINTS if the dropped
column is part of a multi-column constraint; the constraint will be dropped.
Example:
ALTER TABLE item_mast DROP COLUMN rol;
You usually mark a column as unused and not dropped if the table very large and takes a lot of
resource at pick hours. In such cases you would mark the column as unused and drop it later.
Once the column is marked as unused, you will not see it as part of the table definition.
Page 65
Page 66
Truncating table
The TRUNCATE statement is similar to the drop statement, but it does not remove the structure
of the table, so none of the indexes, constraints, triggers or privileges on the table are dropped.
By default, the space allocated to the table and indexes is freed. If you do not wish to free up the
space, include the REUSE STOTAGE clause. You cannot rollback a truncate operation. Also,
you cannot selectively delete rows using the TRUNCATE statement. You cannot truncate the
parent table of an enabled referential integrity constraint. You must first disable the constraint
and then truncate the table, even if the child table has no rows. The following example
demonstrates this :
STEP I
CREATE TABLE m1
(
no number CONSTRAINT nopk PRIMARY KEY
);
STEP II
CREATE TABLE m2
(
no1 number CONSTRAINT nofk REFERENCES m1(no)
);
STEP III
TRUNCATE TABLE m1;
truncate table m1
*
ERROR at line 1:
ORA-02266: unique/primary keys in table referenced by enabled foreign keys
STEP IV
ALTER TABLE m2 DISABLE CONSTRAINT nofk;
STEP V
TRUNCATE TABLE m1;
Page 67
Example :
INSERT INTO ITEM_MAST ( itno, itnm, class)
VALUES ( 111,Baby Food, A);
Page 68
Syntax:
UPDATE <table_name> SET <column_name>=value
[,<column_name>=value,] [WHERE <condition>];
Example:
UPDATE itmast SET qty=100 WHERE into=111;
Syntax:
DELETE FROM <table_name> [WHERE <conditional>];
Example:
DELETE FROM emp;
DELETE emp;
Both the statements are same and will delete all the rows from the emp table.
Page 69
Introduction to Views
A view is a customized representation of data from one or more tables. The view takes the result
of a query and stores it in the database. A view can be considered to be as a stored query or a
virtual table. Only the query is stored in the Oracle data dictionary; the actual data is not copied
anywhere. So, creating views does not take any storage place, other than the space in the data
dictionary. The views can have different column names than the base table. You may create a
view to limit the data accessible to the other user.
Creating a view
A view can be created using the following syntax:
CREATE VIEW <view_name>[<column_names>] AS <select_statement>;
Example:
CREATE VIEW empview AS SELECT empno,ename,deptno FROM emp WHERE deptno=20;
Now to select the rows from the view you can use the following statement:
SELECT * FROM empview;
The INSERT, UPDATE and DELETE statements can also be used with views
Using these commands with views is an indirect way of manipulating tables
WITH CHECK OPTION clause allows integrity constraints and data validation to be
enforced on data being inserted or updated
Join view can also be modified
Key-preserved table is used to understand the restriction on modifying join views
Page 70
Key-preserved table
A table is key-preserved if every key of the table can also be a key of the result of the join, so, a
key-preserved table has its keys preserved through a join.
Criteria to be a key-preserved table
View should be based on more than one table and should be a join view
To satisfy key-preserved table at least one column should be a PRIMARY KEY in the join
statement
Example:
CREATE VIEW myview AS SELECT empno, ename, dname, dept.deptno
FROM emp, dept WHERE emp.deptno=dept.deptno;
In the above example, table emp is a key-preserved table and table dept is a non-key-preserved
table.
Following will the output when you will select from the view called myview:
Page 71
Page 72
Dropping a view
The DROP VIEW command is used to remove a view from the database.
Example:
DROP VIEW myview;
MAXVALUE
CYCLE
DESCRIPTION
Defines the 1st number that the sequence will generate. The default is
1.
Defines the increase or decrease for subsequently generated number.
The lowest number the sequence will generate. This is the bounding
value in the decreasing sequence. The default MINVALUE is the
keyword NOMINVALUE, which translates 1 for an increasing
sequence and to minus -1026 for a decreasing sequence.
The largest number the sequence will generate. This is the bounding
value by default for the increasing sequence. The default
MAXVALUE is the keyword NOMAXVALUE, which translates to
1027 for an increasing sequence and to minus -1 for a decreasing
sequence.
Configures the sequence to repeat numbers after reaching the
bounding values.
When you create the sequence the START WITH value must be equal to or greater than
MINVALUE. To access the next number in the SEQUENCE, you simply select from it, using the
pseudo-column NEXTVAL. To get the last SEQUENCE number that your session has generated,
you select from it using the pseudo-column CURRVAL. If your session has not yet generated a
new sequence number, CURRVAL will be un-defined.
To Create a SEQUENCE:
CREATE SEQUENCE sq START WITH 1 INCREAMENT BY 5 MAXVALUE 50;
To fetch the NEXTVAL from a SEQUENCE:
SELECT sq.NEXTVAL FROM dual;
Page 73
Page 74
Chapter 6
Snapshots
Page 75
Objectives
Page 76
SQL is mostly executed in environments that require to recognize to differentiate between the
various users of the system.
Each user in an Oracle database has a specific authorization.
Commands are interpreted and permitted (or prohibited) on the basis of information
associated with the authorization associated with the ID of the user issuing the command.
The database administrator creates the users and assigns the privileges.
Privileges determine whether or not a user can execute a given command or a command
when acting on specific groups of data.
Grant Command
Page 77
Revoke Command
Using REVOKE command a user can withdraw the privileges which has been granted earlier.
Syntax:
REVOKE <database_privilege(s)> FROM <user(s)>
REVOKE <object_privilege(s)|ALL> ON <object_name> FROM <user(s)|PUBLIC>
Examples:
REVOKE ALL ON emp FROM PUBLIC;
REVOKE SELECT ON emp FROM user1;
REVOKE SELECT,INSERT ON emp FROM user1, user2;
Page 78
SQL *Plus has the facility to automatically commit all the transactions without explicitly issuing
the COMMIT command.
SET AUTOCOMMIT ON
SET AUTOCOMMIT OFF
Implicit COMMIT
The actions that will force a commit to occur, even without issuing the COMMIT command are:
Auto ROLLBACK
After completion of any DML statement, if the user experiences serious difficulty such as:
Hardware failure and no explicit COMMIT is made, Oracle will automatically rollback all uncommitted work.
If there is no explicit COMMIT made and if the AUTOCOMMIT mode set to OFF then after the
normal shut-down the server will commit all the un-committed transaction.
Savepoint
SAVEPOINT identifies a point in a transaction to which one can later rollback with the
ROLLBACK statement. It is helpful when a transaction contain a large number of SQL
statement and the user wants to commit only once when all are done.
If required one can rollback to a particular transaction. It works in a Last In Fast Out basis.
Example:
INSERT INTO dept VALUES(60,PURCHASE,DELHI);
SAVEPOINT sp1;
UPDATE emp SET deptno=60 WHERE ename=SMITH;
ROLLBACK TO SAVEPOINT sp1;
Page 79
Page 80
Snapshots
Introduction to PL/SQL
Advantages of PL/SQL
PL/SQL Architecture
PL/SQL Block Structure
Named and Anonymous block
Conditional and Iterative Control
IF THEN
IF THENELSE
IF THENELSIF
LOOPEND LOOP
WHILELOOP
FORLOOP
SQL within PL/SQL
Writing a PL/SQL code
Composite Data Types
PL/SQL Records
Record Assignment
PL/SQL TABLES
Page 81
Introduction to PL/SQL
Objectives
IF THEN
IF THENELSE
IF THENELSIF
LOOPEND LOOP
WHILELOOP
FORLOOP
Introduction to PL/SQL
Introduction to PL/SQL
Advantages of PL/SQL
PL/SQL Architecture
Application
Anonymous
Block
OR
Stored
Program
call
Oracle Server
SGA
Anonymous
Block
OR
Stored
Procedure
OR
PL/SQL Engine
PL/SQL
block
PL/SQL
block
Procedural
SQL
SQL statements
SQL
SQL statement executer
Procedural
statement
executor
Introduction to PL/SQL
Introduction to PL/SQL
LOOP
WHILELOOP
FORLOOP
IF THEN
The IF statement evaluates a condition, and if the condition is satisfied, a set of statement are
executed.
IF <condition> THEN
Statement 1;
Statement 2;
END IF;
The statements are executed only if the result of the condition is TRUE. The condition always
evaluates to a Boolean result of TRUE/FALSE.
Example :
DECLARE
no NUMBER;
BEGIN
no := &no;
IF no>100 THEN
DBMS_OUTPUT.PUT_LINE ( You got 100 points!!!!!!!!);
END IF;
DBMS_OUTPUT.PUT_LINE ( TRY AGAIN!!!!!!!);
END;
Introduction to PL/SQL
IF THENELSE
This is similar to IFTHEN statement but a set of statements can be executed if the condition
evaluates to FALSE or NULL.
IF <condition> THEN
Statement 1;
ELSE
Statement 2;
END IF;
The statement between THEN and ELSE are executed only if the result of the condition is
TRUE, and the statement between ELSE and END IF are executed only if the result of the
condition is FALSE.
Example :
DECLARE
no NUMBER;
BEGIN
no := &no;
IF no>100 THEN
DBMS_OUTPUT.PUT_LINE ( You got 100 points!!!!!!!!);
ELSE
DBMS_OUTPUT.PUT_LINE ( TRY AGAIN!!!!!!!);
END IF;
END;
IF THENELSIF
Use this structure if you need to select an action from several mutually exclusive conditions.
IF <condition1> THEN
Statement 1;
ELSIF<condition2> THEN
Statement 2;
ELSE
Statement 3;
END IF;
If conditon1 is TRUE then statement1 will executes otherwise it will check condition2. If
condition2 is TRUE then statement2 executes otherwise statement3 will executes.
Introduction to PL/SQL
Example :
DECLARE
age NUMBER;
BEGIN
age:=&age;
IF (age>=60) THEN
DBMS_OUTPUT.PUT_LINE('Age more than equal to 60 !!!');
ELSIF(age>=40 and age<60) THEN
DBMS_OUTPUT.PUT_LINE('Age more than equal to 40 !!!');
ELSIF(age>=30 and age<40) THEN
DBMS_OUTPUT.PUT_LINE('Age more than equal to 30 !!!');
ELSE
DBMS_OUTPUT.PUT_LINE('You are still young !!!');
END IF;
END;
LOOPEND LOOP
The basic form of iterative control is the LOOP statement. The statements between LOOP and
END LOOP will executed infinitely. You must use an EXIT statement to force a loop to
terminate un-conditionally and pass the control to the statement following the END LOOP. The
EXIT WHEN statement completes an infinitely loop conditionally.
LOOP
Statements;
END LOOP;
Example :
DECLARE
no NUMBER :=10;
BEGIN
LOOP
no := no + 10;
DBMS_OUTPUT.PUT_LINE ( Value of the variable is : || no);
IF (no>100) THEN
EXIT;
END IF;
END LOOP;
END;
Introduction to PL/SQL
WHILELOOP
This loop has a condition associated with it. The condition is evaluate, and, if the result is TRUE,
the statements inside the loop are executed. If the condition is FALSE, execution continues from
the next statement to END LOOP.
WHILE <condition>
LOOP
Statements;
END LOOP;
Example :
DECLARE
no NUMBER :=10;
BEGIN
WHILE ( no <100)
LOOP
no := no + 10;
DBMS_OUTPUT.PUT_LINE ( Value of the variable is : || no);
END LOOP;
END;
FORLOOP
Use the FORLOOP if you need the iterations to occur a fixed number of times. In the basic
LOOP and in WHILELOOP, the number of iteration is unknown. The FORLOOP is
executed for a range of values.
FOR <counter> IN [REVERSE] <start_range> .. <end_range>
LOOP
Statements;
END LOOP;
Here, counter is a variable known as the Index Variable (This need not be declared in the
DECLARE section; it is implicitly declared as Integer), which will have the value of start_range
for the first iteration and it will continue till the end_range. The two dots(..) serve as a Range
Operator. If the REVERSE keyword is used, the range is decremented. The range can be
expression or variable.
Introduction to PL/SQL
Example :
BEGIN
FOR cn IN REVERSE 1..10
LOOP
DBMS_OUTPUT.PUT_LINE(cn);
END LOOP;
END;
DML in PL/SQL
The allowable DML statements are SELECT, INSERT, UPDATE and DELETE. When SELECT
statements are used queries must return one and only one row.
The INTO Clause
The INTO clause is used with SELECT, to store values from the table into variables. The INTO
clause occurs between the SELECT and FROM clauses. This clause specifies the names of
variables that will be populated by the items being selected in the SELECT clause. For each item
selected a separate variable must be used, and their order corresponds to the item selected.
Introduction to PL/SQL
PL/SQL records provides a way to deal with separate but related variables as a unit
PL/SQL record is a variable that may contain a collection of separate values, each
individually addressable
The record type has to be defined before its record can be declared
In case one of the record component is a record, then it is called a nested record
The records have uniquely named fields. The fields within the record will obtain their names and
datatypes from the columns of the table of view referenced in the record declaration.
The syntax for creating a record is :
TYPE <type_name> IS RECORD
(
<field_name1> { field_type|variable%TYPE|table.column%TYPE|table%ROWTYPE },
<field_name2> { field_type|variable%TYPE|table.column%TYPE|table%ROWTYPE },
..
);
Where as
<type_name>
<field_type>
Example:
DECLARE
TYPE employee IS RECORD
(
ecode
emp.empno.%type,
ename
emp.ename%type,
esalary
emp.sal.%type
);
emprec employee;
Record Assignment
In order to assign one record to another, both records must be of the same type. Even if the fields
of the records of different types match exactly, they cannot be assigned to each other. Also a list
of values cannot be assigned to a record using assignment operator and cannot be tested for
equality or inequality.
Introduction to PL/SQL
Example :
deprectype;
dept.%ROWTYPE;
PL/SQL TABLES
Pl/SQL tables are modeled as database tables, but are actually not
Primary keys can be associated with them to have array-like access to row
The size can be dynamically increased by adding more rows when required. However no row
can be deleted
Column can belong to any scalar type, but the primary key must belong to
BINARY_INTEGER. This give you array-like access to rows
Introduction to PL/SQL
The syntax for creating a table type is :
TYPE <type_name> IS TABLE OF
<column_type | variable%TYPE | table.column%TYPE > [ NOT NULL ]
INDEX BY BINARY_INTEGER;
Where as
<type_name>
<column_type>
Example :
DECLARE
TYPE enm IS TABLE OF emp.ename%type
INDEX BY BINARY_INTEGER;
x binary_integer :=1;
ename enm;
BEGIN
FOR i IN(SELECT ename FROM emp)
LOOP
ename(x) :=i.ename;
x:=x+1;
END LOOP;
FOR j IN 1..x-1
LOOP
DBMS_OUTPUT.PUT_LINE(ename(j));
END LOOP;
END;
Chapter 8
Snapshots
PL/SQL - II
Objectives
PL/SQL - II
Implicit Cursor
Implicit cursors are declared by PL/SQL implicitly for all DML statements and for single row
queries. For example, SELECT statement issued directly within the BEGIN END part of a
block opens up an Implicit cursor.
Explicit Cursor
When the query returns more than one row, you need to define an Explicit cursor; you can not
use SELECT INTO statement. An Explicit cursor is defined in the declared section and is open,
fetched and closed in the executable or in the Exception section. An Explicit cursor can be
deemed an array with upper limit. It can have any number of rows.
Difference between Implicit and Explicit cursor
IMPLICIT CURSOR
Maintained internally by PL/SQL. Opened and
closed automatically when the query is
executed.
The cursor attributes are prefixed with SQL
(For example, SQL%FOUND).
The cursor attribute %ISOPEN is always
FALSE, because the implicit cursor is closed
immediately when the query completes.
Only one row can be processed; the SELECT
statement with the INTO clause is used.
EXPLICIT CURSOR
Defined, opened and closed explicitly in the
program. The cursor has a name.
The cursor attributes are prefixed with cursor
name (For example, C1%FOUND).
The %ISOPEN attribute will have a valid value
depending upon the status of the cursor.
Any number of rows can be processed.
Iterative routines should be set up in the
program, and each row should be fetched
explicitly (except for a Cursor-For Loop)
Using Cursor
The term cursor usually refers to an explicit cursor. The cursor to be used in the program defined
in the declare section. The cursor has a name and a SELECT statement. WHERE, ORDER BY,
GROUP BY, Sub-queries are all permitted in a cursor definition.
PL/SQL - II
Declaring a cursor
A cursor declaration defines the SELECT statements for the query you need to process in the
body of the block.
Syntax:
CURSOR <cursor_name> IS <select_statement>;
The cursor_name is an un-declared PL/SQL variable. You can not assign values to a cursor name
or use it in an expression.
Opening a cursor
The cursor should be opened before its row values can be used. Opening the cursor initiates the
query processing.
Syntax:
OPEN <cursor_name>;
Where cursor_name is the name of the cursor defined in the DECLARE section.
Fetching rows from a cursor
A cursor is fetched to retrieve a row at a time; use the FETCH command for this. After each
fetch, the cursor advances to the next row in the result set.
Syntax:
FETCH <cursor_name> INTO <variable> [, variable ];
For each column in the cursor definition SELECT, there should be a corresponding variable in
the fetch variable list. The variables should be declared with the appropriate data type in the
declaration section.
Closing a cursor
Explicitly opened cursors should be closed explicitly.
Syntax:
CLOSE <cursor_name>;
PL/SQL - II
PL/SQL - II
PL/SQL - II
Example:
DECLARE
Eno emp.empno%type;
Enm emp.ename%type;
Esal emp.sal%type;
CURSOR C1(p number) IS SELECT empno, ename, sal
FROM emp WHERE deptno=p;
BEGIN
OPEN C1(10);
LOOP
FETCH C1 INTO Eno, Enm, Esal;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(Eno|| ||Enm|| ||Esal);
END LOOP;
CLOSE C1;
END;
PL/SQL - II
Example:
DECLARE
BEGIN
FOR i IN ( SELECT empno,ename,sal from emp )
LOOP
DBMS_OUTPUT.PUT_LINE(i.Eno|| ||i.Enm|| ||i.Esal);
END LOOP;
END;
Advantages of Exception
Without exception handling, every time a command is issued a check must be made for
execution errors. With exceptions, errors are handled conveniently without the need to code
multiple checks.
Exceptions improve readability by isolating error handling routines.
Exception improve readability. One need not worry about checking for an error at every point
it might occur. If PL/SQL block contains an exception handler, and if an exception is ever
raised in that block, the exception handler will handle the exception.
Helps successful execution of a block called from another PL/SQL block.
PL/SQL - II
Raising Exceptions
There are three ways that an exception can be raised:
Oracle Error
ORA-01403
ORA-01422
ORA-06511
ORA-01001
ORA-01722
ORA-01476
PL/SQL - II
The WHEN OTHERS Exception Handler
Rather than defining a separate handler for every exception type, WHEN OTHERS exception
handler is defined, which handlers all errors not already handled in the block. WHEN OTHERS
exception handler should always be the last exception handler in the block. When an exception
has occurred, one wants to evaluate the associated error. This is more relevant when WHEN
OTHERS exception is handled as it helps to know what error has exactly occurred.
PL/SQL provides two functions for this purpose:
SQLCODE
It returns the error number associated with the exception that has occurred. If used
outside an EXCEPTION handler, the function will return zero. The error number
returned may be assigned to a NUMBER variable with default precision.
SQLERRM
It returns character data. It returns the complete error message associated with the
exception including the error number.
Exception can not be declared twice in the same block. However, same exception can be
declared in two different block.
Exception declared in a block are considered local to that block and global to all its subblocks. Because a block can reference only local or global exceptions, enclosing blocks
cannot reference exceptions declared in a sub block
PL/SQL - II
Exception Propagation
When an exception is raised in the executable section of a block, the exception is handled in the
following manner:
The current block has the exception handler, then it executes it and completes the block
successfully. The control then passes to the enclosing block.
DECLARE
my_exception EXCEPTION;
BEGIN
Statements;
BEGIN
RAISE my_exception;
EXCEPTION
WHEN my_exception THEN
Statements;
END;
Control passes here
Statements;
END;
EXCEPTION my_exception is
raised in the inner block
EXCEPTION handled in the
inner block
If there is no exception handler in the current block for a raised exception, the execution
propagates according to the following rules :
If there is an enclosing block for the current block, the exception is passed on to that block. The
enclosing block then becomes the current block. If a handler for the raised exception is not
found, the process is repeated.
DECLARE
my_exception1 EXCEPTION;
my_exception2 EXCEPTION;
BEGIN
EXCEPTION my_exception2 is
Statements;
raised in the inner block
BEGIN
IF < condition1 > THEN
RAISE my_exception2;
EXCEPTION my_exception2 not
EXCEPTION
handled here
WHEN my_exception1 THEN
Statements;
END;
EXCEPTION my_exception2 is propagated
EXCEPTION
to enclosing block and is handled there
WHEN my_exception2 THEN
Statements;
Control passes to enclosing block
END;
Statements;
PL/SQL - II
If there is no enclosing block for the current block, the exception si passed back to the
environment that invoked the PL/SQL program.
DECLARE
my_exception1 EXCEPTION;
my_exception2 EXCEPTION;
my_exception3 EXCEPTION;
BEGIN
Statements;
EXCEPTION my_exception3 is raised
BEGIN
in the inner block
IF < condition1 > THEN
RAISE my_exception3;
EXCEPTION my_exception3 not
EXCEPTION
handled in inner block
WHEN my_exception1 THEN
Statements;
END;
EXCEPTION my_exception3 is propagated
EXCEPTION
to enclosing block but is not handled there
WHEN my_exception2 THEN
Statements;
my_exception3 is propagated out of the calling environment
END;
Only one exception at a time can be active in the exception handling part of a block. Therefore, if
an exception is raised inside a handler, the block that encloses the current block is the first block
searched to find a handler for the newly raised exception.
Example 1 :
DECLARE
Eno emp.empno%type;
Enm emp.ename%type;
Esal emp.sal%type;
Hsal EXCEPTION;
Lsal EXCEPTION;
BEGIN
Eno := &Eno;
SELECT ename, sal into Enm, Esal FROM emp WHERE Eno = empno;
IF ( Esal <2000 ) THEN
RAISE Lsal;
ELSEIF ( Esal >4000 ) THEN
RAISE Has;
END IF;
DBMS_OUTPUT.PUT_LINE(Enm|| ||Esal);
EXCEPTION
WHEN Lsal THEN
DBMS_OUTPUT.PUT_LINE(The salary is too Low!);
PL/SQL - II
Chapter 9
Snapshots
Sub-Programs in PL/SQL
Advantages of Sub-Programs
Procedure
Calling a Procedure
Actual Vs. Formal parameter
Argument Modes
Functions
Stored Package
Advantages of package
Creating a package body:
Dropping Procedures, Function and Package
DataBase Trigger
Advanced PL/SQL
Objective
Advanced PL/SQL
Sub-Programs in PL/SQL
Subprograms are named PL/SQL programs that are stored in a compiled form in the database.
These programs can be invoked whenever required.
Advantages of Sub-Programs
Modularity
Subprograms allow you to break a program down into manageable, well-defined logic modules.
This supports top down design and the stepwise refinement approach to problem solving.
Reusability and Maintainability
Subprograms once validated, can be used with confidence in any number of applications.
Furthermore, only the subprogram is affected if its definition changes. This simplifies
maintenance and enhancement.
Procedure
A procedure is a subprogram that performs a specific action. A procedure can be called from any
PL/SQL program and also be invoked from the SQL prompt. A procedure has two parts: the
specification and body.
The procedure specification begins with the keyword PROCEDURE followed by the procedure
name and an optional list of arguments, enclosed within parenthesis. Procedures that take no
parameters are written without parentheses. The procedure body begins with the keyword IS or
AS and ends with an END followed by an optional procedure name. The procedure body has
three parts: a declarative part, an executable part, and an optional exception handling part. The
declarative part contains local declarations. The keyword DECLARE is NOT used to declare
variables and expressions. All the declarations are placed in between the IS and BEGIN
keywords. The executable part contains statements, which are placed between the keywords
BEGIN and EXCEPTION ( or END ). At least one statement must appear in the executable part
of a procedure. The exception-handling part contains exceptions handlers, which are placed
between the keywords EXCEPTION and END. This part is optional.
The syntax for writing procedure is :
CREATE [ OR REPLACE ] PROCEDURE < PROCEDURE_NAME >
(<arg1> [ mode ] <datatype>, . )
IS | AS
[ local declaration ]
BEGIN
Executable statements
[ EXCEPTION
exception handlers ]
END [ PROCEDURE_NAME ];
Advanced PL/SQL
Calling a Procedure
To call the procedure from a block, the command is
PROCEDURE_NAME ( <arguments>);
To invoked from the SQL prompt using the EXECUTE command
EXECUTE
PROCEDURE_NAME( <arguments> );
Example :
CREATE OR REPLACE PROCEDUR PR1 ( Eno NUMBER )
IS
Enm emp.ename%TYPE;
Esal emp.sal%TYPE;
BEGIN
SELECT ename,sal into Enm, Esal FROM emp WHERE Eno := emp.empno;
DBMS_OUTPUT.PUT_LINE ( Eno|| ||Enm|| ||esal);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE (Invalid Employee Number !!!);
END;
The variable or expressions referenced in the parameter list of a subprogram all are actual
parameters
The variables declared in a subprogram specification and referenced in the subprogram body
are formal parameters
The actual parameter and its corresponding formal parameter must to compatible datatype
Argument Modes
Argument modes are used to define the behavior of formal parameters. There are three argument
modes to be used with any subprograms.
IN
The IN parameter lets the user pass values to the called subprogram. Inside the
subprogram, the IN parameter acts like a constant; therefore, it cannot be
modified.
OUT
The OUT parameter lets the user return values to the called subprogram. Inside
the subprogram, the OUT parameter acts like a un-initialized variable. Therefore,
it cannot be assigned to another variable or to itself.
The IN OUT parameter lets the user pass initial values to the called subprogram
and returns updated values to the calling block.
IN OUT
Advanced PL/SQL
Example 1:
CREATE OR REPLACE
PROCEDUR PR1 ( eno IN NUMBER, enm OUT VARCHAR2, esal OUT NUMBER )
IS
BEGIN
SELECT ename,sal into enm, esal FROM emp WHERE eno := emp.empno;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE (Invalid Employee Number !!!);
END;
Calling a Procedure :
DECLARE
Eno emp.empno%TYPE;
Enm emp.ename%TYPE;
Esal emp.sal%TYPE;
BEGIN
Eno := &Eno;
PR1 ( Eno, Enm, Esal );
DBMS_OUTPUT.PUT_LINE ( Eno||
END;
||Enm||
||esal);
Example 2 :
Creating a Procedure
Advanced PL/SQL
Calling a procedure
DECLARE
bb NUMBER;
BEGIN
bb:=5;
ad(bb);
DBMS_OUTPUT.PUT_LINE(The changed value : ||bb);
END;
Functions
A Function is a sub-program that returns a value. A function must have return clause. The syntax
for the function is:
CREATE [ OR REPLACE ] FUNCTION < function_name >
(<arg1><datatype>, . ) RETURN <data_type>
IS
[ local declaration ]
BEGIN
Executable statements;
[ EXCEPTION
exception handlers ]
END [ function_name ];
Like a procedure, a function has two parts; the specification and the body. The function
specification begins with the keyword FUNCTION and ends with the RETURN clause, which
specifies the datatype of the result value. The function is exactly same as procedure body. The
RETURN statement immediately returns control to the caller environment. Execution then
resumes with the statement following the sub-program call.
Example 1:
Specifying a function
CREATE OR REPLACE
FUNCTION fn1 ( esal NUMBER, rate NUMBER) RETURN NUMBER
IS
da NUMBER(8,2);
BEGIN
da:= esal*(rate/100);
RETURN da;
END;
Advanced PL/SQL
DECLARE
eno
emp.empno%TYPE;
enm emp.ename%TYPE;
esal emp.sal%TYPE;
rt
NUMBER(2);
da
NUMBER(8,2);
BEGIN
rt:=&rt;
eno := &eno;
SELECT empno, ename, esal INTO eno, enm, esal
FROM emp WHERE empno=eno;
da:=fn1(esal, rt);
DBMS_OUTPUT.PUT_LINE ( Eno|| ||Enm|| ||esal||
END;
||da);
Stored Package
A Package is a database object that groups logically related PL/SQL objects. Package
encapsulates related procedures, functions together as a logical unit in the database. Packages are
made of two components; the specification and the body. A specification is the interface to
applications and has declarative statements. The body of the package contains different
procedures and functions.
Package Specification
The specification is the interface to the application, it declares the procedures and functions. The
package specification holds the public declarations, which are visible to the application.
Package Body
The body holds implementation details and private declaration, which are hidden from the
application. The scope of these declarations is local to the package body. Unlike a package
specification, the declarative part of a package body can contain sub-program bodies. Package
can overload procedures and functions, declaring multiple programs with the same name. The
correct program to be called is decided at runtime, based on the number or datatypes of the
parameters. To create a package, you must first create the package specification. You cannot
GRANT privileges on only one procedure or function within a package.
Advanced PL/SQL
Advantages of package
Modularity
Packages encapsulates related procedures and functions together in a named PL/SQL module.
Easier application design
It is not important to compile the package body completely until the application is complete.
When designing an application initially the information in the specification is required. A
specification can be coded and compiled without its body. Once the specification has been
compiled, stored sub-programs that reference the package can be compiled as well.
Information Hiding
The packages can be specified in which all sub-programs are public that is, visible and accessible
or private that is hidden and in-accessible. By hiding implements details from users, integrity of
package is protected.
Better Performance
The entire package is loaded into the memory when a procedure, within the package, is called for
the first time. This reduce the un-necessary disk I/O and network traffic.
Specifying a package:
CREATE [OR REPLACE] PACKAGE <package_name> AS
/* Procedures and function declarations */
END [ <package_name> ];
Advanced PL/SQL
Example:
CREATE OR REPLACE PACKAGE pkg AS
PROCEDURE addition(a NUMBER, b NUMBER);
FUNCTION higher(a NUMBER, b NUMBER) RETURN NUMBER;
END pkg;
CREATE OR REPLACE PACKAGE BODY pkg AS
PROCEDURE addition(a NUMBER, b NUMBER)
IS
c NUMBER;
BEGIN
c:=a+b;
DBMS_OUTPUT.PUT_LINE(The resultant value is : || c);
END addition;
FUNCTION hiegher(a NUMBER, b NUMBER)
IS
c NUMBER;
BEGIN
IF (a>b) THEN
c:=a;
ELSE
c:=b;
END IF
RETURN c;
END higher;
END pkg;
Advanced PL/SQL
DataBase Trigger
Triggers are programs that are executed automatically in response to a change in the database.
Triggers can be configured to fire, or execute, either before or after the triggering event. The
events that can be hooked with triggers include the following.
DML events
DDL events
Database events
DML event triggers can be statement or row triggers. The DML statement trigger fires before or
after the triggering statement. The DML row trigger fires before or after each row affected by the
statement is changed. You can define multiple triggers for a single event and type, but there is no
way to enforce the order in which these multiple triggers will fire.
Trigger Events
Event
INSERT
UPDATE
DELETE
CREATE
ALTER
DROP
Trigger Description
Fires whenever a row is inserted into the table or view.
Fires whenever a row is updated in the table or view.
Fires whenever a row is deleted from a table or view.
Fires whenever a CREATE statement adds a new object to the database.
Fires whenever a ALTER statement changes an object in the database.
Fires whenever a DROP statement removes an object from the database.
Advanced PL/SQL
The :new in this example refers to a record containing the new, post-change data. Another is
there, i.e. :old; it would refer to a record containing the old, pre-change data. The trigger can
have visibility to both old and new values. However, the :old on an insert and :new on a delete
have no meaning; they contain all NULLs. Like constraints triggers may be disabled or enabled
to turn off or turn on their execution. To enable or disable a single trigger, use the ALTER
TRIGGER statement :
ALTER TRIGGER <trigger_name> ENABLE;
ALTER TRIGGER <trigger_name> DISABLE;
To enable or disable all triggers on a table, use the following statement:
ALTER TABLE < table_name> ENABLE ALL TRIGGER;
ALTER TABLE < table_name> DISABLE ALL TRIGGER;
To drop trigger, use the following statement :
DROP TRIGGER <trigger_name>;
Example 1
STEP 1: Create the following table.
CREATE TABLE stock
(
itno number(5),
qty number(5,2),
rate number(2),
total number(10,2)
);
STEP 2: Create the following Trigger on that table.
CREATE or REPLACE TRIGGER stock_total_updat
BEFORE INSERT or UPDATE ON stock FOR EACH ROW
BEGIN
:new.total:=:new.qty*:new.rate;
END;
STEP 3: Insert a row on stock table and see the effect.
INSERT INTO stock (into , qty , rate) VALUES(1,120,25.75);
It will update the total column of the table automatically.
Advanced PL/SQL
Example 2
Create a time restriction trigger on the above table.
CREATE or REPLACE TRIGGER restriction_on_time
BEFORE INSERT or UPDATE or DELETE on stock
BEGIN
IF (to_char(sysdate,'hh24'))<9 or (to_char(sysdate,'hh24'))>=18 THEN
RAISE_APPLICATION_ERROR(-20002,'Only Query is possible');
END IF;
end;
When you want to give an error message through trigger you should explicitly raise the error
through the following statement:
RAISE_APPLICATION_ERROR(err_code, err_message);
Err_code
: This will be the error code. The code will be onwards 20000.
Err_message : This will be error message which you want to show. The message will be within
single quotation.
Example 3
Master table updation using trigger.
STEP 1: Create the following tables.
1. CREATE TABLE ITEM_MAST
(
ITNO Number(4) PRIMARY KEY,
ITNM Varchar2(20),
QOH Number(5),
RATE Number(8,2)
);
2. CREATE TABLE ITEM_TRANS
(
ITNO Number(4) REFERENCE ITEM_MUST(ITNO),
TRTP Char(1) CHECK ( TRTP IN ( P, S ),
TRDT DATE,
QTY Number(5),
);
Advanced PL/SQL
STEP 2: Create the following trigger on the transaction table.
CREATE or REPLACE TRIGGER master_qoh_update
AFTER INSERT or UPDATE ON item_trans FOR EACH ROW
DECLARE
a NUMBER;
BEGIN
SELECT qoh INTO a FROM item_mast WHERE itno=:new.itno;
IF INSERTING THEN
IF UPPER(:new.trtp)='S' THEN
IF :new.qty>a THEN
RAISE_APPLICATION_ERROR(-20050,'Out of stock');
END IF;
END IF;
IF UPPER(:new.trtp)='S' THEN
UPDATE item_mast SET qoh= qoh-:new.qty WHERE itno=:new.itno;
ELSE
UPDATE item_mast SET qoh= qoh+:new.qty WHERE itno=:new.itno;
END IF;
END IF;
IF UPDATING THEN
IF UPPER(:new.trtp)<>UPPER(:old.trtp) THEN
IF UPPER(:new.trantype)='S' THEN
UPDATE item_mast SET qoh = qoh-(:old.qty*2)
WHERE itno=:old.itno;
ELSE
UPDATE item_mast set qoh= qoh+(:old.qty*2)
WHERE itno=:old.itno;
END IF;
END IF;
END IF;
IF DELETING THEN
IF UPPER(:old.trtp)='S' THEN
UPDATE item_mast SET qoh = qoh+:old.qty WHERE itno=:old.itno;
ELSE
UPDATE item_mast SET qoh= qoh-:old.qty WHERE itno=:old.itno;
END IF;
END IF;
END;
Advanced PL/SQL
Snapshots
Objectives
Type
Function
IS_OPEN
FCLOSE
GET_LINE
PUT_LINE
FFLASH
Function
Procedure
Procedure
Procedure
Procedure
Purpose
Open a text file for Input or Output. Create an Output file if it
does not exists.
Determine if a file handle refers to an open file.
Used to close a file.
Read a line of text from an opened file.
Write a line to a file. Append an OS specific line terminator.
Physically write all pending output to a file.
Chapter 11
Snapshots
Objectives
What is an object?
Object in a unit or instance of a class that contains a collection of related procedures and data, to
produce specific result. Procedures could be in the form of methods or functions. Data could be
the form of variable or attributes or data members.
Existence of an Object
In Oracle object can be of two type.
Transient Object
Persistent Object
Row Object
Column Object
Null?
Type
---------------- ---------------------------NOT NULL NUMBER(4)
VARCHAR2(10)
VARCHAR2(9)
NUMBER(4)
DATE
NUMBER(7,2)
NUMBER(7,2)
NUMBER(2)
Null?
-------NOT NULL
Type
---------------NUMBER(4)
VARCHAR2(10)
VARCHAR2(9)
NUMBER(4)
DATE
NUMBER(7,2)
NUMBER(7,2)
NUMBER(2)
REF OF D_TYPE
STEP 9 : Update the ref2newdept column of newemp table with the reference number taking
from newdept table.
UPDATE newemp SET ref2newdept = (SELECT REF(d) FROM newdept d WHERE
d.deptno=newemp.deptno);
STEP 10 : Display the contents of ref2newdept with corresponding deptno.
SELECT deptno,ref2newdept FROM newemp e
DEPTNO REF2NEWDEPT
------------- --------------------------------------------------------------------------------------------------20
30
30
20
30
30
10
20
10
30
20
30
20
10
000022020817E5E47B25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47C25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47C25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47B25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47C25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47C25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47A25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47B25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47A25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47C25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47B25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47C25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47B25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
000022020817E5E47A25BB11D6924100508BD88E0317E5E47925BB11D6924100508BD88E03
STEP 11: Select empno,ename and their corresponding department details using DEREF.
select empno,ename,deref(ref2newdept) from newemp;
EMPNO
----------------7369
7499
7521
7566
7654
7698
7782
7788
7839
7844
7876
7900
7902
7934
ENAME
--------------SMITH
ALLEN
WARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
JAMES
FORD
MILLER
DEREF(REF2NEWDEPT)(DEPTNO, DNAME)
----------------------------------------------------------------D_TYPE(20, 'SALES')
D_TYPE(30, 'ADMIN')
D_TYPE(30, 'ADMIN')
D_TYPE(20, 'SALES')
D_TYPE(30, 'ADMIN')
D_TYPE(30, 'ADMIN')
D_TYPE(10, 'PRODUCTION')
D_TYPE(20, 'SALES')
D_TYPE(10, 'PRODUCTION')
D_TYPE(30, 'ADMIN')
D_TYPE(20, 'SALES')
D_TYPE(30, 'ADMIN')
D_TYPE(20, 'SALES')
D_TYPE(10, 'PRODUCTION')
Calling a Method
The referencing of methods or member functions is the same as referencing attributes of abstract
or user defined object data type. To call a method for a particular instance, use the dot (.)
notation. The syntax is :
OBJECT_NAME.METHOD_NAME
Eg: SELECT empno,ename,e.adr.state,e.adr.city from empobj e;
MAP Method
A MAP method is a function that returns a scalar data type. When the object is to be stored, the
MAP method can be called to convert the object to a scalar type that can be stored. A MAP
method will be automatically invoked in the following cases:
Include the following statement on the emp_type declaration, after member function declaration.
MAP MEMBER FUNCTION NAMED RETURN NUMBER
Include the following code on the emp_type body code :
MAP MEMBER FUNCTION zip
RETURN NUMBER IS
BEGIN
RETURN adr.zip;
END;
Using the map method within select statement :
SELECT empno, ename, e.adr.zip FROM empobj e ORDER BY e.zip();
Chapter 12
Snapshots
Using LOBs
Objectives
Using LOBs
The BLOB, CLOB and NCLOB datatypes are stored in the database and are known as Internal
LOBs. Oracle supports data integrity and concurrency for Internal LOBs. The BFILE is not
stored in the database and Oracle does not validate whether the file exists or not when a record is
inserted using the BFILE type. The data for LOB columns is not stored in the table, if the size is
more than 4000 bytes. Oracle stores a Locator as column values for internal LOBs having more
than 4000 bytes and for BFILE types. The Locator points to the location of the actual data stored
inside or outside or inside the database. For BFILE you have to create a directory.
Using LOBs
To set an internally stored column to an empty locator value, we have to use the following
functions :
For BLOB columns EMPTY_BLOB()
For CLOB columns EMPTY_CLOB()
For NCLOB columns EMPTY_CLOB()
WRITE
APPEND
COMPARE
COPY
ERASE
GETLENGTH
SUBSTR
Using LOBs
To modify the values of LOBs, the following steps have to be taken:
SYNTAX :
Where :
LOCATION
AMOUNT
OFFSET
BUFFERS
APPEND
COMPARE Compares the whole or parts of two LOBs. It returns 0 for a successful match.
SYNTAX : DBMS_LOB.APPEND ( FIRST_LOC, SECOND_LOC, AMOUNT,
FIRST_OFFSET, SECOND_OFFSET);
Where :
FIRST_LOC
SECOND_LOC
AMOUNT
FIRST_OFFSET
SECOND_OFFSET
Using LOBs
COPY
Copies the whole or a part of the source LOB into the destination LOB.
Using LOBs
Example 2 : Writing a new value to the CLOB column using PL/SQL block
DECLARE
A
CLOB,
M
NUMBER,
N
NUMBER,
B
VARCHAR2(100),
BEGIN
SELECT responsibility INTO A FROM personnel_details
WHERE man_id=1001 FOR UPDATE;
M := DBMS_LOB.GETLENGTH(A);
DBMS_LOB.ERASE ( A, M,1 );
B:=&responsibility;
N := LENGTH(B);
DBMS_LOB.WRITE ( A, N, 1, B );
COMMIT;
END;
Example 3 : Copying One LOB to another using PL/SQL
DECLARE
A
CLOB,
N
NUMBER,
B
CLOB,
BEGIN
SELECT responsibility INTO A FROM personnel_details WHERE man_id=1001;
SELECT responsibility INTO B FROM personnel_details
WHERE man_id=1002 FOR UPDATE;
N := DBMS_LOB.GETLENGTH(A);
DBMS_LOB.COPY( B, A, N,1,1 );
END;
Chapter 13
Snapshots
Collections
Nested Tables
Creating table using Nested Table
DML operations on Nested Table
Nested Table in PL/SQL
VARRAYs
Creating VARRAYs
DML operations with VARRAYs
VARRAYs in PL/SQL
Similarities and differences between Nested Table and VARRAYs
Collections in Oracle
Objectives
Collections in Oracle
Collections
Collections are similar to arrays in other languages. In oracle release 7.3 and earlier, there was
only one kind of collection, called a PL/SQL table. This type of collection is still supported but is
now known as an index-by table. A collection is an ordered group of elements. Like records,
collections must be defined with the TYPE statement, then variables of that type can be created
and used. Oracle provides two new Collection types: Nested Table and VARRAYS.
Nested Tables
A Nested table is useful for data models requiring referential integrity and is suitable for master
detail and one to many relationships. A Nested table is a database table which stores data in it,
that cannot be accessed directly. A Nested table can be included in a table definition as one of the
columns. That is why, they are known as Nested tables. Nested table can be manipulated directly
using SQL.
..,
..,
<column_name >
< table_type >
)
NESTED TABLE < column of table_type > STORE AS < store_table >;
Example :
Step 1 : Creating An object
CREATE TYPE book_type AS OBJECT
(
book_no
NUMBER(4),
book_name VARCHAR2(20),
author
VARCHAR2(20)
);
Step 2 : Creating a table type
CREATE TYPE bk_type AS TABLE OF book_type;
Collections in Oracle
Step 3 : Creating the nested table
CREATE TABLE studlab_rec
(
stno
NUMBER(4) NOT NULL,
stnm
VARCHAR2(20),
book_issu
bk_type
)
NESTED TABLE book_issu STORE AS booknest;
Insert statement
INSERT INTO studlab_rec VALUES
(1001, 'Amit Kumar', bk_type(book_type(2001,'Oracle ','loney'),
book_type(2002,'Oracle bible','kevin')));
2.
Update statement
UPDATE THE ( SELECT book_issu FROM studlab_rec WHERE stno=1001)
SET book_name ='Oracle Unleashed' WHERE book_no=2001;
3.
4.
Delete statement
DELETE FROM THE (SELECT book_issu FROM studlab_rec WHERE stno=1001)
WHERE book_no=2003
Collections in Oracle
Example :
DECLARE
mbk studlab_rec.book_issu%TYPE;
mnm studlab_rec.stnm%TYPE;
CURSOR ntc IS SELECT stnm,book_issu FROM studlab_rec;
BEGIN
OPEN ntc;
LOOP
FETCH ntc INTO mnm,mbk;
EXIT WHEN ntc%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Book issued to : '||mnm);
FOR i IN 1..mbk.COUNT
LOOP
DBMS_OUTPUT.PUT_LINE ('Book Title ---> '||mbk(i).book_name);
END LOOP;
END LOOP;
CLOSE ntc;
END;
VARRAYs
VARRAY is a datatype similar to an array in C or Pascal. Elements are inserted into a VARRAY,
starting at index 1 upto the maximum length declared in the VARRAY type. Each element of the
array has the position indicated by an index which can range from one to the COUNT value. A
VARRAY can be stored in a database column. A VARRAY can only be manipulated as a whole.
Individual elements of stored VARRAYS cannot be modified.
Creating VARRAYs
The syntax of creating a VARRAY is as follows :
CREATE OR REPLACE TYPE < type_name >
IS VARRAY<(maximum_size)> OF < element_type >;
Example :
STEP 1 : Creating an Object.
CREATE TYPE book_type AS OBJECT
(
book_no
number(4),
book_name varchar2(20),
author
varchar2(20)
);
Collections in Oracle
STEP 2 : Creating VARRAY.
CREATE OR REPLACE TYPE book_arr AS VARRAY(10) OF book_type;
STEP 3 : Creating the table.
CREATE TABLE stud_rec
(
stno
number(4) NOT NULL,
book_issu
book_arr
);
Insert Statement
INSERT INTO stud_rec VALUES(1002, book_arr (
book_type(1001,'Java 1.2.1','Sun MicroS'),
book_type(1002,'Java Servlets','Sun MicroS'),
book_type(1003,'Java beans','Sun MicroS'),
book_type(1009,'Java 1.2.1','Sun MicroS')));
2.
Update Statement
UPDATE stud_rec SET book_issu=book_arr(book_type(1006,'Corba','Sun MicroS'),
book_type(1007,'Java beans','Sun MicroS'),
book_type(1008,'Java servlates','Sun MicroS'))
WHERE stno = 1002;
VARRAYs in PL/SQL
To modify a stored VARRAY, it has to be selected into a PL/SQL variable and then inserted back
into the table. This technique is illustrated below :
Collections in Oracle
Example 1 : Update a particular column in the VARRAY.
DECLARE
bk_arr
book_arr;
BEGIN
SELECT book_issu INTO bk_arr FROM stud_rec WHERE stno=1002;
FOR i IN 1..bk_arr.COUNT
LOOP
IF bk_arr(i).book_no=1006 THEN
bk_arr(i).book_name :='VC++';
END IF;
END LOOP;
UPDATE stud_rec SET book_issu = bk_arr WHERE stno=1002;
END;
Example 2 : Insert a new row in the VARRAY.
DECLARE
bk_arr
book_arr;
BEGIN
SELECT book_issu INTO bk_arr FROM stud_rec WHERE stno=1002;
bk_arr.EXTEND;
bk_arr(bk_arr.COUNT):=book_type(1011,'Web tool','BPB');
UPDATE stud_rec SET book_issu = bk_arr WHERE stno=1002;
END;
Differences :
VARRAYs have a maximum size, as specified at the time of creation, while Nested Table do
not
VARRAYs stored inline with the containing table, while Nested Tables are stored in a
separate table which can have different storage characteristics
Rows in the Nested Table can be accessed individually by using the THE clause, where as
in the VARRAYs all the rows should be accessed as one object and is to be manipulated
using PL/SQL blocks
Collections in Oracle
A
ABORT
ACCEPT
ACCESS
ADD
ALL
ALTER
AND
ANY
ARRAY
AS
ASC
ASSIGN
AT
AUTHORIZATION
AVG
B
BASE_TABLE
BEGIN
BETWEEN
BINARY_INTEGER
BODY
BOLEAN
BY
C
CASE
CHAR
CHAR_BASE
CHECK
CLOSE
CLUSTER
COLAUTH
COLUMNS
COMMIT
COMPRESS
CONNECT
CONSTANT
COUNT
CRASH
CREATE
CURRENT
CURSOR
CURRVAL
D
DATABASE
DATA_BASE
DATE
DBA
DEBUGOFF
DEBOGON
DECLARE
DECIMAL
DEFAULT
DEFINITION
DELAY
DELETE
DESC
DIGITS
DISTINCT
DO
DROP
E
ELSE
ELSIF
END
ENTRY
EXCEPTION
EXISTS
EXIT
F
FALSE
FETCH
FLOAT
FOR
FORM
FROM
FUNCTION
G
GENERIC
GOTO
O
OF
ON
OPEN
OPTION
GRANT
OR
GROUP
ORDER
H
OTHERS
HAVING
P
I
PUT
IDENTIFIED
PACKAGE
IF
PARTITION
IN
PRAGMA
INDEX
PRIOR
INDICATOR
PRIVATE
INSERT
PROCEDURE
INTEGER
PUBLIC
INTERSECT
R
INTO
RAISE
IS
RANGE
L
REAL
LEVEL
RECORD
LIKE
RELEASE
LEMETED
REM
LOOP
RENAME
M
RESOURSE
MAX
RETURN
MIN
REVERSE
MINUS
REVOKE
MOD
ROLLBACK
N
ROWID
NATURAL
ROWLABEL
NEW
ROWNUM
NEXTVAL
ROWTYPE
NOT
RUN
NULL
S
NUMBER
SAVEPOINT
NUMBER_BAS SCHEMA
SELECT
SET
SIZE
SMALLINT
SPACE
SQL
SQLCODE
SQLERR
START
STATEMENT
SUM
T
TABAUTH
TABLE
TABLES
TASK
TERMINATE
THETON
TRUE
TYPE
U
UNION
UNIQUE
UPDATE
USE
V
VALUES
VARCHAR
VARCHAR2
VIEW
VIEWS
W
WHEN
WHERE
WHILE
WITH
WORK
Collections in Oracle
Table Structure
EMP table :
Column name
EMPNO
ENAME
JOB
MGR
HIREDATE
SAL
COMM
DEPTNO
Type
NUMBER(4)
VARCHAR2(20)
CHAR(10)
NUMBER(4)
DATE
NUMBER(9,2)
NUMBER(7,2)
NUMBER(2)
Description
Employee number
Employee name
Designation
Respective managers EMPNO
Date of joining
Basic salary
Commission
Department number
DEPT table :
Column name
DEPTNO
DNAME
LOC
Type
NUMBER(2)
VARCHAR2(20)
VARCHAR2(10)
Description
Department number
Name of the department
Location of the department
INCR table :
Column name
EMPNO
AMT
DATEINCR
Type
NUMBER(4)
VARCHAR2(20)
DATE
Description
Employee number
Incremented amount
Date of increment
ITEMMAST table :
Column name
ITNO
NAME
QOH
CLASS
ROL
RATE
Type
NUMBER(4)
VARCHAR2(20)
NUMBER(5)
CHAR(1)
NUMBER(5)
NUMBER(8,2)
Description
Item number
Item description
Quantity on hand
Category of item
Reorder quantity
Unit price of sale
ITTRAN table :
Column name
ITNO
UPD_FLAG
TRANTYPE
TRANDATE
QTY
Type
NUMBER(4)
CHAR(1)
CHAR(1)
DATE
NUMBER(5)
Description
Item number
Master updated ( Y/N )
Transaction type
Transaction date
Transaction quantity
Collections in Oracle
Hands on Session
Session 1
Write an appropriate SQL statement for the following : 01. List all details of those employees who are getting salary more than 1500.
02. List all the employees who are working on department 20 & 30.
03. List all the clerk details who are working on department 10 & 30.
04. List all the employees details who are getting commission.
05. List all the employees details who are getting no commission but the salary must be
greater than 2000.
06. List all the employees details who does not reported anybody.
07. List all the jobs available in the emp table.
08. List all the location available in the dept table.
09. List all the employees details according to their salary priority.
10. List the number of jobs available in the emp table.
11. List the maximum salary of employee working as a salesman.
12. List the average salary of employee working as a salesman.
13. List the jobs and the number of employees in each job. The result should be in
descending order of the number of employees.
14. List the total salary job wise.
15. List the average salary for each job excluding managers.
16. List the average salary for each job type within department.
17. List average salary for all departments employing more than five people.
18. List the employee details and the department name.
19. List the employee details and the department name even if no employee belongs to
that department.
20. List all the employee name along with their manager. Also show the employee name
who is not reporting to anyone.
21. List all the employees of department 30 who joined the company before their manager.
22. Display the different designations in the department 20 and 30.
23. List the jobs common to department 20 and 30.
24. List the jobs unique to the department 20.
25. List the names of the employee drawing the highest salary.
26. List the job with highest average salary.
27. List the names of the employees, who earn lowest salary in each department.
28. List employee details who earn salary greater than the average salary for their department.
29. List all employees who have at least one person reporting to them.
30. List all employees whose salary is greater than any of the manager.
31. List all employees who do not manages any one.
32. List the details of the employee earning more than the highest paid manager.
33. List the employee details who earn highest salary for their job.
34. List the details of those employees who are among the five highest earners of the company.
Collections in Oracle
Session 2
Create the following tables :
BANK_MAIN
Field Name
ACC_NO
NAME
ADDRESS
ACC_TYPE
OPEN_BAL
CURR_BAL
Description
Account number
Account holder
Address of account holder
Type of account
Opening balance
Current balance
Constraints
Primary Key
NOT NULL
NOT NULL
NOT NULL
Description
Account number
Transaction date
Type of Transaction
Transaction amount
Master update ( Y/N)
Constraints
FK to bank_main
NOT NULL
NOT NULL
NOT NULL
Deposit ( D ) , Withdrawal ( W )
Description
Account number
Interest amount
Constraints
FK to bank_main
NOT NULL
Appendix C
Session 3
Create two tables with the following fields :
STUDMAST
Field Name
Stno
Stnm
Btcd
Btrlno
Crnm
Rgdt
Stdt
Pat
Totfee
Duefee
Description
Student ID
Student name
Batch Code
Batch Roll NO.
Course Name
Registration Date
Starting Date
Pattern
Total Fees
Due Fees
Constraints
Primary Key
NOT NULL
NOT NULL
Description
Student ID
Paid Date
Fees Paid
Constraints
FK to STUDMUST
NOT NULL
Project
Project
Stock
must be for one and only one item
Purchase Order
must be having one or more Purchase Order Details
may be having in one or more Goods Inward Headers
must be raised to one and only one suppliers
Supplier
may be raised one or more Purchase Order
Goods Inward Detail
must be for one and only one Goods Inward Header
must be for one and only one item
Purchase Order Detail
must be for one and only one Purchase Order
must be containing one and only one item
ATTRIBUTES
ITEM
Item Number
Item Description
Quantity on hand
Item classification
Unit of measurement
Reorder level
Reorder quantity
Item rate
STOCK
Item code
Opening balance
Opening balance date
Item classification
Year to date receipts
Year to date issues
SUPPLIER
Supplier code
Supplier name
Street
City
State
ZIP
Phone
PURCHASE ORDER
Quantity ordered
Rate
Quantity received
Quantity accepted
Rate
Project
Tables and Keys
ITEMMAST
Attributes
Item Number
Item Description
Quantity on Hand
Item Classification
Unit of Measurement
Reorder Level
Reorder Quantity
Item Rate
Columns
ITNO
NAME
QOH
CLASS
UOM
ROL
ROQ
RATE
Datatype/size
NUMBER(4)
VARCHAR2(20)
NUMBER(5)
VARCHAR2(1)
VARCHAR2(4)
NUMBER(5)
NUMBER(5)
NUMBER(8,2)
Constraints
Primary Key
NOT NULL
Default 100
NOT NULL
NOT NULL
Columns
ITNO
OPBAL
OPBALDATE
Datatype/size
NUMBER(4)
NUMBER(8,2)
DATE
YTDRCV
YTDISS
NUMBER(8,2)
NUMBER(8,2)
SUPPLIER
Attributes
Supplier Code
Supplier Name
Street
City
State
ZIP
Phone
Columns
SUPCODE
SUPNAME
STREET
CITY
STATE
ZIP
PHONE
GINHEAD
Attributes
Goods inward number
Goods inward date
Supplier Code
Purchase order number
Columns
GINNO
GINDATE
SUPCODE
PONO
Datatype/size
NUMBER(4)
VARCHAR2(25)
VARCHAR2(25)
VARCHAR2(25)
VARCHAR2(25)
VARCHAR2(25)
VARCHAR2(25)
Datatype/size
NUMBER(4)
DATE
NUMBER(4)
NUMBER(4)
Constraints
Primary Key
NOT NULL
NOT NULL
Constraints
Primary Key
NOT NULL
NOT NULL
Constraints
Primary Key
NOT NULL
FK to SUPPLIER
FK to POHEAD
Project
GIN value
GINDETAIL
Attributes
Goods inward number
Item code
Quantity received
Quantity accepted
Rate
Purchase order number
GINVAL
NUMBER(8,2)
Columns
GINNO
GINITEM
GINQTY
GINACCEPT
GINRATE
PONO
Datatype/size
NUMBER(4)
NUMBER(4)
NUMBER(4)
NUMBER(4)
NUMBER(8,2)
NUMBER(4)
Default 0
Constraints
FK to GINHEAD
FK to ITEMMAST
NOT NULL
NOT NULL
NOT NULL
Columns
PONO
PODATE
DELIDATE
PURVALUE
SUPCODE
POSTAT
PODETAIL
Attributes
Quantity ordered
Rate
Item number
Purchase order number
Quantity received
Columns
POQTY
PORATE
POITNO
PONO
PORECV
Datatype/size
NUMBER(4)
DATE
DATE
NUMBER(8,2)
NUMBER(4)
VARCHAR2(1)
Datatype/size
NUMBER(4)
NUMBER(4)
NUMBER(4)
NUMBER(4)
NUMBER(4)
Constraints
Primary Key
NOT NULL
NOT NULL
Default 0
FK to SUPPLIER
Check I,N,C or F
Default N
Constraints
NOT NULL
NOT NULL
FK to ITEMMAST
FK to POHEAD
Project
3. When all the items in required quantities for a particular purchase order has been
accepted, disallow further generation of GINs.
4. The GIN value will be automatically calculated from the quantity accepted and rate.
Goods Inward Detail (GINDETAIL)
1. The items for GINDETAIL must be the same as present in the PODETAIL. To perform
this operation, retrieve all the PO details and prepare the GIN details for those items only.
2. The PO number can be maintained in the GINDETAIL table, through which the item and
the quantity ordered in a particular PO can be easily retrieved. The value for this column
will be automatically derived from the GINHEAD.
3. The GIN quantity received must be less than or equal to the quantity ordered for that
item. In case a PO is received in parts, the further GINs must be generated for the
remaining items and / or quantities only.
4. When the quantity accepted is entered, the quantity on hand of ITEMMAST table must
be updated. This can be done using DB Trigger on GINDETAIL table.
Purchase Order ( PO )
1. A PO can have four state, viz. New, Incomplete, Fully received or Canceled. An
additional column must be added to the PO which will indicate the state so that a GIN
can be generated for the POs which are New or Incomplete only. The proposed Datatype
and length of this column is VARCHAR2(1) and the allowable values are :
N : New
C : Canceled
I : Incomplete
F : Fully received or complete.
2. The PO value will be calculated automatically by multiplying the quantity ordered and
the rate from the PODETAIL table.
Purchase Order Detail ( PODETAIL )
1. A column can be added to PODETAIL, which will contain the quantity accepted by a
GIN. Each time a GIN is accepted, the quantity received ( in PODETAIL ) against a
particular item can be updated. This helps us in retrieving the remaining quantities of a
particular item to be received more efficiently.
2. Create a unique index on PONP + POITNO, which will help in retrieving a particular
item in a PO from the PODETAIL.
Project
Development Methodology
The following Database Triggers, Procedure, Reports, Entry Screens suggested.
Reports/Queries and Entry screens
1.
2.
3.
4.
5.
6.
Database Triggers
GINDETAIL
This trigger will fire after insertions of each row into GINDETAIL. The following functions
will be performed after execution of this trigger :
1. QOH column of the ITEMMUST table will be updated by adding the quantity accepted.
2. QTYRECV column in PODETAIL will be updated by adding the quantity accepted.
Procedures and Functions
1.
2.
3.
4.
5.
6.
7.
Calculate PO value.
Get pending Pos from the POHEAD.
Get pending items, qty ordered and qty received from the PODETAIL.
Update QOH in ITEMMUST.
Update the quantity accepted ( PORECV ) in PODETAIL.
Update the POSTAT in PO.
Get GIN numbers for a PO.
Item
Master
Transaction
Supplier
Master
Stock
Master
Purchase
Order
Query
GoodsInward Note