Rdbms Theory
Rdbms Theory
html
Advantages of DBMS.
Due to its centralized nature, the database system can overcome the disadvantagesof the file
system-based system
1. Data independency:
Application program should not be exposed to details of data representation and storage
DBMS provides the abstract view that hides these details.
2. Efficient data access.:
DBMS utilizes a variety of sophisticated techniques to store and retrieve dataefficiently.
3. Data integrity and security:
Data is accessed through DBMS, it can enforce integrity constraints.
E.g.: Inserting salary information for an employee.
4. Data Administration:
When users share data, centralizing the data is an important task, Experienceprofessionals can
minimize data redundancy and perform fine tuning which reducesretrieval time.
5. Concurrent access and Crash recovery:
DBMS schedules concurrent access to the data. DBMS protects user from the effects
ofsystem failure.
6. Reduced application development time.
DBMS supports important functions that are common to many applications
Page 1 of 208
Architecture of DBMS
Page 2 of 208
Levels of abstraction in DBMS
External - individual user view
Conceptual - community user view
Internal - physical or storage view
Schema: A description of data in terms of a data model is called a schema. In the relational
model, the schema for a relation specifies its name, the name of each field, and the type of
each field. As an example
Employee(eid: string, ename: string, street:string, city:real)
WORKS ( eid:string, cid:string, salary:real)
COMPANY(cid:string, company-name:string,city:string)
MANAGERS (mid:string, eid:string, cid:string, manager-name:string)
Conceptual schema:
Also called as logical schema describes the stored data in terms of the data model of the
RDBMS. This describes all relations that are stored in the database.
Physical Schema:
This specifies the storage details. This shows how the relations described in conceptual
schema are actually stored on secondary storage devices. It describes about what file
organizations is used, which data structures are used, usage of indexes to retrieve the speedy
retravel operations.
External Schema:
External schemas allow data access to be customized at the level of individual users or
groups.Any given database has exactly one conceptual schema and one physical schema because it has
just one set of stored relations, but it may have several external schemas, each tailored to a particular group
of users. Each external schema consists of a collection of one or more views and relations from the
conceptual schema. A view is conceptually a relation, but the records in a view are not stored in the
DBMS.
The three level database architecture allows a clear separation of the information
meaning(conceptual view) from the external data representation and from the physical
datastructure layout. A database system that is able to separate the three different views
ofdata is likely to be flexible and adaptable. This flexibility and adaptability is
dataindependence that we have discussed earlier.
The external level is the view that the individual user of the database has. This view isoften a
restricted view of the database and the same database may provide a number ofdifferent
views for different classes of users. In general, the end users and even the application
programmers are only interested in a subset of the database. For example, adepartment head
may only be interested in the departmental finances and studentenrolments but not the library
information. The librarian would not be expected to haveany interest in the information about
academic staff. The payroll office would have nointerest in student enrolments.
The conceptual view is the information model of the enterprise and contains the view ofthe
whole enterprise without any concern for the physical implementation. This view isnormally
more stable than the other two views. In a database, it may be desirable tochange the internal
view to improve performance while there has been no change in theconceptual view of the
database. The conceptual view is the overall community view ofthe database and it includes
all the information that is going to be represented in thedatabase. The conceptual view is
defined by the conceptual schema which includesdefinitions of each of the various types of
data.
Page 3 of 208
The internal view is the view about the actual physical storage of data. It tells us whatdata is
stored in the database and how. At least the following aspects are considered atthis level:
Storage allocation e.g. B-trees, hashing etc.
Access paths e.g. specification of primary and secondary keys, indexes and
pointers and sequencing.
Miscellaneous e.g. data compression and encryption techniques, optimization of
the internal structures.
Efficiency considerations are the most important at this level and the datastructures are
chosen to provide an efficient database. The internal view does not dealwith the physical
devices directly. Instead it views a physical device as a collection ofphysical pages and
allocates space in terms of logical pages.
The separation of the conceptual view from the internal view enables us toprovide a logical
description of the database without the need to specify physicalstructures. This is often called
physical data independence. Separating the external viewsfrom the conceptual view enables
us to change the conceptual view without affecting theexternal views. This separation is
sometimes called logical data independence.
Assuming the three level view of the database, a number of mappings are needed toenable the
users working with one of the external views. For example, the payroll officemay have an
external view of the database that consists of the following informationonly:
Staff number, name and address.
Staff tax information e.g. number of dependents.
Staff bank information where salary is deposited.
Staff employment status, salary level, leave information etc.
The conceptual view of the database may contain academic staff, general staff, casualstaff
etc. A mapping will need to be created where all the staff in the different categoriesare
combined into one category for the payroll office. The conceptual view would
includeinformation about each staff's position, the date employment started, full-time or part-
timeetc. This will need to be mapped to the salary level for the salary office. Also, ifthere is
some change in the conceptual view, the external view can stay the same if themapping is
changed.
Attribute example
Page 4 of 208
Composite attribute
Metadata
Metadata characterizes data. It is used to provide documentation such that data can be understood
and more readily consumed by your organization. Metadata answers the who, what, when, where,
why, and how questions for users of the data.In addition to managing data, corporations must to be
able to manage and control the definition of the data elements used in databases. Without an
understanding of the structure, limitations, definition, and description of data, it is likely that data will
be misinterpreted or misused; further, data that is not well-defined can cause database integrity
problems. This is a metadata issue.
In order for data to be anything more than simply data, metadata is required. Without metadata, data
has no identifiable meaning – it is merely a collection of digits, characters, or bits. Metadata gives
data its form and makes it usable by information professionals.
most DBMSs store all of the following metadata in the system catalog:
The names of every database, table, column, index, view, relationship, stored
procedure, trigger, and so on.
The primary key for each table and any foreign keys that refer back to that primary
key.
Which tables are in which views.
The data type, length, and constraints for each column of every table.
The names of the physical files used to store database data, as well as information
about file storage, extents, and disk volumes.
Authorization and security information detailing which users have what type of
authority on which database objects.
The date and time of the last database definition change, as well as the ID of the user
who implemented the DDL for the change.
Database organization information.
For example, a digital image may include metadata that describes how large the picture is, the color
depth, the image resolution, when the image was created, the shutter speed, and other data. A text
document's metadata may contain information about how long the document is, who the author is,
when the document was written, and a short summary of the document. Metadata within web pages
can also contain descriptions of page content, as well as key words linked to the content. These links
are often called "Metatags", which were used as the primary factor in determining order for a web
Page 5 of 208
search until the late 1990s. The reliance of metatags in web searches was decreased in the late 1990s
because of "keyword stuffing". Metatags were being largely misused to trick search engines into
thinking some websites had more relevance in the search than they really did.Web pages often include
metadata in the form of meta tags. Description and keywords in meta tags are commonly used to
describe the Web page's content. Meta elements also specify page description, key words, authors of
the document, and when the document was last modified. Web page metadata helps search engines
and users to find the types of web pages they are looking for.
Set operations
Relations in relational algebra are seen as sets of tuples, so we can use basic set operations.
Projection
Example: The table E (for EMPLOYEE)
nr name salary
1 John 100
5 Sarah 300
7 Tom 100
salary
select salary
from E 100 PROJECTsalary(E)
300
nr salary
7 100
Selection
The same table E (for EMPLOYEE) as above.
Page 6 of 208
1 John 100
where salary < 200
7 Tom 100
select *
from E nr name salary
where salary < 200 SELECTsalary < 200 and nr >= 7(E)
and nr >= 7 7 Tom 100
Example:
Page 7 of 208
Cartesian product
The cartesian product of two tables combines each row in one table with each row in the other table.
1 Bill A
2 Sarah C
3 John A
dnr dname
A Marketing
B Sales
C Legal
1 Bill A A Marketing
1 Bill A B Sales
1 Bill A C Legal
2 Sarah C C Legal
3 John A A Marketing
3 John A B Sales
3 John A C Legal
Page 8 of 208
Join (sometimes called "inner join")
The cartesian product example above combined each employee with each department. If we only keep
those lines where the dept attribute for the employee is equal to the dnr (the department number) of
the department, we get a nice list of the employees, and the department that each employee works for:
Natural join
A normal inner join, but using the join condition that columns with the same names should be equal.
Duplicate columns are removed.
nr name dept
1 Bill A
2 Sarah C
3 John A
nr Name
A Marketing
B Sales
C Legal
Page 9 of 208
Several columns in the result will have the same name (nr and name).
How do we express the join condition, when there are two columns called nr?
Solutions:
3 John A A Marketing
You can use another variant of the renaming operator to change the name of a table, for
example to change the name of E to R. This is necessary when joining a table with itself (see
below).
RENAMER(E)
A third variant lets you rename both the table and the columns:
RENAMER(enr, ename, dept)(E)
Aggregate functions
Example: The table E (for EMPLOYEE)
1 John 100 A
5 Sarah 300 C
7 Tom 100 A
12 Anne null C
Page 10 of 208
from E
500
Note:
Result:
select count(salary)
from E count Fcount(salary)(E)
Result:
select count(distinct salary)
from E count Fcount(salary)(PROJECTsalary(E))
dept sum
select sum(salary)
from E
group by dept A 200 F (E)
dept sum(salary)
C 300
C 300 1
Page 11 of 208
Hierarchies
Example: The table E (for EMPLOYEE)
nr name mgr
1 Gretchen null
2 Bob 1
5 Anne 2
6 John 2
3 Hulda 1
4 Hjalmar 1
7 Usama 4
Outer join
Example: The table E (for EMPLOYEE)
1 Bill A
2 Sarah C
3 John A
dnr dname
A Marketing
B Sales
C Legal
List each employee together with the department he or she works at:
Page 12 of 208
No employee works at department B, Sales, so it is not present in the result. This is probably
not a problem in this case. But what if we want to know the number of employees at each
department?
Use a right outer join, which keeps all the rows from the right table. If a row can't be
connected to any of the rows from the left table according to the join condition, null values
are used:
1 Bill A A Marketing
select *
from (E right outer join D on edept = E RIGHT OUTER JOINedept = dnr
dnr) 2 Sarah C C Legal
D
3 John A A Marketing
C Legal 1
Page 13 of 208
C Legal 1
Join types:
Outer union
Outer union can be used to calculate the union of two relations that are partially union compatible.
Not very common.
A B
1 2
3 4
B C
4 5
6 7
A B C
1 2 null
3 4 5
null 6 7
Normalization of Database
Page 14 of 208
Database Normalisation is a technique of organizing the data in the database. Normalization
is a systematic approach of decomposing tables to eliminate data redundancy and undesirable
characteristics like Insertion, Update and Deletion Anomalies. It is a multi-step process that
puts data into tabular form by removing duplicated data from the relation tables.
Without Normalization, it becomes difficult to handle and update the database, without facing
data loss. Insertion, Updation and Deletion Anamolies are very frequent if Database is not
Normalized. To understand these anomalies let us take an example of Student table.
Updation Anamoly : To update address of a student who occurs twice or more than twice in
a table, we will have to update S_Address column in all the rows, else data will become
inconsistent.
Insertion Anamoly : Suppose for a new admission, we have a Student id(S_id), name and
address of a student but if student has not opted for any subjects yet then we have to insert
NULL there, leading to Insertion Anamoly.
Deletion Anamoly : If (S_id) 401 has only one subject and temporarily he drops it, when we
delete that row, entire student record will be deleted along with it.
Normalization Rule
Page 15 of 208
First Normal Form (1NF)
As per First Normal Form, no two Rows of data must contain repeating group of information
i.e each set of column must have a unique value, such that multiple columns cannot be used
to fetch the same row. Each table should be organized into rows, and each row should have a
primary key that distinguishes it as unique.
The Primary key is usually a single column, but sometimes more than one column can be
combined to create a single primary key. For example consider a table which is not in First
normal form
Student Table :
Alex 14 Maths
Stuart 17 Maths
In First Normal Form, any row must not have a column in which more than one value is
saved, like separated with commas. Rather than that, we must separate such data into multiple
rows.
Adam 15 Biology
Adam 15 Maths
Alex 14 Maths
Stuart 17 Maths
Using the First Normal Form, data redundancy increases, as there will be many columns with
same data in multiple rows but each row as a whole will be unique.
As per the Second Normal Form there must not be any partial dependency of any column on
primary key. It means that for a table that has concatenated primary key, each column in the
table that is not part of the primary key must depend upon the entire concatenated key for its
Page 16 of 208
existence. If any column depends only on one part of the concatenated key, then the table
fails Second normal form.
In example of First Normal Form there are two rows for Adam, to include multiple subjects
that he has opted for. While this is searchable, and follows First normal form, it is an
inefficient use of space. Also in the above Table in First Normal Form, while the candidate
key is {Student, Subject}, Age of Student only depends on Student column, which is
incorrect as per Second Normal Form. To achieve second normal form, it would be helpful to
split out the subjects into an independent table, and match them up using the student names as
foreign keys.
Student Age
Adam 15
Alex 14
Stuart 17
In Student Table the candidate key will be Student column, because all other column i.e Age
is dependent on it.
Student Subject
Adam Biology
Adam Maths
Alex Maths
Stuart Maths
In Subject Table the candidate key will be {Student, Subject} column. Now, both the above
tables qualifies for Second Normal Form and will never suffer from Update Anomalies.
Although there are a few complex cases in which table in Second Normal Form suffers
Update Anomalies, and to handle those scenarios Third Normal Form is there.
Third Normal form applies that every non-prime attribute of table must be dependent on
primary key, or we can say that, there should not be the case that a non-prime attribute is
determined by another non-prime attribute. So this transitive functional dependency should
Page 17 of 208
be removed from the table and also the table must be in Second Normal form. For example,
consider a table with following fields.
Student_Detail Table :
In this table Student_id is Primary key, but street, city and state depends upon Zip. The
dependency between zip and other fields is called transitive dependency. Hence to apply
3NF, we need to move the street, city and state to new table, with Zip as primary key.
Address Table :
Boyce and Codd Normal Form is a higher version of the Third Normal form. This form
deals with certain type of anamoly that is not handled by 3NF. A 3NF table which does not
have multiple overlapping candidate keys is said to be in BCNF. For a table to be in BCNF,
following conditions must be satisfied:
Page 18 of 208
Example 2
Example: Suppose a manufacturing company stores the employee details in a table named
employee that has four attributes: emp_id for storing employee’s id, emp_name for storing
employee’s name, emp_address for storing employee’s address and emp_dept for storing the
department details in which the employee works. At some point of time the table looks like
this:
The above table is not normalized. We will see the problems that we face when a table is not
normalized.
Update anomaly: In the above table we have two rows for employee Rick as he belongs to
two departments of the company. If we want to update the address of Rick then we have to
update the same in two rows or the data will become inconsistent. If somehow, the correct
address gets updated in one department but not in other then as per the database, Rick would
be having two different addresses, which is not correct and would lead to inconsistent data.
Page 19 of 208
Insert anomaly: Suppose a new employee joins the company, who is under training and
currently not assigned to any department then we would not be able to insert the data into the
table if emp_dept field doesn’t allow nulls.
Delete anomaly: Suppose, if at a point of time the company closes the department D890 then
deleting the rows that are having emp_dept as D890 would also delete the information of
employee Maggie since she is assigned only to this department.
To overcome these anomalies we need to normalize the data. In the next section we will
discuss about normalization.
Normalization
As per the rule of first normal form, an attribute (column) of a table cannot hold multiple
values. It should hold only atomic values.
Example: Suppose a company wants to store the names and contact details of its employees.
It creates a table that looks like this:
8812121212
102 Jon Kanpur
9900012222
103 Ron Chennai 7778881212
9990000123
104 Lester Bangalore
8123450987
Two employees (Jon & Lester) are having two mobile numbers so the company stored them
in the same field as you can see in the table above.
This table is not in 1NF as the rule says “each attribute of a table must have atomic (single)
values”, the emp_mobile values for employees Jon & Lester violates that rule.
To make the table complies with 1NF we should have the data like this:
Page 20 of 208
101 Herschel New Delhi 8912312390
An attribute that is not part of any candidate key is known as non-prime attribute.
Example: Suppose a school wants to store the data of teachers and the subjects they teach.
They create a table that looks like this: Since a teacher can teach more than one subjects, the
table can have multiple rows for a same teacher.
111 Maths 38
111 Physics 38
222 Biology 38
333 Physics 40
333 Chemistry 40
The table is in 1 NF because each attribute has atomic values. However, it is not in 2NF
because non prime attribute teacher_age is dependent on teacher_id alone which is a proper
subset of candidate key. This violates the rule for 2NF as the rule says “no non-prime
attribute is dependent on the proper subset of any candidate key of the table”.
To make the table complies with 2NF we can break it in two tables like this:
teacher_details table:
teacher_id teacher_age
Page 21 of 208
111 38
222 38
333 40
teacher_subject table:
teacher_id subject
111 Maths
111 Physics
222 Biology
333 Physics
333 Chemistry
An attribute that is not part of any candidate key is known as non-prime attribute.
In other words 3NF can be explained like this: A table is in 3NF if it is in 2NF and for each
functional dependency X-> Y at least one of the following conditions hold:
An attribute that is a part of one of the candidate keys is known as prime attribute.
Example: Suppose a company wants to store the complete address of each employee, they
create a table named employee_details that looks like this:
Page 22 of 208
1201 Steve 222999 MP Gwalior Ratan
To make this table complies with 3NF we have to break the table into two tables to remove
the transitive dependency:
employee table:
employee_zip table:
It is an advance version of 3NF that’s why it is also referred as 3.5NF. BCNF is stricter than
3NF. A table complies with BCNF if it is in 3NF and for every functional dependency X->Y,
X should be the super key of the table.
Page 23 of 208
Example: Suppose there is a company wherein employees work in more than one
department. They store the data like this:
The table is not in BCNF as neither emp_id nor emp_dept alone are keys.
To make the table comply with BCNF we can break the table in three tables like this:
emp_nationality table:
emp_id emp_nationality
1001 Austrian
1002 American
emp_dept table:
emp_dept_mapping table:
emp_id emp_dept
1001 Stores
Page 24 of 208
1002 design and technical support
Functional dependencies:
emp_id -> emp_nationality
emp_dept -> {dept_type, dept_no_of_emp}
Candidate keys:
For first table: emp_id
For second table: emp_dept
For third table: {emp_id, emp_dept}
This is now in BCNF as in both the functional dependencies left side part is a key.
Third example
In the above table all the students belong to CSE branch. In this the branch, hod,
and office_tel fields have the same data which is data redundancy.
Updation anomaly
What if Mr.X leaves teh college? Or no longer the HOD of computer science
department? In which case all the students record has to be updated with new data.
Even if one record is missed out from updation then this will lead to data
inconsistency.
Deletion anomaly
If the students record is deleted, then we lose the branch details also.
Normalization Rule
Page 25 of 208
4. BCNF
5. Fourth Normal Form
For a table to be in the First Normal Form, it should follow the following 4 rules:
Ie. In the column designated for date of birth should not be used for storing name
of a person. If a column is designated to store last name of a person, first name
should not be stored.
In the above table rule 2,3,4 are satisfied but rule 1 is violated as subject column
consists of multiple values.
To satisfy this rule the multiple values are to be written as single values like
below:
Page 26 of 208
101 Akon CN
103 Ckon Java
102 Bkon C
102 Bkon C++
For a table to be in the Second Normal Form, it must satisfy two conditions:
What is dependency?
Let's take an example of a Student table with columns student_id, name, reg_no(registration
number), branch and address(student's home address).
In this table, student_id is the primary key and will be unique for every row, hence we can use
student_id to fetch any row of data from this table
Even for a case, where student names are same, if we know the student_id we can easily fetch
the correct record.
Hence we can say a Primary Key for a table is the column or a group of columns(composite
key) which can uniquely identify each record in the table. If we have the student_id then we
will be able to extract that particular record. All the columns depent on student_id (primary
key). This is called dependency otherwise functional dependency.
Consider another table which consists of subject details wher subject_id is the primary key.
subject_id subject_name
1 Java
2 C++
3 Php
Let there be another table called Score, to store marks obtained by students in the respective
subjects.
Page 27 of 208
score_id student_id subject_id marks teacher
1 10 1 70 Java Teacher
2 10 2 75 C++ Teacher
3 11 1 80 Java Teacher
In the above the non-key element techer depend only on subject_id not on student_id. This is
Partial Dependency, where an attribute in a table depends on only a part of the primary key and not
on the whole key.
This can be done by removing teacher column from score table and keep it in subjet table as follows:
Subject table:
Score table:
1. For a table to be in the Second Normal form, it should be in the First Normal form
and it should not have Partial Dependency.
2. Partial Dependency exists, when for a composite primary key, any attribute in the
table depends only on a part of the primary key and not on the complete primary key.
3. To remove Partial dependency, we can divide the table, remove the attribute which is
causing partial dependency, and move it to some other table where it fits in well.
In the scoretable , add two more column, exam _name and total_marks.
Page 28 of 208
What is transitive dependency?
When a non-prime attribute depends on other non-prime attributes rather than depending upon the
prime attributes or primary key.
For example in the above table, the column total_marks depends on exam_name as with exam
type the total score changes. For example, practicals are of less marks while theory exams are
of more marks.
But, exam_name is just another column in the score table. It is not a primary key or even a part
of the primary key, and total_marks depends on it. This is called transitive dependency.
This should be removed. How to remoce this? The columns exam_name and total_marks can
be removed from Score table and put then in an Exam table and use exam_id wherever
required.
Exam table
For a table to satisfy the Boyce-Codd Normal Form, it should satisfy the following two
conditions:
The second point sounds a bit tricky, right? In simple words, it means, that for a dependency
A → B, A cannot be a non-prime attribute, if B is a prime attribute.
Page 29 of 208
Example
Enrollement table
One more important point to note here is, one professor teaches only one subject, but one
subject may have two different professors.
Hence, there is a dependency between subject and professor here, where subject depends on the
professor name.
This table satisfies the 1st Normal form because all the values are atomic, column names are
unique and all the values stored in a particular column are of same domain.
This table also satisfies the 2nd Normal Form as their is no Partial Dependency.
And, there is no Transitive Dependency, hence the table also satisfies the 3rd Normal
Form.
In the table above, student_id, subject form primary key, which means subjectcolumn is a prime
attribute.
And while subject is a prime attribute, professor is a non-prime attribute, which is not allowed
by BCNF.
To make this relation(table) satisfy BCNF, we will decompose this table into two tables,
student table and professor table.
Page 30 of 208
Below we have the structure for both the tables.
Student Table
student_id p_id
101 1
101 2
and so on...
And now, this relation satisfy Boyce-Codd Normal Form. In the next tutorial we will learn
about the Fourth Normal Form.
E-R Diagram
ER-Diagram is a visual representation of data that describes how data is related to each other.
Page 31 of 208
Symbols and Notations
1) Entity
An Entity can be any object, place, person or class. In E-R Diagram, an entity is represented
using rectangles. Consider an example of an Organisation. Employee, Manager, Department,
Product and many more can be taken as entities from an Organisation.
Page 32 of 208
Weak Entity
Weak entity is an entity that depends on another entity. Weak entity doesn't have key
attribute of their own. Double rectangle represents weak entity.
2) Attribute
Page 33 of 208
Key Attribute
Key attribute represents the main characteristic of an Entity. It is used to represent Primary
key. Ellipse with underlying lines represent Key Attribute.
Composite Attribute
An attribute can also have their own attributes. These attributes are known as Composite
attribute.
3) Relationship
Page 34 of 208
Binary Relationship
Recursive Relationship
Ternary Relationship
Binary Relationship
Binary Relationship means relation between two Entities. This is further divided into three
types.
The above example describes that one student can enroll only for one course and a
course will also have only one Student. This is not what you will usually see in
relationship.
2. One to Many : It reflects business rule that one entity is associated with many number of
same entity. The example for this relation might sound a little weird, but this means that one
student can enroll to many courses, but one course will have one Student.
The arrows in the diagram describes that one student can enroll for only one course.
Page 35 of 208
3. Many to One : It reflects business rule that many entities can be associated with just one
entity. For example, Student enrolls for only one Course but a Course can have many
Students.
4. Many to Many :
The above diagram represents that many students can enroll for more than one
courses.
Recursive Relationship
Page 36 of 208
Ternary Relationship
Generalization
Generalization is a bottom-up approach in which two lower level entities combine to form a
higher level entity. In generalization, the higher level entity can also combine with other
lower level entity to make further higher level entity.
Specialization
Page 37 of 208
Aggregation
Aggregation is a process when relation between two entity is treated as a single entity. Here
the relation between Center and Course, is acting as an Entity in relation with Visitor.
Introduction to SQL
Structure Query Language(SQL) is a programming language used for storing and managing
data in RDBMS. SQL was the first commercial language introduced for E.F Codd's
Relational model. Today almost all RDBMS(MySql, Oracle, Infomix, Sybase, MS Access)
uses SQL as the standard database language. SQL is used to perform all type of data
operations in RDBMS.
SQL Command
All DDL commands are auto-committed. That means it saves all the changes permanently in
the database.
Command Description
Page 38 of 208
DML : Data Manipulation Language
DML commands are not auto-committed. It means changes are not permanent to database,
they can be rolled back.
Command Description
These commands are to keep a check on other commands and their affect on the database.
These commands can annul changes made by other commands by rolling back to original
state. It can also make changes permanent.
Command Description
Data control language provides command to grant and take back authority.
Command Description
Naming rules
A table and column name can be up to 30 characters long and must start with alphabet only.
Page 39 of 208
Letters (A-Z,a-z), numbers(0-9) and special characters $,_,#, are allowed. Spaces and hypens
are not allowed.
Data types
When a table is created, the columns must be specified with respective datatypes and the size
of each column.
Varchar2
This type is a character data type to store variable-length alphanumeric data in a column. The
default size is one character. The maximum allowable size is 8000 character. The size is
specified within parenthesis-for example varchar2(20).
Char
The CHAR type is a character data type to store fixed-length alphanumeric data in a column.
Minimum and default is one and maximum is 8000 characters. This is most appropriate when
the columns are to be declared as fixed-length characters.
Number
This is used to store negative,positive, integer, fixed-decimal and floating point numbers. The
size has to defined within parenthesis.
Example - Age number(3) – age can store 3 digit numerical integer value
Salary number(7,2) – salary stores a floating point number which has 7 digits of
which two decimal places and one decimal point. Example 3456.78 ( in this total digits are 7 ,
2 decimal digits, one decimal point, and 4 integer portion)
Date
The date data type is used for storing date and time values. The range of allowable dates is
between January 1,4712 B.C and December 31, 9999 A.D. There is no need to specify the
size for the Date column. Default format is DD-MON-YY.
Page 40 of 208
BINARY
VARYING(n)
TIMESTAMP Stores year, month, day, hour, minute, and second values
Page 41 of 208
bigint -9,223,372,036,854,775,808 9,223,372,036,854,775,807
tinyint 0 255
bit 0 1
Note − Here, datetime has 3.33 milliseconds accuracy where as smalldatetime has 1 minute
accuracy.
Page 42 of 208
char Maximum length of 8,000 characters.( Fixed
length non-Unicode characters)
Page 43 of 208
timestamp Stores a database-wide unique number that gets
updated every time a row gets updated
Operators are used to specify conditions in an SQL statement and to serve as conjunctions
for multiple conditions in a statement.
Arithmetic operators
Comparison operators
Logical operators
Show Examples
Page 44 of 208
Operator Description Example
Show Examples
< Checks if the value of left operand is less than the (a < b) is
value of right operand, if yes then condition true.
becomes true.
Page 45 of 208
condition becomes true.
!< Checks if the value of left operand is not less than (a !< b)
the value of right operand, if yes then condition is false.
becomes true.
Show Examples
Operator Description
BETWEEN The BETWEEN operator is used to search for values that are
within a set of values, given the minimum value and the
maximum value.
Page 46 of 208
NOT The NOT operator reverses the meaning of the logical
operator with which it is used. Eg: NOT EXISTS, NOT
BETWEEN, NOT IN, etc. This is a negate operator.
Types of constraints
Page 47 of 208
1) Integrity constraints: define both the primary key and the foreign key with the table
and primary key it references. Integrity constraints are used to ensure accuracy and
consistency of data in a relational database.
2) Value constraints: define if NULL values are disallowed, if UNIQUE values are
required, and if only certain set of values are allowed in a column.
Naming a constraint:
The general convention used for naming constraints is
<table name><column name><constraint name>
It advisable to create constraints with name.Because if one wants to remove the constraints it
can be done only if the constraints are declared with a name. A user cannot create constraints
in two different tables with the same name.
Constraint Abbreviation
PRIMARY KEY pk
FOREIGN KEY fk
UNIQUE uk
CHECK ck or cc
NOT NULL nn
1) Column level: A column level constraint references a single column and is defined
along with the definition of column.
2) Table level : A table level constraint references one or more columns and is defined
separately from the definitions of the columns.
The PRIMARY KEY constraint uniquely identifies each record in a database table.Primary
keys must contain UNIQUE values.A primary key column cannot contain NULL values.
Most tables should have a primary key, and each table can have only ONE primary key.
Page 48 of 208
At the table level: if the table uses more than one key as its primary key ( i.e composite key)
it can be declared only at the table level.
The following SQL creates a PRIMARY KEY on the "rollno" column when the "student"
table is created:
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:
Note: In the example above there is only ONE PRIMARY KEY (student_rollno_pk).
However, the VALUE of the primary key is made up of TWO COLUMNS (rollno +
LastName).
To create a PRIMARY KEY constraint on the "rollno" column when the table is already
created, use the following SQL:
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:
Page 49 of 208
ADD CONSTRAINT student_rollno_pk PRIMARY KEY (rollno,LastName)
Note: If you use the ALTER TABLE statement to add a primary key, the primary key
column(s) must already have been declared to not contain NULL values (when the table was
first created).
Let's illustrate the foreign key with an example. Look at the following two tables:
1 77895 3
2 44678 3
3 22456 2
4 24562 1
Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the
"Persons" table.
The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.
Page 50 of 208
The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.
The FOREIGN KEY constraint is used to prevent actions that would destroy links between
tables.
The FOREIGN KEY constraint also prevents invalid data from being inserted into the foreign
key column, because it has to be one of the values contained in the table it points to.
The following SQL creates a FOREIGN KEY on the "P_Id" column when the "Orders" table
is created:
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY
constraint on multiple columns, use the following SQL syntax:
To create a FOREIGN KEY constraint on the "P_Id" column when the "Orders" table is
already created, use the following SQL:
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY
constraint on multiple columns, use the following SQL syntax:
Page 51 of 208
ALTER TABLE Orders
ADD CONSTRAINT fk_PerOrders
FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
To DROP a FOREIGN KEY Constraint
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a single column it allows only certain values for this
column.
If you define a CHECK constraint on a table it can limit the values in certain columns based
on values in other columns in the row.
The following SQL creates a CHECK constraint on the "P_Id" column when the "Persons"
table is created. The CHECK constraint specifies that the column "P_Id" must only include
integers greater than 0.
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns, use the following SQL syntax:
Page 52 of 208
Address varchar(255),
City varchar(255),
CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes')
)
To create a CHECK constraint on the "P_Id" column when the table is already created, use
the following SQL:
To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple
columns, use the following SQL syntax:
When we try to enter for age below 11 the following error comes as follows:
1 row created.
Page 53 of 208
ALTER TABLE Persons
DROP CONSTRAINT chk_Person
SQL NOT NULL Constraint
The NOT NULL constraint enforces a column to NOT accept NULL values.
The NOT NULL constraint enforces a field to always contain a value. This means that you
cannot insert a new record, or update a record without adding a value to this field.
The following SQL enforces the "rollno" column and the "Name" column to not accept
NULL values:
Example
CREATE TABLE student
(
rollno int NOT NULL,
Name varchar(255) NOT NULL,
Address varchar(255),
City varchar(255)
)
SQL UNIQUE Constraint
The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a
column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it. There
can be many UNIQUE constraints per table, but only one PRIMARY KEY constraint per
table.
The following SQL creates a UNIQUE constraint on the "P_Id" column when the "Persons"
table is created:
Page 54 of 208
SQL UNIQUE Constraint on ALTER TABLE
To create a UNIQUE constraint on the "P_Id" column when the table is already created, use
the following SQL:
The default value will be added to all new records, if no other value is specified.
The following SQL creates a DEFAULT constraint on the "City" column when the "Persons"
table is created:
Page 55 of 208
P_Id int,
OrderDate date DEFAULT GETDATE()
)
SQL DEFAULT Constraint on ALTER TABLE
To create a DEFAULT constraint on the "City" column when the table is already created, use
the following SQL:
Table altered.
Now to add insert data we have to add only values for the
columns without default values.
SQL> insert into student1 (sid,name,login,age) values ('106','krish','krish@maths',19);
In the above output data column gpa for sid=106 is not entered in insert command but it is automatically entered.
Page 56 of 208
SQL SELECT Statement:
The SELECT statement is used to select data from a database.
Example
SQL> select ename,street,city,eid from employee_csc;
8 rows selected.
The DISTINCT keyword can be used to return only distinct (different) values.
Example:
CITY
---------------
chennai
mumbai
andhra
bangalore
Example:
SQL> select ename,street,city,eid from employee_csc
where city='chennai';
Page 57 of 208
ENAME STREET CITY EID
---------- --------------- --------------- ----------
anitha 1st street chennai 100
aiswarya 2nd street chennai 101
chandra 2nd street chennai 102
hema 3rd street chennai 103
Example:
SQL> select * from employee_csc where eid=101;
The AND operator displays a record if both the first condition AND the second condition are true.
The OR operator displays a record if either the first condition OR the second condition is true.
Using Or
SQL> select * from employee_csc where city='chennai' or city='bangalore';
6 rows selected.
SQL IN Clause:
The IN operator allows you to specify multiple values in a WHERE clause.
SELECT column1, column2....columnN
FROM table_name
WHERE column_name IN (val-1, val-2,...val-N);
Page 58 of 208
---------- --------------- --------------- ----------
anitha 1st street chennai 100
aiswarya 2nd street chennai 101
chandra 2nd street chennai 102
hema 3rd street chennai 103
lalitha metha street mumbai 104
8 rows selected.
Example: applying order by for more than one column:
SQL> select * from employee_csc order by city,ename;
8 rows selected.
Page 59 of 208
8 rows selected.
SQL> select * from employee_csc where eid between 100 and 103;
SQL> select * from employee_csc where eid not between 100 and 103;
Example: this selects records with city has spelling ‘an’ anywhere in its word.
Page 60 of 208
harini kalam street andhra 106
danush ragav street bangalore 107
Example: this selects records with city does not have spelling ‘an’ anywhere in its word.
SQL> select * from employee_csc where city not like '%an%';
Syntax:
Table altered.
suppose we want to modify the datatype of zip to some other it can be done as follows:
Table altered.
Suppose we have another table named “manager_csc” and want to make eid in this table as
foreign key, it can be done as follows:
Page 61 of 208
Name Null? Type
----------------------------------------- -------- ----------------------------
MNAME VARCHAR2(30)
ENAME VARCHAR2(30)
MID NOT NULL VARCHAR2(3)
EID NUMBER(3)
CID VARCHAR2(4)
SQL> alter table manager_csc
add constraint manager_eid_fk FOREIGN KEY(eid)REFERENCES employee(eid)
Suppose we want to add check constraint to the following table on salary column so that it
should not have negative and 0 value, we can do it by:
Table altered.
Drop column
Table altered.
Dropping a table
A table can be dropped when not needed or found to be fault. When a table is dropped, all
data and the table structure are permanently deleted. The drop operation cannot be reversed.
Syntax
Page 62 of 208
DROP TABLE tablename;
Renaming a Table:
Truncating a table:
Truncating a table removes only data, the structure of table remains intact.
Error codes
You can go to the following website and type your error code in search box to know the
meaning of error.
http://otn.oracle.com/pls/db92/db92.error_search
SQL aggregate functions return a single value, calculated from values in a column.
Page 63 of 208
Useful aggregate functions:
SQL scalar functions return a single value, based on the input value.
SELECT COUNT(column_name)
FROM table_name
WHERE CONDITION;
COUNT(8)
----------
8
Page 64 of 208
SELECT COUNT(DISTINCT column_name) FROM table_name;
Example: to know how many city in the table:
SQL> select count(distinct city) from employee_csc;
COUNT(DISTINCTCITY)
-------------------
4
7 rows selected.
To find the average salary type the following command:
SQL> select avg(salary) from works_csc;
AVG(SALARY)
-----------
37857.1429
Example :select employeeid(eid) whose salary is more than average salary in works_csc table
SQL> select eid from works_csc where salary>(select avg(salary) from works_csc);
EID
----------
100
103
106
AVG(SALARY)
-----------
32500
Example:select employee id whose salary is greater than average salary of a particular company.
Page 65 of 208
SQL> select eid from works_csc where salary>(select avg(salary) from works_csc where cname='cts');
EID
----------
100
101
102
103
106
SQL>select x.eid,x.ename from employee_csc x,works_csc y where salary>(select avg(salary) from works_csc where
cname='cts') and x.eid=y.eid
EID ENAME
---------- ----------
100 anitha
101 aiswarya
102 chandra
103 hema
106 harini
Max function
MAX(SALARY)
-----------
50000
SQL> select x.ename,x.eid,y.salary from employee_csc x, works_csc y where y.salary>=(select max(salary) from
works_csc) and x.eid=y.eid;
GROUPBY CLAUSE
SQL> select city,count(eid) from employee_csc
2 group by city;
CITY COUNT(EID)
------------------------------ ----------
chennai 4
mumbai 1
andhra 1
bangalore 2
calcutta 1
Having clause
SQL> select city,count(eid) from employee_csc
2 group by city
3 having count(eid)>=2;
CITY COUNT(EID)
------------------------------ ----------
chennai 4
bangalore 2
Page 66 of 208
SQL Joins
INNER JOIN: Returns all rows when there is at least one match in BOTH tables
LEFT JOIN: Return all rows from the left table, and the matched rows from the right table
RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table
FULL JOIN: Return all rows when there is a match in ONE of the tables
Employee_csc
ENAME STREET CITY EID
---------- --------------- ---------- ----------
anitha 1st street chennai 100
aiswarya 2nd street chennai 101
chandra 2nd street chennai 102
hema 3rd street chennai 103
lalitha metha street mumbai 104
raman krishnan street bangalore 105
harini kalam street andhra 106
danush ragav street bangalore 107
david kamaraj street calcutta 108
ananthi rajaji street chennai 109
works_csc
SALARY EID CID
---------- ---------- ----
45000 100 c1
35000 101 c2
35000 102 c3
50000 103 c4
30000 104 c2
30000 105 c3
40000 106 c1
30000 108 c3
28000 109 c3
inner join
SQL> select * from employee_csc x inner join works_csc y
2 on x.eid=y.eid
3 order by x.ename;
Page 67 of 208
treet
9 rows selected.
The INNER JOIN keyword selects all rows from both tables as long as there is a match between
the columns. If there are rows in the "employee_csc" table that do not have matches in
"works_csc", these customers will NOT be listed.
Manager_csc data
MNAME MID EID CID
------------------------------ --- ---------- ----
ajith m1 100 c1
hari m2 105 c3
karthik m3 104 c2
janani m4 101 c2
krishnan m5 103 c4
jothi m6 102 c3
dhanush m7 107 c4
Page 68 of 208
EID EMPNAME STREET CITY MID MNAME EID CID
7 rows selected.
11 rows selected.
Page 69 of 208
select* from manager_csc x left join employee_csc y
on x.eid=y.eid
order by x.eid
7 rows selected.
7 rows selected.
Page 70 of 208
MID MNAME EID CID EID EMPNAME STREET CITY
--- ---------- ----- ---- ----- ---------- --------------- ----------
m1 ajith 100 c1 100 anitha 1st street calcutta
m4 janani 101 c2 101 aiswarya 2nd street chennai
m6 jothi 102 c3 102 chandra 2nd street chennai
m5 krishnan 103 c4 103 hema 3rd street chennai
m3 karthik 104 c2 104 lalitha metha street mumbai
m2 hari 105 c3 105 raman krishnan street bangalore
m7 dhanush 107 c4 107 danush ragav street bangalore
108 david kamaraj street calcutta
112 krish 3rd street bangalore
109 ananthi rajaji street chennai
106 harini kalam street andhra
11 rows selected.
The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins.
order by x.eid
11 rows selected.
The FULL OUTER JOIN keyword returns all the rows from the left table (employee_csc), and all the rows from the right table (manager_csc). If
there are rows in "employee_csc" that do not have matches in "manager_csc", or if there are rows in "manager_csc" that do not have matches in
"employee_csc ", those rows will be listed as well.
Page 71 of 208
Set operators
UNION :
The UNION set operator returns all distinct rows selected by either query. That means any duplicate
rows will be removed.
SQL> select * from employee_csc where city='chennai'
union
select * from employee_csc where city='bangalore';
6 rows selected.
another example
select eid, empname from employee where city='chennai' union select eid, mname from manager_csc
SQL> /
EID EMPNAME
---------- ------------------------------
100 ajith
100 anitha
101 aiswarya
101 janani
102 chandra
102 jothi
103 hema
103 krishnan
104 karthik
105 hari
107 dhanush
EID EMPNAME
---------- ------------------------------
109 ananthi
Page 72 of 208
12 rows selected.
INTERSECT
The INTERSECT set operator returns all distinct rows selected by both queries. That means only those
rows common to both queries will be present in the final result set.
select * from employee_csc where eid>=103
intersect
select * from employee_csc where eid<107
Example 2:
1* select eid from employee where eid>=100 intersect select eid from manager_csc where eid<=107
SQL> /
EID
----------
100
101
102
103
104
105
107
7 rows selected.
MINUS
The MINUS set operator returns all distinct rows selected by the first query but not the second.
This is functionally equivalent to the ANSI set operator EXCEPT DISTINCT.
sql>select eid, empname from employee minus select eid, mname from manager_csc
/
EID EMPNAME
----- ----------
100 anitha
101 aiswarya
102 chandra
103 hema
104 lalitha
105 raman
Page 73 of 208
106 harini
107 danush
108 david
109 ananthi
112 krish
11 rows selected.
sql>select eid,mname from manager_csc minus select eid,empname from employee
/
EID MNAME
----- ----------
100 ajith
101 janani
102 jothi
103 krishnan
104 karthik
105 hari
107 dhanush
7 rows selected.
ORDER BY
9 rows selected.
9 rows selected.
Page 74 of 208
Defining User Variables:
To define a user variable NAME and give it the value “MALA” enter the following command
SQL> DEFINE NAME=MALA
NOTE: Any user variable defines through DEFINE is considered to be of CHAR data type.
To see what has been assigned type the following
SQL>DEFINE NAME
SQL*Plus lists the definition as:
DEFINE NAME = “MALA” (CHAR)
To delete the definition use UNDEFINE followed by the variable name
Page 75 of 208
SQL> /
Enter value for eid: 101
Enter value for empname: aiswary
Enter value for street: 2ND STREET
Enter value for city: chennai
old 1: insert into employee values(&eid,'&empname','&street','&city')
new 1: insert into employee values(101,'aiswary','2ND STREET','chennai')
1 row created.
To display the list of all existing tables in data base
It was developed by Oracle Corporation in the early 90’s to enhance the capabilities of SQL.
Architecture of PL/SQL
1. PL/SQL block
2. PL/SQL Engine
3. Database Server
PL/SQL block:
Page 76 of 208
o Trigger
o Type
o Type Body
PL/SQL Engine
PL/SQL engine is the component where the actual processing of the codes takes place.
PL/SQL engine separates PL/SQL units and SQL part in the input (as shown in the image
below).
The separated PL/SQL units will be handled with the PL/SQL engine itself.
The SQL part will be sent to database server where the actual interaction with database takes
place.
It can be installed in both database server and in the application server.
Database Server:
This is the most important component of Pl/SQL unit which stores the data.
The PL/SQL engine uses the SQL from PL/SQL units to interact with the database
server.
It consists of SQL executor which actually parses the input SQL statements and
execute the same.
Page 77 of 208
Basic Difference between SQL and PL/SQL
In this section, we will discuss some differences between SQL and PL/SQL
SQL PL/SQL
Block Structure
PL/SQL blocks have a pre-defined structure in which the code is to be grouped. Below are
different sections of PL/SQL blocks
1. Declaration section
2. Execution section
3. Exception-Handling section
Declaration Section
This is the first section of the PL/SQL blocks. This section is an optional part. This is the
section in which the declaration of variables, cursors, exceptions, subprograms, pragma
instructions and collections that are needed in the block will be declared. Below are few more
characteristics of this part.
This particular section is optional and can be skipped if no declarations are needed.
This should be the first section in a PL/SQL block, if present.
This section starts with the keyword 'DECLARE' for triggers and anonymous block. For other
subprograms this keyword will not be present, instead the part after the subprogram name
definition marks the declaration section.
This section should be always followed by execution section.
Execution Section
Page 78 of 208
Execution part is the main and mandatory part which actually executes the code that is
written inside it. Since the PL/SQL expects the executable statements from this block this
cannot be an empty block, i.e., it should have at least one valid executable code line in it.
Below are few more characteristics of this part.
Exception-Handling Section:
The exception are unavoidable in the program which occurs at run-time and to handle this
Oracle has provided an Exception-handling section in blocks. This section can also contain
PL/SQL statements. This is an optional section of the PL/SQL blocks.
This is the section where the exception raised in the execution block is handled.
This section is the last part of the PL/SQL block.
Control from this section can never return to the execution block.
This section starts with the keyword 'EXCEPTION'.
This section should be always followed by the keyword 'END'.
The Keyword 'END' marks the end of PL/SQL block. Below is the syntax of the PL/SQL
block structure.
Note: A block should be always followed by '/' which sends the information to the compiler
about the end of the block.
Page 79 of 208
Types of PL/SQL block
1. Anonymous blocks
2. Named Blocks
Anonymous blocks:
Anonymous blocks are PL/SQL blocks which do not have any names assigned to them. They
need to be created and used in the same session because they will not be stored in the server
as a database objects.
Since they need not to store in the database, they need no compilation steps. They are written
and executed directly, and compilation and execution happen in a single process.
These blocks don't have any reference name specified for them.
These blocks start with the keyword 'DECLARE' or 'BEGIN'.
Since these blocks are not having any reference name, these cannot be stored for later
purpose. They shall be created and executed in the same session.
They can call the other named blocks, but call to anonymous block is not possible as
it is not having any reference.
It can have nested block in it which can be named or anonymous. It can also be nested
to any blocks.
These blocks can have all three sections of the block, in which execution section is
mandatory, the other two sections are optional.
Named blocks:
Named blocks are having a specific and unique name for them. They are stored as the
database objects in the server. Since they are available as database objects, they can be
referred to or used as long as it is present in the server. The compilation process for named
blocks happens separately while creating them as a database objects.
1. Procedure
2. Function
Page 80 of 208
PL/SQL block structure example
Let’s take a look at the simplest PL/SQL block that does nothing.
1 BEGIN
2 NULL;
3 END;
If you execute the above anonymous block in SQL*Plus you will see that it issues a message
1 PL/SQLproceduresuccessfullycompleted.
First, use the SET SERVEROUTPUT ON command to instruct SQL*Plus to echo database’s
output after executing the PL/SQL block. The SET SERVEROUTPUT ON is SQL*Plus
command, which is not related to PL/SQL.
Second, use the DBMS_OUTPUT.PUT_LINE procedure to output a string on the screen.
The following example displays a message Hello PL/SQL on a screen using SQL*Plus:
1 SETSERVEROUTPUTON
2 BEGIN
3 DBMS_OUTPUT.PUT_LINE('Hello PL/SQL');
4 END;
5 /
PL/SQL variables
Like other programming languages, a variable in PL/SQL must follow the naming rules as
follows:
The variable name must be less than 31 characters. Try to make it as meaningful as possible
within 31 characters.
The variable name must begin with an ASCII letter. It can be either lowercase or uppercase
and is case-insensitive, which means data and DATArefer to the same variable.
Page 81 of 208
Followed by the first character are any number, underscore ( _), and dollar sign ( $)
characters.
PL/SQL variables naming convention : it is better to follow the following naming convention
for variables.
v_ VARCHAR2
n_ NUMBER
t_ TABLE
r_ ROW
d_ DATE
b_ BOOLEAN
For example, if you want to declare a variable that holds the first name of employee with the
VARCHAR2 data type, and salary of NUMBER data type then the variable name should be
v_first_name and n_salary respectively.
The literal values should always be enclosed between single quotes while assigning them to
CHARACTER data type.
This data type stores the string value, and the size of the string is fixed at the time of
declaring the variable.
Oracle will be blank-padded the variable if the variable didn't occupy the entire size that has
been declared for it, hence oracle will allocate the memory for declared size even if the
variable didn't occupy it fully.
The size restriction for this data type is 1-2000 bytes.
CHAR data type is more appropriate to use where ever fixed size of data will be handled. .
Page 82 of 208
Syntax Explanation:
The first declaration statement declares the variable 'grade' of CHAR data type with the
maximum size of 1 byte (default value).
The second declaration statement declares the variable 'manager' of CHAR data type with the
maximum size of 10 and assigned the value 'guru99' which is of 6 bytes. Oracle will allocate
the memory of 10 bytes rather than 6 bytes in this case.
This data type stores the string, but the length of the string is not fixed.
The size restriction for this data type is 1-4000 bytes for table column size and 1-32767 bytes
for variables.
The size is defined for each variable at the time of variable declaration.
But Oracle will allocate memory only after the variable is defined, i.e., Oracle will consider
only the actual length of the string that is stored in a variable for memory allocation rather
than the size that have been given for a variable in the declaration part.
It is always good to use VARCHAR2 instead of CHAR data type to optimize the memory
usage.
Syntax Explanation:
The above declaration statement declares the variable 'manager' of VARCHAR2 data type
with the maximum size of 10 and assigned the value 'guru99' which is of 6 bytes. Oracle will
allocate memory of only 6 bytes in this case.
Syntax Explanation:
The above declaration statement declares the variable 'manager' of VARCHAR data type with
the maximum size of 10 and assigned the value 'guru99' which is of 6 bytes. Oracle will
allocate memory of only 6 bytes in this case. (Similar to VARCHAR2)
Page 83 of 208
NCHAR Data type:
This data type is same as CHAR data type, but the character set will of national character set.
This character set can be defined for the session using NLS_PARAMETERS.
The character set can be either UTF16 or UTF8.
The size restriction is 1-2000 bytes.
Syntax Explanation:
The above declaration statement declares the variable 'native' of NCHAR data type with the
maximum size of 10.
The length of this variable depends upon the (number of length) per byte as defined in the
character set.
This data type is same as VARCHAR2 data type, but the character set will be of national
character set.
This character set can be defined for the session using NLS_PARAMETERS.
The character set can be either UTF16 or UTF8.
The size restriction is 1-4000 bytes.
Syntax Explanation:
The above declaration statement declares the variable 'Native_var' of NVARCHAR2 data
type with the maximum size of 10.
This data type is used to store large text or raw data up to the maximum size of 2GB.
Page 84 of 208
Syntax Explanation:
The above declaration statement declares the variable 'Large_text' of LONG data type and
'Large_raw' of LONG RAW data type.
Note: Using LONG data type is not recommended by Oracle. Instead LOB data type should
be preferred.
This data type stores fixed or floating point numbers up to 38 digits of precision. This data
type is used to work with fields which will contain only number data. The variable can be
declared either with precision and decimal digit details or without these information. Values
need not to enclose within quotes while assigning for this data type.
Syntax Explanation:
In the above, the first declaration declares the variable 'A' is of number data type with total
precision 8 and decimal digits 2.
The second declaration declares the variable 'B' is of number data type with total precision 8
and no decimal digits.
The third declaration is the most generic, declares variable 'C' is of number data type with no
restriction in precision or decimal places. It can take up to a maximum of 38 digits.
This data type stores the logical values. It represents either TRUE or FALSE and mainly used
in conditional statements. Values need not enclose within quotes while assigning for this data
type.
Syntax Explanation:
In the above, variable 'Var1' is declared as BOOLEAN data type. The output of the code will
be either true or false based on the condition set.
This data type stores the values in date format, as date, month, and year. Whenever a variable
is defined with DATE data type along with the date it can hold time information and by
default time information is set to 12:00:00 if not specified. Values need to enclose within
quotes while assigning for this data type.
Page 85 of 208
The standard oracle time format for input and output is 'DD-MON-YY' and it is again set at
NLS_PARAMETERS (NLS_DATE_FORMAT) at the session level.
Syntax Explanation:
In the above, variable 'newyear' is declared as DATE data type and assigned the value of Jan
1st, 2015 date.
The second declaration declares the variable current_date as DATE data type and assigned the
value with current system date.
Both these variable holds the time information.
This data type is mainly used to store and manipulate large blocks of unstructured data's like
images, multimedia files, etc. Oracle prefers LOB instead of the LONG data type as it is
more flexible than LONG data type. The below are the few main advantage of LOB over
LONG data type.
The number of column in a table with LONG data type is limited to 1, whereas a table has no
restriction on number of columns with LOB data type.
The data interface tool accepts LOB data type of the table during data replication, but it omits
LONG column of the table. These LONG columns need to be replicated manually.
The size of LONG column is 2GB, whereas LOB can store up to 128 TB.
Oracle is constantly improvising the LOB data type in each of their releases according to the
modern requirement, whereas LONG data type is constant and not getting much updates.
So, it is always good to use LOB data type instead of LONG data type. Following are the
different LOB data types. They can store up to the size of 128 terabytes.
1. BLOB
2. CLOB and NCLOB
3. BFILE
BLOB:
This data type stores the LOB data in the binary file format up to the maximum size of 128
TB. This doesn't store data based on the character set details, so it can store the unstructured
data such as multimedia objects, images, etc.
Syntax Explanation:
Page 86 of 208
CLOB and NCLOB:
CLOB data type stores the LOB data into the character set, whereas NCLOB stores the data
in the native character set. Since these data types uses character set based storage, these
cannot store the data like multimedia, images, etc. that cannot be put into a character string.
The maximum size of these data types is 128 TB.
Syntax Explanation:
BFILE:
BFILE are the data types that stored the unstructured binary format data outside the
database as an operating-system file.
The size of BFILE is to a limited operating system, and they are read-only files and
can't be modified.
1 DECLARE
2 v_first_namevarchar2(20);
3 v_last_namevarchar2(20);
4 n_employee_idnumber;
5 d_hire_datedate;
6 BEGIN
7 NULL;
8 END;
In PL/SQL program, one of the most common tasks is to select values from columns in a
table into a set of variables. In case the data types of columns of the table changes, you have
to change the PL/SQL program to make the types of the variables compatible with the new
changes.
PL/SQL provides you with a very useful feature called variable anchors. It refers to the use
of the %TYPE keyword to declare a variable with the data type is associated with a column’s
data type of a particular column in a table.
Page 87 of 208
Let’s take a look at the employees table in HR sample database provided by Oracle:
Employees Table
1 DECLARE
2 v_first_name EMPLOYEES.FIRST_NAME%TYPE;
3 v_last_name EMPLOYEES.LAST_NAME%TYPE;
4 n_employee_idEMPLOYEES.EMPLOYEE_ID%TYPE;
5 d_hire_date EMPLOYEES.HIRE_DATE%TYPE;
6 BEGIN
7 NULL;
8 END;
9 /
The v_first_name variable has data type that is the same as the data type of the first_name
column in the emloyees table. In case the data type of the first_name column changes, the type
of the v_first_name variable is automatically inherits the new data type of the column.
In PL/SQL, to assign a value or a variable to a variable, you use the assignment operator ( := )
which is a colon( : ) followed by the equal sign( = ).
1 DECLARE
2 v_first_nameEMPLOYEES.FIRST_NAME%TYPE;
3 v_last_nameEMPLOYEES.LAST_NAME%TYPE;
4 n_employee_idEMPLOYEES.EMPLOYEE_ID%TYPE;
Page 88 of 208
5 d_hire_dateEMPLOYEES.HIRE_DATE%TYPE;
6 BEGIN
7 v_first_name:='Mary';
8 v_last_name:='Jane';
9 d_hire_date:=to_date('19700101','YYYYMMDD');
10 END;
11 /
In the example above, we assigned Mary to v_first_name variable, Jane to v_last_name variable,
and result of the to_date function to d_hire_date variable.
You can use INTO of the SQL SELECT statement to assign a value to a variable. The INTO
clause moves the values from the SELECT query’s column list into corresponding PL/SQL
variables.
1 SETSERVEROUTPUTONSIZE1000000;
2 DECLARE
3 v_first_nameEMPLOYEES.FIRST_NAME%TYPE;
4 v_last_nameEMPLOYEES.LAST_NAME%TYPE;
5 n_employee_idEMPLOYEES.EMPLOYEE_ID%TYPE;
6 d_hire_dateEMPLOYEES.HIRE_DATE%TYPE;
7 BEGIN
8 SELECTemployee_id, first_name, last_name, hire_date INTOn_employee_id,
9 v_first_name, v_last_name, d_hire_date FROMemployees
10 WHEREemployee_id=200;
11 DBMS_OUTPUT.PUT_LINE(v_first_name);
12 DBMS_OUTPUT.PUT_LINE(v_last_name);
13 DBMS_OUTPUT.PUT_LINE(d_hire_date);
14 END;
15 /
16
17
18
19
Page 89 of 208
20
21
22
23
Initializing variables
When you declare a variable, its value is uninitialized and hence is NULL. You can initialize
variable a value in declaration section by using variable assignment.
1 DECLARE
2 n_employee_idEMPLOYEES.EMPLOYEE_ID%TYPE:=200;
3 d_hire_dateEMPLOYEES.HIRE_DATE%TYPE:=to_date('19700101','YYYYMMDD');
4 BEGIN
5 NULL;
6 END;
7 /
In PL/SQL, NULL means an unknown value so it has some special characteristics as follows:
Commenting Codes
Commenting code simply instructs the compiler to ignore that particular code from
executing.
Comment can be used in the program to increase the readability of the program. In PL/SQL
codes can be commented in two ways
Using '--' in the beginning of the line to comment that particular line.
Using '/*…….*/' we can multiple lines. The symbol '/*' marks the starting of the comment
and the symbol '*/' marks the end of the comment. The code between these two symbols will
be treated as comments by the compiler.
Example: In this example, we are going to print 'Hello World' and we are also going to see
how the commented lines behave in the code
Page 90 of 208
Example of initilizing variable
1. DECLARE
2. a integer := 30;
3. b integer := 40;
4. c integer;
5. f real;
6. BEGIN
7. c := a + b;
8. dbms_output.put_line('Value of c: ' || c);
9. f := 100.0/3.0;
10. dbms_output.put_line('Value of f: ' || f);
11. END;
1. Value of c: 70
2. Value of f: 33.333333333333333333
3.
4. PL/SQL procedure successfully completed.
A block can be nested into another block. This can be nested either in the execution part or in
the exception handling part. These block can also be labelled. One outer block can contain
many inner blocks. Each inner block is once again a PL/SQL block, hence all the properties
and characteristics of the inner block will be the same as outer block. The below image gives
the pictorial representation of nested block structure. Parent block is the main block and child
block is the nested block.
Page 91 of 208
Below is the syntax for nested block.
Syntax Explanation:
The above syntax shows the nested block that contains a total of two blocks.
These blocks are labelled as 'outer_block' and 'inner_block'
In nested block, one needs to understand the scope and visibility of each block clearly before
using them. Particularly in the inner block the elements from both outer and the inner block
will be visible, hence proper understanding of this is necessary.
Page 92 of 208
Below points will summarize more regarding the scopes in nested blocks.
The elements declared in the outer block and value that is defined before the inner block
definition is visible inside the inner block.
The elements declared in the inner block is not visible in the outer block. They are visible
only within the inner block.
Outer block and Inner block can have a variable with the same name.
In case of variables with same name, inner block by default will refer to the variable declared
in inner block only.
If inner block wants to refer the outer block variable that is having the same name as that of
the inner block, then outer block should be LABELLED and the outer block variable can be
referred as '<outer_block_label>.<variable_name>'
The below example will help to understand more about these scopes.
Example 1: In this example, we are going to see the scope of variables in the inner and outer
block. Also, we are going to see how to refer the variables using block label.
Code Explanation:
Page 93 of 208
Code line 11: Printing the value of outer block variable 'var1'. Since the inner block is having
the variable with the same name, we need to refer with outer block label. Thus printing the
message 'outer block'.
Code line 12: Printing the value of outer block variable 'var2'. Since there is no variable with
this name present in the inner block, by default it will take the value from an outer block,
hence printing 'value before inner block' message.
The variable 'var2' in the outer block has been assigned with the value 'value after inner
block'. But this assignment has happened after the definition of an inner block, hence this
value is not present in the inner block.
Example 2: In this example, we are going to find the difference between two numbers, one
declared at the outer block and another at inner block. Both will have the same name. Let's
see how block label is useful in referring these variables.
Code Explanation:
PL/SQL allows nesting of blocks. A program block can contain another inner block. If you
declare a variable within an inner block, it is not accessible to an outer block. There are two
types of variable scope:
Local Variable: Local variables are the inner block variables which are not accessible to outer
blocks.
Global Variable: Global variables are declared in outermost block.
Page 94 of 208
Example of Local and Global variables
Let's take an example to show the usage of Local and Global variables in its simple form:
1. DECLARE
2. -- Global variables
3. num1 number := 95;
4. num2 number := 85;
5. BEGIN
6. dbms_output.put_line('Outer Variable num1: ' || num1);
7. dbms_output.put_line('Outer Variable num2: ' || num2);
8. DECLARE
9. -- Local variables
10. num1 number := 195;
11. num2 number := 185;
12. BEGIN
13. dbms_output.put_line('Inner Variable num1: ' || num1);
14. dbms_output.put_line('Inner Variable num2: ' || num2);
15. END;
16. END;
17. /
PL/SQL constants
A constant is a value used in a PL/SQL block that remains unchanged throughout the
program. It is a user-defined literal value. It can be declared and used instead of actual values.
Suppose, you have to write a program which will increase the salary of the employees upto
30%, you can declare a constant and use it throughout the program. Next time if you want to
increase the salary again you can change the value of constant than the actual value
throughout the program.
Constant_name:it is the name of constant just like variable name. The constant word
is a reserved word and its value does not change.
Page 95 of 208
VALUE: it is a value which is assigned to a constant when it is declared. It can not be
assigned later.
1. DECLARE
2. -- constant declaration
3. pi constant number := 3.141592654;
4. -- other declarations
5. radius number(5,2);
6. dia number(5,2);
7. circumference number(7, 2);
8. area number (10, 2);
9. BEGIN
10. -- processing
11. radius := 9.5;
12. dia := radius * 2;
13. circumference := 2.0 * pi * radius;
14. area := pi * radius * radius;
15. -- output
16. dbms_output.put_line('Radius: ' || radius);
17. dbms_output.put_line('Diameter: ' || dia);
18. dbms_output.put_line('Circumference: ' || circumference);
19. dbms_output.put_line('Area: ' || area);
20. END;
21. /
After the execution of the above code at SQL prompt, it will produce the following result:.
1. Radius: 9.5
2. Diameter: 19
3. Circumference: 59.69
4. Area: 283.53
5.
6. Pl/SQL procedure successfully completed.
PL/SQL If
PL/SQL supports the programming language features like conditional statements and iterative
statements. Its programming constructs are similar to how you use in programming languages
like Java and C++.
1. IF condition
2. THEN
Page 96 of 208
3. Statement: {It is executed when condition is true}
4. END IF;
This syntax is used when you want to execute statements only when condition is TRUE.
1. IF condition
2. THEN
3. {...statements to execute when condition is TRUE...}
4. ELSE
5. {...statements to execute when condition is FALSE...}
6. END IF;
This syntax is used when you want to execute one set of statements when condition is TRUE
or a different set of statements when condition is FALSE.
1. IF condition1
2. THEN
3. {...statements to execute when condition1 is TRUE...}
4. ELSIF condition2
5. THEN
6. {...statements to execute when condition2 is TRUE...}
7. END IF;
This syntax is used when you want to execute one set of statements when condition1 is
TRUE or a different set of statements when condition2 is TRUE.
1. IF condition1
2. THEN
3. {...statements to execute when condition1 is TRUE...}
4. ELSIF condition2
5. THEN
6. {...statements to execute when condition2 is TRUE...}
7. ELSE
8. {...statements to execute when both condition1 and condition2 are FALSE...}
9. END IF;
It is the most advance syntax and used if you want to execute one set of statements when condition1 is
TRUE, a different set of statement when condition2 is TRUE or a different set of statements when
both the condition1 and condition2 are FALSE.
Page 97 of 208
When a condition is found to be TRUE, the IF-THEN-ELSE statement will execute the corresponding
code and not check the conditions any further.
If there no condition is met, the ELSE portion of the IF-THEN-ELSE statement will be executed.
ELSIF and ELSE portions are optional.
Example of PL/SQL If Statement
1. DECLARE
2. a number(3) := 500;
3. BEGIN
4. -- check the boolean condition using if statement
5. IF( a < 20 ) THEN
6. -- if condition is true then print the following
7. dbms_output.put_line('a is less than 20 ' );
8. ELSE
9. dbms_output.put_line('a is not less than 20 ' );
10. END IF;
11. dbms_output.put_line('value of a is : ' || a);
12. END;
After the execution of the above code in SQL prompt, you will get the following result:
The CASE statement works like the IF statement, only using the keyword WHEN. A CASE
statement is evaluated from top to bottom. If it get the condition TRUE, then the
corresponding THEN clause is executed and the execution goes to the END CASE clause.
1. CASE [ expression ]
2. WHEN condition_1 THEN result_1
3. WHEN condition_2 THEN result_2
4. ...
5. WHEN condition_n THEN result_n
6. ELSE result
7. END
Page 98 of 208
1. DECLARE
2. grade char(1) := 'A';
3. BEGIN
4. CASE grade
5. when 'A' then dbms_output.put_line('Excellent');
6. when 'B' then dbms_output.put_line('Very good');
7. when 'C' then dbms_output.put_line('Good');
8. when 'D' then dbms_output.put_line('Average');
9. when 'F' then dbms_output.put_line('Passed with Grace');
10. else dbms_output.put_line('Failed');
11. END CASE;
12. END;
Suppose you have stored the program in a folder you can execute it as follows:
@e:/books/sql_prgs/grade.sql;
After the execution of above code, you will get the following result:
Excellent
PL/SQL procedure successfully completed.
In this example, we are going to do arithmetic calculation between two numbers 55 and 5.
Code Explanation:
Page 99 of 208
Code line 2: Declaring the variable 'a' as 'NUMBER' data type and initializing it with value
'55'.
Code line 3: Declaring the variable 'b' as 'NUMBER' data type and initializing it with value
'5.'
Code line 4: Declaring the variable 'arth_operation' as 'VARCHAR2' data type of size 20 and
initializing it with value 'MULTIPLY'.
Code line 6: Printing the statement "Program started".
Code line 7: CASE checks the value of the expression. In this case, the value of the variable
'arth_operation' is 'MULTIPLY'. This value will be treated as a selector for this CASE
statement now.
Code line 10: The WHEN clause with value 'MULTIPLY' matches with the selector value,
hence controller will select this action_block and will print the message 'Multiplication of the
numbers are: 275'.
Code line13: Marks the end of CASE statement.
Code line14: Printing the statement "Program completed".
Code Output:
Program started.
Program completed.
SEARCHED CASE statement is similar to CASE statement, rather than using the selector to
select the alternative, SEARCHED CASE will directly have the expression defined in the
WHEN clause.
The first WHEN clause that satisfies the condition will be executed, and the controll will skip
the remaining alternatives.
Syntax Explanation:
In the above syntax, each WHEN clause has the separate <expression> and <action_block>.
The WHEN clause for which the expression returns TRUE will be executed.
'ELSE' block is optional which hold the <action_block_default> that needs to be executed
when none of the alternatives satisfies.
The 'END' marks the end of CASE statement and it is a mandatory part of CASE.
In this example, we are going to do arithmetic calculation between two numbers 55 and 5.
Code line 2: Declaring the variable 'a' as 'NUMBER' data type and initializing it with value
'55'.
Code line 3: Declaring the variable 'b' as 'NUMBER' data type and initializing it with value
'5'.
Code line 4: Declaring the variable 'arth_operation' as 'VARCHAR2' data type of size 20 and
initializing it with value 'DIVIDE.'
Code line 6: Printing the statement "Program started".
Code line 7: SEARCHED CASE statement begins.The code from line8 to line 13 is skipped
as their selector value (ADD, SUBTRACT, MULTIPLY) doesn't match with the value of
'arth_operation'.
Code line 14: The WHEN clause expression "arth_operation = 'DIVIDE'" satisfied and the
expression returns TRUE.
Code line 15: Action_block of the WHEN clause will be executed, and message 'Division of
the numbers are: 11' will be printed.
Code line 17: Marks the end of CASE statement.
Code line 18: Printing the statement "Program completed".
Code Output:
Program started.
Program completed.
1. LOOP
2. Sequence of statements;
3. END LOOP;
1. LOOP
2. Sequence of statements;
3. END LOOP;
1. LOOP
2. statements;
3. EXIT;
4. {or EXIT WHEN condition;}
5. END LOOP;
1. DECLARE
2. i NUMBER := 1;
3. BEGIN
4. LOOP
After the execution of the above code, you will get the following result:
1
2
3
4
5
6
7
8
9
10
Note: You must follow these steps while using PL/SQL Exit Loop.
1. DECLARE
2. VAR1 NUMBER;
3. VAR2 NUMBER;
4. BEGIN
5. VAR1:=100;
6. VAR2:=1;
7. LOOP
8. DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
9. IF (VAR2=10) THEN
10. EXIT;
11. END IF;
12. VAR2:=VAR2+1;
13. END LOOP;
14. END;
Output:
100
200
300
400
500
600
700
800
900
1000
1. WHILE <condition>
2. LOOP statements;
3. END LOOP;
1. DECLARE
2. i INTEGER := 1;
3. BEGIN
4. WHILE i <= 10 LOOP
5. DBMS_OUTPUT.PUT_LINE(i);
6. i := i+1;
7. END LOOP;
8. END;
After the execution of the above code, you will get the following result:
1
2
3
4
5
6
7
8
9
10
Note: You must follow these steps while using PL/SQL WHILE Loop.
1. DECLARE
2. VAR1 NUMBER;
3. VAR2 NUMBER;
4. BEGIN
5. VAR1:=200;
6. VAR2:=1;
Output:
200
400
600
800
1000
1200
1400
1600
1800
2000
1. BEGIN
2. FOR k IN 1..10 LOOP
3. -- note that k was not declared
4. DBMS_OUTPUT.PUT_LINE(k);
5. END LOOP;
6. END;
After the execution of the above code, you will get the following result:
1
2
3
4
Note: You must follow these steps while using PL/SQL WHILE Loop.
You don't need to declare the counter variable explicitly because it is declared implicitly in
the declaration section.
The counter variable is incremented by 1 and does not need to be incremented explicitly.
You can use EXIT WHEN statements and EXIT statements in FOR Loops but it is not done
often.
1. DECLARE
2. VAR1 NUMBER;
3. BEGIN
4. VAR1:=10;
5. FOR VAR2 IN 1..10
6. LOOP
7. DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
8. END LOOP;
9. END;
Output:
10
20
30
40
50
60
70
80
90
100
PL/SQL For Loop REVERSE Example 3
Let's see an example of PL/SQL for loop where we are using REVERSE keyword.
1. DECLARE
2. VAR1 NUMBER;
3. BEGIN
4. VAR1:=10;
5. FOR VAR2 IN REVERSE 1..10
6. LOOP
7. DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
8. END LOOP;
9. END;
Output:
The continue statement is not a keyword in Oracle 10g. It is a new feature encorporated in
oracle 11g.
For example: If a continue statement exits a cursor FOR LOOP prematurely then it exits an
inner loop and transfer control to the next iteration of an outer loop, the cursor closes (in this
context, CONTINUE works like GOTO).
Syntax:
1. continue;
1. DECLARE
2. x NUMBER := 0;
3. BEGIN
4. LOOP -- After CONTINUE statement, control resumes here
5. DBMS_OUTPUT.PUT_LINE ('Inside loop: x = ' || TO_CHAR(x));
6. x := x + 1;
7. IF x < 3 THEN
8. CONTINUE;
9. END IF;
10. DBMS_OUTPUT.PUT_LINE
11. ('Inside loop, after CONTINUE: x = ' || TO_CHAR(x));
12. EXIT WHEN x = 5;
13. END LOOP;
14.
15. DBMS_OUTPUT.PUT_LINE (' After loop: x = ' || TO_CHAR(x));
16. END;
17. /
After the execution of above code, you will get the following result:
Inside loop: x = 0
Labelling of Loops
In PL/SQL, the loops can be labeled. The label should be enclosed between "<<" and ">>".
The labeling of loops particularly in nested loop codes will give more readability. The label
can be given in EXIT command to exit from that particular loop. Using label, the control can
be made to directly exit the outer loop of the nested loops from anyplace inside the loops, by
giving the exit command followed by outer loop label.
Syntax Explanation:
In the above syntax, the out loop has one more loop inside it.
The '<<OUTER_LOOP>>' and '<<INNER_LOOP>>' are the labels of these loops.
Example 1: In this example, we are going to print number starting from 1 using Basic loop
statement. Each number will be printed as many times as its value. The upper limit of the
series is fixed at the program declaration part. Let us learn how we can use the label concept
to achieve this. For that, we will execute the following code
Code line 2-3: Declaring the variable 'a' and 'b' as 'NUMBER' data type.
Code line 4: Declaring the variable 'upper_limit' as 'NUMBER' data type with value '4'
Code line 6: Printing the statement "Program started".
Code line 7: The outer loop has been labeled as "outer_loop"
Code line 9: The value of 'a' is incremented by 1.
Code line 11: Inner loop has been labeled as "inner_loop".
Code line 13: EXIT condition that check whether the value 'a' is higher than 'upper_limit'
value. If not then it will go further, else it exits outer loop directly.
Code line 14: Printing the value of 'b'.
Code line 15: Increments the value of 'b' by +1.
Code line 16: EXIT condition that checks whether the value of 'b' is higher than 'a'. If so, then
it will exit the control from the inner loop.
Basic Exit when encounters the keyword Good to use when exit is not based on any
Loop 'EXIT' in the execution part particular condition.
WHILE Exit when the check condition Good to use when the loop count is unknown,
Loop returns false and exit is based on some other condition.
Exit when the counter reaches the Good to use when loop count to be executed is
FOR Loop
limit known.
Here the label declaration which contains the label_name encapsulated within the <<>>
symbol and must be followed by at least one statement to execute.
Syntax:
1. GOTO label_name;
Here the label declaration which contains the label_name encapsulated within the <<>>
symbol and must be followed by at least one statement to execute.
1. GOTO label_name;
2. ..
3. ..
4. <<label_name>>
5. Statement;
1. DECLARE
2. a number(2) := 30;
3. BEGIN
4. <<loopstart>>
5. -- while loop execution
6. WHILE a < 50 LOOP
7. dbms_output.put_line ('value of a: ' || a);
8. a := a + 1;
9. IF a = 35 THEN
10. a := a + 1;
11. GOTO loopstart;
12. END IF;
13. END LOOP;
14. END;
15. /
value of a: 30
value of a: 31
value of a: 32
value of a: 33
value of a: 34
value of a: 36
value of a: 37
value of a: 38
value of a: 39
value of a: 40
value of a: 41
value of a: 42
value of a: 43
value of a: 44
value of a: 45
value of a: 46
value of a: 47
value of a: 48
value of a: 49
Statement processed.
Restriction on GOTO statement
Cannot transfer control into an IF statement, CASE statement, LOOP statement or sub-block.
Cannot transfer control from one IF statement clause to another or from one CASE statement
WHEN clause to another.
Cannot transfer control from an outer block into a sub-block.
Cannot transfer control out of a subprogram.
Cannot transfer control into an exception handler.
PL/SQL Procedure
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one
or more specific tasks. It is just like procedures in other programming languages.
Header: The header contains the name of the procedure and the parameters or variables
passed to the procedure.
Body: The body contains a declaration section, execution section and exception section
similar to a general PL/SQL block.
When you want to create a procedure or function, you have to define parameters .There is
three ways to pass parameters in procedure:
1. IN parameters: The IN parameter can be referenced by the procedure or function. The value
of the parameter cannot be overwritten by the procedure or the function.
Note: Subprogram is nothing but a procedure, and it needs to be created manually as per the
requirement. Once created they will be stored as database objects.
Procedures are standalone blocks of a program that can be stored in the database.
Call to these procedures can be made by referring to their name, to execute the PL/SQL
statements.
It is mainly used to execute a process in PL/SQL.
It can have nested blocks, or it can be defined and nested inside the other blocks or packages.
It contains declaration part (optional), execution part, exception handling part (optional).
The values can be passed into the procedure or fetched from the procedure through
parameters.
These parameters should be included in the calling statement.
Procedure can have a RETURN statement to return the control to the calling block, but it
cannot return any values through the RETURN statement.
Procedures cannot be called directly from SELECT statements, they can be called from
another block or through EXEC keyword.
Syntax Explanation:
CREATE PROCEDURE instructs the compiler to create new procedure. Keyword 'OR
REPLACE' instructs the compile to replace the existing procedure (if any) with the current
one.
Procedure name should be unique.
In this example, we are going to create a procedure that takes the name as input and prints the
welcome message as output. We are going to use EXEC command to call procedure.
Code Explanation:
Code line 1: Creating the procedure with name 'welcome_msg' and with one parameter
'p_name' of 'IN' type.
Code line 4: Printing the welcome message by concatenating the input name.
Procedure is compiled successfully.
Code line 7: Calling the procedure using EXEC command with the parameter 'Guru99'.
Procedure is executed, and the message is printed out as "Welcome Guru99".
Function
Functions are a standalone block that is mainly used for calculation purpose.
Function use RETURN keyword to return the value, and the datatype of this is defined at the
time of creation.
Function should either return a value or raise the exception, i.e. return is mandatory in
functions.
Function with no DML statements can be directly called in SELECT query whereas the
function with DML operation can only be called from other PL/SQL blocks.
It can have nested blocks, or it can be defined and nested inside the other blocks or packages.
It contains declaration part (optional), execution part, exception handling part (optional).
The values can be passed into the function or fetched from the procedure through the
parameters.
These parameters should be included in the calling statement.
Function can also return the value through OUT parameters other than using RETURN.
Syntax Explanation:
CREATE FUNCTION instructs the compiler to create a new function. Keyword 'OR
REPLACE' instructs the compiler to replace the existing function (if any) with the current
one.
Function name should be unique.
RETURN datatype should be mentioned.
Keyword 'IS' will be used, when the procedure is nested into some other blocks. If the
procedure is standalone then 'AS' will be used. Other than this coding standard, both have the
same meaning.
In this program, we are going to create a function that takes the name as input and returns the
welcome message as output. We are going to use anonymous block and select statement to
call the function.
Code line 1: Creating the function with name 'welcome_msg_func' and with one parameter
'p_name' of 'IN' type.
Code line 2: declaring the return type as VARCHAR2
Code line 5: Returning the concatenated value 'Welcome' and the parameter value.
Code line 8: Anonymous block to call the above function.
Code line 9: Declaring the variable with datatype same as the return datatype of the function.
Code line 11: Calling the function and populating the return value to the variable 'lv_msg'.
Code line 12: Printing the variable value. The output you will get here is "Welcome Guru99"
Code line 14: Calling the same function through SELECT statement. The return value is
directed to the standard output directly.
RETURN will simply exit the control RETURN will exit the control from
from subprogram. subprogram and also returns the value
Return datatype will not be specified Return datatype is mandatory at the time of
at the time of creation creation
PL/SQL contains various built-in functions to work with strings and date datatype. Here we
are going to see the commonly used functions and their usage
Conversion Functions
These built-in functions are used to convert one datatype to another datatype.
In this example, we are going to insert record in user table. So you need to create user table
first.
Table creation:
Procedure Code:
Output:
Procedure created.
PL/SQL program to call procedure
1. BEGIN
2. insertuser(101,'Rahul');
3. dbms_output.put_line('record inserted successfully');
4. END;
5. /
Now, see the "USER" table, you will see one record is inserted.
ID Name
101 Rahul
PL/SQL Function
The PL/SQL Function is very similar to PL/SQL Procedure. The main difference between
procedure and a function is, a function must always return a value, and on the other hand a
procedure may or may not return a value. Except this, all the other things of PL/SQL
procedure are true for PL/SQL function too.
Here:
RETURN clause specifies that data type you are going to return from the function.
Function_body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone function.
1. DECLARE
2. n3 number(2);
3. BEGIN
4. n3 := adder(11,22);
5. dbms_output.put_line('Addition is: ' || n3);
6. END;
7. /
Output:
Addition is: 33
Statement processed.
0.05 seconds
Let's take an example to demonstrate Declaring, Defining and Invoking a simple PL/SQL
function which will compute and return the maximum of two values.
1. DECLARE
2. a number;
3. b number;
4. c number;
5. FUNCTION findMax(x IN number, y IN number)
6. RETURN number
7. IS
8. z number;
9. BEGIN
10. IF x > y THEN
11. z:= x;
12. ELSE
13. Z:= y;
14. END IF;
15.
16. RETURN z;
17. END;
18. BEGIN
19. a:= 23;
20. b:= 45;
21.
22. c := findMax(a, b);
23. dbms_output.put_line(' Maximum of (23,45): ' || c);
24. END;
25. /
Output:
Maximum of (23,45): 45
Statement processed.
0.02 seconds
PL/SQL function example using table
Let's take a customer table. This example illustrates creating and calling a standalone
function. This function will return the total number of CUSTOMERS in the customers table.
After the execution of above code, you will get the following result.
Function created.
While creating a function, you have to give a definition of what the function has to do. To use
a function, you will have to call that function to perform the defined task. Once the function
is called, the program control is transferred to the called function.
After the successful completion of the defined task, the call function returns program control
back to the main program.
To call a function you have to pass the required parameters along with function name and if
function returns a value then you can store returned value. Following program calls the
function totalCustomers from an anonymous block:
1. DECLARE
2. c number(2);
3. BEGIN
4. c := totalCustomers();
5. dbms_output.put_line('Total no. of Customers: ' || c);
6. END;
7. /
After the execution of above code in SQL prompt, you will get the following result.
You already know that a program or a subprogram can call another subprogram. When a
subprogram calls itself, it is called recursive call and the process is known as recursion.
Let's take an example to calculate the factorial of a number. This example calculates the
factorial of a given number by calling itself recursively.
After the execution of above code at SQL prompt, it produces the following result.
Factorial 6 is 720
PL/SQL procedure successfully completed.
PL/SQL Drop Function
If you want to remove your created function from the database, you should use the following
syntax.
1 CREATE[ORREPLACE]FUNCTIONfunction_name[(
2 parameter_1[IN][OUT]data_type,
3 parameter_2[IN][OUT]data_type,
4 parameter_N[IN][OUT]data_type]
5 RETURNreturn_data_typeIS
6 --the declaration statements
You specify the function name function_name after the FUNCTION keyword. By convention, the
function name should start with a verb, for example convert_to_number .
A function may have zero or more than one parameter. You specify the parameter names in
the parameter_1, parameter_2, etc. You must specify the data type of each parameter explicitly in
the data_type. Each parameter has one of three modes: IN, OUT and IN OUT.
An IN parameter is a read-only parameter. If the function tries to change the value of the IN
parameters, the compiler will issue an error message. You can pass a constant, literal,
initialized variable, or expression to the function as the IN parameter.
An OUT parameter is a write-only parameter. The OUT parameters are used to return values
back to the calling program. An OUT parameter is initialized to a default value of its type
when the function begins regardless of its original value before being passed to the function.
An IN OUT parameter is read and write parameter. It means the function reads the value from
an IN OUT parameter, change its value and return it back to the calling program.
The function must have at least one RETURN statement in the execution section. The RETURN
clause in the function header specifies the data type of returned value.
1 CREATEORREPLACEFUNCTIONtry_parse(
2 iv_numberINVARCHAR2)
3 RETURNNUMBERIS
4 BEGIN
5 RETURNto_number(iv_number);
6 EXCEPTION
7 WHENothersTHEN
The iv_number is an IN parameter whose data type is VARCHAR2 so that you can pass any string
to the try_parse() function.
Inside the function, we used the built-in PL/SQL function named to_number() to convert a
string into a number. If any exception occurs, the function returns NULL in the exception
section, otherwise, it returns a number.
The PL/SQL function returns a value so you can use it on the right-hand side of an
assignment or in a SELECT statement.
1 SETSERVEROUTPUTONSIZE1000000;
2 DECLARE
3 n_xnumber;
4 n_ynumber;
5 n_znumber;
6 BEGIN
7 n_x:=try_parse('574');
8 n_y:=try_parse('12.21');
9 n_z:=try_parse('abcd');
10
11 DBMS_OUTPUT.PUT_LINE(n_x);
12 DBMS_OUTPUT.PUT_LINE(n_y);
13 DBMS_OUTPUT.PUT_LINE(n_z);
14 END;
15 /
1 SELECTtry_parse('1234')FROMdual;
2
3 SELECTtry_parse('Abc')FROMdual;
The select statement retrieves data from Oracle table and place the data in temporary
variables:
Syntax:
SELECT columnnames..
FROM tablename
WHERE conditions;
The columnnames must contain at least one column and may include arithmetic or string
expressions, group functions etc. The variablenames must contain a list of variables to hold
the values returned by the SELECT clause. The Recordname is a PL/SQL record type.
If no rows are returned, the standard exception (error condition) NO_DATA_FOUND occurs.
If more than one rows are retrieved, the TOO_MANY_ROWS exception occurs.
declare
n_eid employee.eid%type;
v_empname employee.empname%type;
v_street employee.street%type;
v_city employee.city%type;
begin
select eid,empname,street,city
into n_eid,v_empname,v_street,v_city
from employee
where eid=109;
dbms_output.put_line('emp id '||n_eid);
dbms_output.put_line('emp name '||v_empname);
dbms_output.put_line('emp street '||v_street);
dbms_output.put_line('city '||v_city);
end;
/
In the above program the first line is declare statement. In the 2,3,4 and 5th line the temporary
variables are declared and are declared to hold data from table employee.
In the execution part the select statement is used to extract the data of employee id=109 and
place the data in the temporary variables.
In this since the row returned is only a single row no problem arises. But if the select coloum
returns more than one row then error occurs unless it is handled properly.
DML stands for Data Manipulation Language. These statements are mainly used to
perform the manipulation activity. It basically deals with the below operations.
Data Insertion
Data Update
Data Deletion
Data Projection/Fetching
In PL/SQL, we can do the data manipulation only by using the SQL commands.
Data Insertion
In PL/SQL, we can insert the data into any table using the SQL command INSERT INTO.
This command will take the table name, table column and column values as the input and
insert the value in the base table.
The INSERT command can also take the values directly from another table using 'SELECT'
statement rather than giving the values for each column. Through 'SELECT' statement, we
can insert as many rows as the base table contains.
Syntax Explanation:
The above syntax shows the INSERT INTO command. The table name and values are
mandatory field, whereas column names are not mandatory if the insert statements have
values for all the column of the table.
In the following program INSERT command is used within PL/SQL to insert a row
into the table
end;
/
Output:
SQL> @e:/books/sql_prgs/insertplsql.sql
Enter value for n_eid: 110
old 2: n_eid employee.eid%type:=&n_eid;
new 2: n_eid employee.eid%type:=110;
Enter value for v_empname: kailash
old 3: v_empname employee.empname%type:='&v_empname';
new 3: v_empname employee.empname%type:='kailash';
Enter value for v_street: 3rd street
old 4: v_street employee.street%type:='&v_street';
new 4: v_street employee.street%type:='3rd street';
Enter value for v_city: chennai
old 5: v_city employee.city%type:='&v_city';
new 5: v_city employee.city%type:='chennai';
Data Update
Data update simply means an update of the value of any column in the table. This can be
done using 'UPDATE' statement. This statement takes the table name, column name and
value as the input and updates the data.
Syntax Explanation:
UPDATE commend:
declare
n_eid employee.eid%type:=&n_eid;
begin
update employee
set city='calcutta'
where eid=n_eid;
commit;
end;
/
Output:
SQL> @e:/books/sql_prgs/updateplsql.sql
Enter value for n_eid: 100
old 2: n_eid employee.eid%type:=&n_eid;
new 2: n_eid employee.eid%type:=100;
Data Deletion
Data deletion means to delete one full record from the database table. The 'DELETE'
command is used for this purpose.
Syntax Explanation:
declare
n_eid employee.eid%type:=&n_eid;
begin
delete from employee where eid=n_eid;
commit;
end;
/
Output:
SQL> @e:/books/sql_prgs/deleteplsql.sql
Enter value for n_eid: 110
old 2: n_eid employee.eid%type:=&n_eid;
new 2: n_eid employee.eid%type:=110;
Data Projection/Fetching
Data projection/fetching means to retrieve the required data from the database table. This can
be achieved by using the command 'SELECT' with 'INTO' clause. The 'SELECT' command
will fetch the values from the database, and 'INTO' clause will assign these values to the local
variable of the PL/SQL block.
'SELECT' statement should return only one record while using 'INTO' clause as one variable
can hold only one value. If the 'SELECT' statement returns more than one value than
'TOO_MANY_ROWS' exception will be raised.
'SELECT' statement will assign the value to the variable in the 'INTO' clause, so it needs to
get at least one record from the table to populate the value. If it didn't get any record, then the
exception 'NO_DATA_FOUND' is raised.
The number of columns and their datatype in 'SELECT' clause should match with the number
of variables and their datatypes in the 'INTO' clause.
The values are fetched and populated in the same order as mentioned in the statement.
'WHERE' clause is optional that allows to have more restriction on the records that is going to
be fetched.
'SELECT' statement can be used in the 'WHERE' condition of other DML statements to
define the values of the conditions.
Syntax Explanation:
The above syntax shows the SELECT-INTO command. The keyword 'FROM' is mandatory
that identifies the table name from which the data needs to be fetched.
'WHERE' clause is optional. If this clause is not given, then the data from the entire table will
be fetched.
Cursors:
When a SQL statement is executed in PL/SQL , Oracle assigns a private work area for that
statement. The work area is called cursor. This stores the statement and results returned by
the execution of that statement. There are two types of cursors namely implicit and explicit.
Types of cursors
1. Static cursor: the contents of this cursor are known at compile time. The
cursor object of such an SQL statement is always based on one SQL
statement.
2. Dynamic Cursor: a cursor variable that can change its value is used. The
variable can refer to different SQL statements at different times.
Implicit cursor:
Pl/SQL creates an implicit cursor when an SQL is executed from within the
program block. When a program is executed the Oracle opens an implicit
cursor and the pointer is set to the first row in the cursor.
9 rows selected.
After execution of the above program the table is updated as:
Output
SQL> select * from works_csc;
9 rows selected.
Attributes Functions
SQL%ISOPEN It returns TRUE if the cursor is open;
otherwise it returns FALSE
SQL %FOUND It returns TRUE if the last fetch
returned a row, otherwise it returns
FALSE
SQL %NOTFOUND It returns TRUE if the last fetch did
Explicit Cursor
An explicit cursor is declared as a SELECT statement in PL/SQL block. The
actions to be performed for an explicit cursor are:
1. Declare it
2. Open it
3. Fetch row(s) from it
4. Close it
A cursor is declared as a SELECT statement. This must not have INTO clause.
If the rows are to be retrieved from table in a specific order, ORDER BY
clause can be used.
Syntax is:
Syntax Explanation:
In the above syntax, the declaration part contains the declaration of the cursor and the cursor
variable in which the fetched data will be assigned.
The cursor is created for the 'SELECT' statement that is given in the cursor declaration.
In execution part, the declared cursor is opened, fetched and closed.
In the following example all the rows from employee table is extracted and put
it in the work area or cursor called employee_cur
Declare
Opening a cursor:
When a cursor is opened, its select query is executed. In order to extract from
work area(cursor) it must be opened. The cursor points to the first row in the
active set.
Syntax
OPEN cursorname;
OPEN employee_cur;
The data stored in cursor can be fetched and placed in the local variables to
perform further processing. After reading the first record pointed by cursor
into temporary variables, now the cursor points to the next record in the
workarea
For example,
Or
Emp_rec employee_cur%ROWTYPE;
Closing a cursor:
Syntax
Attributes Functions
%ISOPEN It returns TRUE if the cursor is open;
otherwise it returns FALSE
%FOUND It returns TRUE if the last fetch
returned a row, otherwise it returns
FALSE
%NOTFOUND It returns TRUE if the last fetch did
not return a row; otherwise, it returns
FALSE. It complements the
%FOUND attribute
%ROWCOUNT It returns total number of rows
returned
In this example the data from employee table is extracted and placed in cursor
employee_cur. The cursor is executed by the statement open cursorname. Here
before opening it, the cursor is checked. The condition is checked in If clause
and if it is not open it is opened or the condition moves to the loop.
Here using fetch the data from cursor is moved to the temporary variables
declared and they are displayed using the following statement;
since more than one row is fetched the cursor is checked for end of the cursor
or no row found by the statement employee_cur%found as follows:
so cursor points to next, next rows until it reaches the end of rowset and when
there is no more row to be extracted the loop is exited.
The %rowcount is used to count the rows in cursor. This is done in the
statement:
Declare
n_eid employee.eid%type;
v_empname employee.empname%type;
v_street employee.street%type;
v_city employee.city%type;
cursor employee_cur
begin
if not employee_cur%isopen then
open employee_cur;
end if;
loop
fetch employee_cur
into n_eid,v_empname,v_street,v_city;
exit when not employee_cur%found;
dbms_output.put_line(n_eid||' '||v_empname||' '||v_street||' '||v_city);
end loop;
dbms_output.put_line(employee_cur%rowcount||' employee(s) found');
end;
/
Output:
SQL> @e:/books/sql_prgs/cursor1.sql
100 anitha 1st street calcutta
101 aiswarya 2nd street chennai
102 chandra 2nd street chennai
103 hema 3rd street chennai
104 lalitha metha street mumbai
105 raman krishnan street bangalore
106 harini kalam street andhra
107 danush ragav street bangalore
108 david kamaraj street calcutta
109 ananthi rajaji street chennai
10 employee(s) found
Declare
n_eid employee.eid%type;
v_empname employee.empname%type;
v_street employee.street%type;
v_city employee.city%type;
cursor employee_cur
is
select * from employee
where eid=100;
The output is
SQL> @e:/books/sql_prgs/cursor1.sql
100 anitha 1st street calcutta
1 employee(s) found
Syntax:
Loop statements;
END LOOP;
Where recordname is the name of the record that is declared implicitly in the
loop and is destroyed when the loop ends and cursorname is the name of
declared explicit cursor.
declare
cursor employee_cur
is
select * from employee;
begin
for emp_rec in employee_cur loop
end;
/
Output:
SQL> @e:/books/sql_prgs/cursor2.sql
100 anitha 1st street calcutta
101 aiswarya 2nd street chennai
102 chandra 2nd street chennai
103 hema 3rd street chennai
104 lalitha metha street mumbai
105 raman krishnan street bangalore
106 harini kalam street andhra
107 danush ragav street bangalore
108 david kamaraj street calcutta
109 ananthi rajaji street chennai
In the above program there is no fetch statement. The open cursor statement is
not there. There is no checking of end of row (%FOUND) statement. All these
are done by for loop. This automatically open the cursor and place the records
from cursor into a record type variable and iterate and reaches end of loop
when all the rows in the cursor has been gone through.
In the below program inside the for loop a condition is given where the
records where the column city is having the value ‘chennai’ only is displayed.
declare
cursor employee_cur
is
select * from employee;
begin
for emp_rec in employee_cur loop
if emp_rec.city='chennai' then
dbms_output.put_line(emp_rec.eid||' '||emp_rec.empname||' '||
emp_rec.street||' '||emp_rec.city);
end if;
end loop;
end;
/
Output:
Output:
SQL> @e:/books/sql_prgs/cursor3.sql
100 anitha 1st street calcutta
Suppose all the record are to be extracted the subquery can be given as
follows:
Output:
SQL> @e:/books/sql_prgs/cursor3.sql
100 anitha 1st street calcutta
101 aiswarya 2nd street chennai
102 chandra 2nd street chennai
103 hema 3rd street chennai
104 lalitha metha street mumbai
105 raman krishnan street bangalore
106 harini kalam street andhra
107 danush ragav street bangalore
108 david kamaraj street calcutta
109 ananthi rajaji street chennai
Another example :
Output:
SQL> @e:/books/sql_prgs/cursor3.sql
101 aiswarya 2nd street chennai
102 chandra 2nd street chennai
103 hema 3rd street chennai
109 ananthi rajaji street chennai
Syntax:
CURSOR cursorname
IS
SELECT query;
Where parameter1 etc are formal parameters passed to the cursor and datatype
is any scalar data type assigned to the parameter. The parameters are assigned
only datatype and not size.
end loop;
close emp_cur;
end;
/
Output
SQL> @e:/books/sql_prgs/cursor4.sql;
Enter value for eid: 101
old 2: n_eid employee.eid%type:=&eid;
new 2: n_eid employee.eid%type:=101;
eid empname street city
101 aiswarya 2nd street chennai
Record type is the complex and composite data type which allows the programmer to create a
new data type with the desirable column structure.
Syntax Explanation:
Syntax Explanation:
In the syntax, we are creating the record type named "type_name" only inside the
subprogram.
In both declaration method, the way of defining the column and data type is similar.
In this program, we are going to see how to create "Record type" as a database object. We are
going to create record type 'emp_det' with 4 columns. The columns and their data type are as
follows:
EMP_NO (NUMBER)
EMP_NAME (VARCHAR2 (150))
MANAGER (NUMBER)
SALARY (NUMBER)
Output:
In this example, we are going to see how to create a record type at subprogram level and how
to populate and fetch the values from it by column level.
We are going to create 'emp_det' record_type at subprogram level, and we are going to use
the same to populate and to display data from it.
declare
type emp_detail is record
(
empid number(3),
empname varchar2(30),
street varchar2(40),
city varchar2(30)
);
emp_rec emp_detail;
begin
emp_rec.empid:=112;
emp_rec.empname:='krish';
emp_rec.street:='3rd street';
emp_rec.city:='bangalore';
dbms_output.put_line('employee details');
SQL> @e:/books/sql_prgs/record1.sql
employee details
employee id: 112
employee name: krish
employee street: 3rd street
employee city: bangalore
Code Explanation:
Code line 2-8: Record type 'emp_det' is declared with columns empid, empname, street and
city of data type NUMBER, VARCHAR2, VARCHAR2, VARCHAR2.
Code line 9: emp_rec variable is declared as 'emp_det' data type. Now this variable can hold
the value that contains all the above 4 fields/columns.
Code line 11: Populating the 'emp_id' field of 'emp_rec' with value 112.
Code line 12: Populating the 'empname' field of 'emp_rec' with value krish.
Code line 13: Populating the 'street' field of 'emp_rec' with value 3rd street.
Code line 14: Populating the 'city' field of 'emp_rec' with value bangalore.
Code line 15-19: Displaying the value of the 'emp_rec' in output.
Code Explanation:
Code line 2-8: Record type 'emp_det' is declared with columns empid, empname, street and
city of data type NUMBER, VARCHAR2, VARCHAR2, VARCHAR2.
Code line 9: emp_rec variable is declared as 'emp_detail' data type. Now this variable can
hold the value that contains all the above 4 fields/columns.
Code line 11-14: Populating the table employee with data 112 as empid, krish as empname,
3rd street as street and bangalore as city.
Code line 15: Committing the above insert transaction.
Code line 16: Populating the 'emp_rec' variable as a row level data from the select query for
employee number 102.
Code line 17-21: Displaying the value of the 'emp_rec' in output.
Note: The record type can be accessed only in column level while redirecting its value to any
output mode.
Another example
declare
type emp_detail is record
(
empid employee.eid%type,
empname employee.empname%type,
street employee.street%type,
city employee.city%type
);
emp_rec emp_detail;
begin
select eid,empname,street,city into emp_rec from employee where eid=103;
Output
SQL> @e:/books/sql_prgs/record3.sql
employee details
employee id: 103
employee name: hema
employee street: 3rd street
employee city: chennai
You can assign a PL/SQL record to another PL/SQL record. The pair of PL/SQL
records must have the same number of fields and the data type of each field has to
be convertible.
You can assign a PL/SQL record NULL value by assigning an uninitialized record.
A PL/SQL record can be used as an argument of parameter in a function
You can return a PL/SQL record from a function
To check if the record is NULL, you have to check each individual field of the
record.
To compare two records, you have to compare each individual field of each record.
Here is an example of working with PL/SQL record at record level:
SET serveroutput ON SIZE 1000000;
DECLARE
TYPE t_name IS RECORD(
PL/SQL COLLECTIONS
The collection is nothing but an ordered group of elements of particular data types. It can be a
collection of simple data type or complex data type (like user defined or record types).
In the collection, each element is identified by a term called "subscript." Each item in the
collection is assigned with a unique subscript. The data in that collection can be manipulated
or fetched by referring to that unique subscript.
Collections are most useful things when a large data of the same type needs to be processed
or manipulated. Collections can be populated and manipulated as whole using 'BULK' option
in Oracle.
Collections are classified based on the structure, subscript and storage as shown below.
At any point, data in the collection can be referred by three terms Collection name, Subscript,
Field/Column name as "<collection_name>(<subscript>).<column_name>".
PL/SQL Tables
A PL/SQL table is a single-dimensional structure which stores homogenous data.
Index-By Table
An index-by table (also called an associative array) is a set of key-value pairs. Each key is
unique and is used to locate the corresponding value. The key can be either an integer or a
string.
Index-by-table is a collection in which the array size is not fixed. Unlike the other collection
types, in the index-by-table collection the subscript can be defined by the user. Following are
the attributes of index-by-table.
The subscript can of integer or strings. At the time of creating the collection, the subscript
type should be mentioned.
These collections are not stored sequentially.
They are always sparse in nature.
The array size is not fixed.
They cannot be stored in the database column. They shall be created and used in any program
in that particular session.
They give more flexibility in terms of maintaining subscript.
The subscripts can be of negative subscript sequence also.
They are more appropriate to use for relatively smaller collective values in which the
collection can be initialized and used within the same subprograms.
They need not to be initialized before start using them.
It cannot be created as a database object. It can only be created inside the subprogram, which
can be used only in that subprogram.
BULK COLLECT cannot be used in this collection type as the subscript should be given
explicitly for each record in the collection.
An index-by table is created using the following syntax. Here, we are creating an index-by
table named table_name whose keys will be of subscript_type and associated values will be
of element_type
Syntax
table_name type_name;
example
In the above example a table by name salary is created which stores integer values whose index will
consists of string values.
declare
type salary is table of number index by varchar2(20);
-- printing table
name:=salary_list.first;
while name is not null loop
dbms_output.put_line('salary of '|| name ||' is '||salary_list(name));
name:=salary_list.next(name);
end loop;
end;
/
Output
SQL> @e:/rdbms/plsql/tableeg1.sql
salary of anitha is 3000
salary of aswin is 5000
salary of banu is 10000
salary of guru is 5000
salary of harini is 4000
Example:
Elements of an index-by table could also be a %ROWTYPE of any database table or %TYPE
of any database table field.
declare
cursor emp_cur is
select empname from employee;
type e_list is table of employee.empname%type index by binary_integer;
emp_list e_list;
counter integer:=0;
begin
for temp in emp_cur loop
counter:=counter+1;
emp_list(counter):=temp.empname;
dbms_output.put_line('employee name: '|| emp_list(counter));
end loop;
end;
/
Output:
Nested Tables
A nested table is like a one-dimensional array with an arbitrary number of elements.
However, a nested table differs from an array in the following aspects:
An array has a declared number of elements, but a nested table does not. The size of a
nested table can increase dynamically.
An array is always dense, i.e., it always has consecutive subscripts. A nested array is
dense initially, but it can become sparse when elements are deleted from it.
table_name type_name;
A nested table can be stored in a database column and so it could be used for simplifying
SQL operations where you join a single-column table with a larger table. An associative array
cannot be stored in the database.
Example
declare
type nametable is table of varchar2(20);
type grade is table of integer;
names nametable;
mark grade;
total integer;
begin
names:=nametable('anitha','aswini','kamala','keerthana','malathi');
Output
SQL> @e:/rdbms/plsql/tableeg3.sql;
total:5 students
student: anitha marks: 56
student: aswini marks: 89
student: kamala marks: 78
student: keerthana marks: 70
student: malathi marks: 66
Elements of a nested table could also be a %ROWTYPE of any database table or %TYPE of
any database table field. The following example illustrates the concept. We will use the
EMPLOYEE table stored in our database as:
declare
cursor emp_cur is
select empname from employee;
type emp_table is table of employee.empname%type;
emplist emp_table:=emp_table();
counter integer:=0;
begin
for temp in emp_cur loop
counter:=counter+1;
emplist.extend;
emplist(counter):=temp.empname;
dbms_output.put_line('employee name: '||emplist(counter) );
end loop;
dbms_output.put_line('number of employees are : '||counter );
end;
/
Output
PL/SQL Varrays
This is a composite data type and stands for variable-size array. This is single-dimensional, bounded
collections of elements of same data type.
Varray is a collection method in which the size of the array is fixed. The array size cannot be
exceeded than its fixed value. The subscript of the Varray is of a numeric value. Following
are the attributes of Varrays.
The basic syntax for creating a VRRAY type at the schema level is:
Where,
Maximum size of a varray can be changed using the ALTER TYPE statement.
For example,
Type created.
The basic syntax for creating a VARRAY type within a PL/SQL block is:
For example:
Example:
declare
type namearray is varray(5) of varchar2(20);
type grade is varray(5) of integer;
names namearray;
mark grade;
SQL> @e:/rdbms/plsql/tableeg5.sql;
total:5 students
student: anitha marks: 56
student: aswini marks: 89
student: kamala marks: 78
student: keerthana marks: 70
student: malathi marks: 66
Example 2
Elements of a varray could also be a %ROWTYPE of any database table or %TYPE of any
database table field. The following example illustrates the concept:
declare
cursor emp_cur is
select empname from employee;
type emp_array is varray(15) of employee.empname%type;
emplist emp_array:=emp_array();
counter integer:=0;
begin
for temp in emp_cur loop
counter:=counter+1;
emplist.extend;
emplist(counter):=temp.empname;
dbms_output.put_line('employee name: '||emplist(counter) );
end loop;
end;
/
Output
SQL> @e:/rdbms/plsql/tableeg6.sql;
employee name: anitha
employee name: aiswarya
employee name: chandra
employee name: hema
employee name: lalitha
Constructors are the in-built function provided by the oracle that has the same name as of the
object or collections. They are executed first whenever object or collections are getting
referred for the first time in a session. Below are the important details of constructor in
collection context:
Collection Methods
Oracle provide many functions to manipulate and to work with the collections. These
functions are very much useful in the program to determine and to modify the different
attribute of the collections. Following table will give the different functions and their
description.
PL/SQL facilitates programmers to catch such conditions using exception block in the
program and an appropriate action is taken against the error condition.
System-defined Exceptions
User-defined Exceptions
1. DECLARE
2. <declarations section>
3. BEGIN
4. <executable command(s)>
5. EXCEPTION
6. <exception handling goes here >
7. WHEN exception1 THEN
8. exception1-handling-statements
9. WHEN exception2 THEN
10. exception2-handling-statements
11. WHEN exception3 THEN
12. exception3-handling-statements
13. ........
14. WHEN others THEN
15. exception3-handling-statements
16. END;
Exception-Handling
In real time processes often such exceptions are unavoidable. These errors will stop the
program from executing further, so in order to avoid such condition they need to be captured
and handled separately. This process is called as Exception-Handling, in which the
programmer handles the exception that can possibly occur at the run time.
These exceptions are handled at the block level, i.e. once if any exception occurs in any block
then the control will come out of execution part of that block. The exception will then be
handled at the exception handling part of that block. After handling the exception, it is not
possible to resend control back to the execution section of that block.
The below syntax explains how to catch and handle the exception.
In the above syntax, the exception-handling block contains series of WHEN condition to
handle the exception.
Each WHEN condition is followed by the exception name which is expected to be raised at
the run time.
When any exception is raised at runtime then the PL/SQL engine will look in the exception
handling part for that particular exception. It will start from the first 'WHEN' clause and
sequentially it will search.
If it found the exception handling for the exception which has been raised, then it will execute
that particular handling code part.
If none of the 'WHEN' clause is present for the exception which has been raised, then PL/SQL
engine will execute the 'WHEN OTHERS' part (if present). This is the common for all the
exception.
After executing the exception part control will go out of the current block.
Only one exception part can be executed for a block at run-time. After executing it, the
controller will skip the remaining exception handling part and will go out of the current block.
Note: WHEN OTHERS should always be at the last position of the sequence. The exception
handling part present after WHEN OTHERS will never get executed as the control will exit
from the block after executing the WHEN OTHERS.
Predefined Exceptions
Oracle has predefined some common exception. These exceptions have a unique exception
name and error number. These exceptions are already defined in the 'STANDARD' package
in oracle. In code, we can directly use these predefined exception name to handle them.
Below are the few predefined exceptions
Error
Exception Exception Reason
Code
ORA-
ACCESS_INTO_NULL Assign value to the attributes of uninitialized objects
06530
ORA-
CURSOR_ALREADY_OPEN Trying to open a cursor which is already opened
06511
ORA-
INVALID_CURSOR Illegal cursor operations like closing an unopened cursor
01001
ORA-
ZERO_DIVIDE Dividing a number by '0'
01476
declare
a number(2):=&a;
b number(2):=&b;
c number(4,2);
begin
c:=a/b;
dbms_output.put_line(a||'/'||b||' = '||c);
end;
/
SQL> /
Enter value for a: 5
old 2: a number(2):=&a;
new 2: a number(2):=5;
Enter value for b: 0
old 3: b number(2):=&b;
new 3: b number(2):=0;
declare
*
ERROR at line 1:
ORA-01476: divisor is equal to zero
ORA-06512: at line 6
in the below program under exception section, when a divide by zero error occurs what
should be done is given.
Page 160 of 208
With proper handling of exception
declare
a number(2):=&a;
b number(2):=&b;
c number(4,2);
begin
c:=a/b;
dbms_output.put_line(a||'/'||b||' = '||c);
exception
when zero_divide then
dbms_output.put_line('you entered 0 for divider. enter some valid numerical value');
end;
/
SQL> @e:/books/sql_prgs/divide_exp1.sql;
Enter value for a: 6
old 2: a number(2):=&a;
new 2: a number(2):=6;
Enter value for b: 0
old 3: b number(2):=&b;
new 3: b number(2):=0;
you entered 0 for divider. enter some valid numerical value
Exception
Declare
n_eid employee.eid%type;
v_empname employee.empname%type;
v_street employee.street%type;
v_city employee.city%type;
begin
select eid,empname,street,city
into n_eid,v_empname,v_street,v_city
from employee;
dbms_output.put_line('emp id '||n_eid);
dbms_output.put_line('emp name '||v_empname);
dbms_output.put_line('emp street '||v_street);
dbms_output.put_line('city '||v_city);
end;
In this the select statement where condition is not given. It returns more than one row. So the
following error occurs:
SQL> @e:/books/sql_prgs/selectinto1.sql
declare
*
ERROR at line 1:
ORA-01422: exact fetch returns more than requested number of rows
ORA-06512: at line 7
declare
n_eid employee.eid%type;
v_empname employee.empname%type;
v_street employee.street%type;
v_city employee.city%type;
begin
select eid,empname,street,city
into n_eid,v_empname,v_street,v_city
from employee;
dbms_output.put_line('emp id '||n_eid);
dbms_output.put_line('emp name '||v_empname);
dbms_output.put_line('emp street '||v_street);
dbms_output.put_line('city '||v_city);
exception
when no_data_found then
dbms_output.put_line('no such employee exists');
when too_many_rows then
dbms_output.put_line('more than one row returned');
end;
/
SQL> @e:/books/sql_prgs/selectinto_exception1.sql
more than one row returned
Let's take a simple example to demonstrate the concept of exception handling. Here we are
using the already created CUSTOMERS table.
1. DECLARE
2. c_id customers.id%type := 8;
3. c_name customers.name%type;
4. c_addr customers.address%type;
5. BEGIN
6. SELECT name, address INTO c_name, c_addr
7. FROM customers
8. WHERE id = c_id;
9. DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
10. DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
11. EXCEPTION
12. WHEN no_data_found THEN
13. dbms_output.put_line('No such customer!');
14. WHEN others THEN
15. dbms_output.put_line('Error!');
16. END;
17. /
After the execution of above code at SQL Prompt, it produces the following result:
No such customer!
PL/SQL procedure successfully completed.
The above program should show the name and address of a customer as result whose ID is
given. But there is no customer with ID value 8 in our database, so the program raises the
run-time exception NO_DATA_FOUND, which is captured in EXCEPTION block.
Note: You get the result "No such customer" because the customer_id used in the above example is 8
and there is no cutomer having id value 8 in that table.
If you use the id defined in the above table (i.e. 1 to 6), you will get a certain result. For a
demo example: here, we are using the id 5.
1. DECLARE
2. c_id customers.id%type := 5;
3. c_name customers.name%type;
4. c_addr customers.address%type;
After the execution of above code at SQL prompt, you will get the following result:
Name: alex
Address: paris
PL/SQL procedure successfully completed.
Pragma Exception_Init
You can define your own error message and error number using Pragma EXCEPTION_INIT or
RAISE_APPLICATION_ERROR function. PRAGMA is a compiler directive that associates an exception
name with an internal Oracle error code. The PRAGMA directive is not processed with the execution
of a PL/SQL block, but it directs the PL/SQL compiler to associate a name with the error code.
Often the programs need to handle an Oracle error that has a particular number associated with it, but
no name by which it can be referenced. As a result, it becomes unable to write a handler and trap this
error. In such cases the error numbers can be given a name using pragma.
Naming and associating are two separate statements in the declaration section. An exception name
has to be declared as an exception and the declared name is associated with an internal error code
returned by SQLCODE with the PRAGMA directive. The general syntax is :
Exceptionname Exception;
PRAGMA EXCEPTION_INIT (exceptionname, errornumber);
Where exceptionname is user supplied and errornumber is oracle’s internal error code.
Syntax:
DECLARE
user_define_exception_name EXCEPTION;
PRAGMA EXCEPTION_INIT(user_define_exception_name,-error_number);
BEGIN
statement(s);
IF condition THEN
RAISE user_define_exception_name;
ENDIF;
EXCEPTION
Example
declare
myex exception;
PRAGMA EXCEPTION_INIT(myex,-20015);
n number:=&n;
begin
for i in 1..n loop
dbms_output.put_line(i);
if i=n then
raise myex;
end if;
end loop;
exception
when myex then
dbms_output.put_line('loop finish');
end;
/
Output
SQL> @e:/plsql/pragmaexp1.sql
Enter value for n: 5
old 4: n number:=&n;
new 4: n number:=5;
1
2
3
4
5
loop finish
Example 2:
declare
begin
insert into employee values('','raman','kalam street','chennai');
commit;
dbms_output.put_line('one record is added');
end;
/
When the above code is executed the following error occurs as a null value is
tried to insert which is not allowed.
Output
SQL> @e:/plsql/pragmaexp2.sql;
Now knowing the error code (ORA-01400) this can be used with pragma
exception_init to give a name and write our own error message like below:
declare
e_constraint_violation exception;
PRAGMA EXCEPTION_INIT(e_constraint_violation, -1400);
begin
insert into employee values('','raman','kalam street','chennai');
commit;
dbms_output.put_line('one record is added');
exception
when e_constraint_violation then
dbms_output.put_line('insert statement null values are inserted which is not
allowed');
end;
/
OUTPUT
SQL> @e:/plsql/pragmaexp2.sql;
insert statement null values are inserted which is not allowed
Example 3:
SQL> DELETE FROM EMPLOYEE WHERE EMP_ID='e01';
DELETE FROM EMPLOYEE WHERE EMP_ID='e01'
*
ERROR at line 1:
ORA-02292: integrity constraint (SYSTEM.SYS_C007000) violated - child
record
found
When the above code is executed in the sql prompt we will get to know the
error code as -2292. This can be used inside pl/sql program to assign a
name for it as follows
declare
In the above example another table named company has emp_id column as
foreign key which is referencing the emp_id as primary key in employee table.
When the record in teh employee table which has its child record in company
tries to be deleted, an error is raised. The user can give proper error message to
handle this error.
Output
SQL> @e:/plsql/pragmaexp4.sql;
Enter value for eid: e01
old 6: delete from employee where emp_id='&eid';
new 6: delete from employee where emp_id='e01';
cannot be removed as child is present in another table
Exception-Trapping functions: when an exception occurs in the program the error code and
its associated message may not be known. Two functions are used to identify them. They are:
1. SQLCODE : the SQLCODE function returns a negative error code number. The
number can be assigned to a variable of NUMBER type.
2. SQLERRM: the SQLERRM function returns the error message associated with the
error code. The maximum length of error message is 512 bytes. It can be assigned to
a VARCHAR2 data type.
declare
v_cid company.cid%type;
v_cname company.cname%type:='&cname';
v_city company.city%type;
v_eid company.eid%type;
v_sqlcode number;
v_msg varchar2(255);
begin
select cid,cname,city,eid into v_cid,v_cname,v_city,v_eid from company where cname=v_cname;
dbms_output.put_line(v_cid||' '||v_cname||' '||v_city||' '||v_eid);
exception
when others then
v_sqlcode:=sqlcode;
v_msg:=sqlerrm;
dbms_output.put_line('error code is '||v_sqlcode);
dbms_output.put_line('error message is '||v_msg);
end;
/
output
SQL> @d:/sql/sqlerror.sql
Enter value for cname: tcs
old 3: v_cname company.cname%type:='&cname';
new 3: v_cname company.cname%type:='tcs';
error code is -1422
error message is ORA-01422: exact fetch returns more than requested number of
rows
PL/SQL procedure successfully completed.
declare
invalid_id EXCEPTION;
invalid_commission EXCEPTION;
no_commission EXCEPTION;
v_comm emp_rr.commission%type;
v_ename emp_rr.ename%type;
empid emp_rr.eid%type:=&eid;
begin
if empid<0 then
raise invalid_id;
else
select ename,commission into v_ename,v_comm from emp_rr where eid=empid;
dbms_output.put_line('program over');
EXCEPTION
when invalid_id then
dbms_output.put_line('id must be greater than zero');
when invalid_commission then
dbms_output.put_line('commission negative');
when no_commission then
dbms_output.put_line('no commission value');
when others then
dbms_output.put_line('no such id');
end;
/
Output
SQL> @e:/plsql/userexp1.sql;
Enter value for eid: 100
old 7: select ename,commission into v_ename,v_comm from emp_rr where
eid=&eid;
SQL> /
Enter value for eid: 101
old 7: select ename,commission into v_ename,v_comm from emp_rr where
eid=&eid;
SQL> /
Enter value for eid: 103
old 7: select ename,commission into v_ename,v_comm from emp_rr where
eid=&eid;
RAISE_APPLICATION_ERROR
Syntax
The error_number must fall between -20000 and -20999. This range is reserved by Oracle
for programmer use and is never used for predefined Oracle server errors.
message is the user-specified message for the exception. It is character string up to 2,048
bytes long.
Executable section
Exception section
declare
v_eid emp_rr.eid%type:=&eid;
v_ename emp_rr.ename%type;
v_salary emp_rr.salary%type;
begin
select ename,salary into v_ename,v_salary from emp_rr where eid=v_eid;
dbms_output.put_line('eid is = '||v_eid);
dbms_output.put_line('ename is = '||v_ename);
dbms_output.put_line('salary is = '||v_salary);
exception
when no_data_found then
RAISE_APPLICATION_ERROR(-20201,'this is not a valid employee id');
when too_many_rows then
RAISE_APPLICATION_ERROR(-20202,'too many employees were found');
end;
/
Output
SQL> /
Enter value for eid: 107
old 2: v_eid emp_rr.eid%type:=&eid;
new 2: v_eid emp_rr.eid%type:=107;
declare
*
ERROR at line 1:
ORA-20201: this is not a valid employee id
ORA-06512: at line 12
Syntax Explanation:
All the predefined exceptions are raised implicitly whenever the error occurs. But the user
defined exceptions needs to be raised explicitly. This can be achieved using the keyword
'RAISE'. This can be used in any of the ways mentioned below.
If 'RAISE' is used separately in the program, then it will propagate the already raised
exception to the parent block. Only in exception block can be used as shown below.
Syntax Explanation:
In the above syntax, the keyword RAISE is used in the exception handling block.
Whenever program encounters exception "exception_name", the exception is handled and
will be completed normally
But the keyword 'RAISE' in the exception handling part will propagate this particular
exception to the parent program.
Note: While raising the exception to the parent block the exception that is getting raised
should also be visible at parent block, else oracle will throw an error.
We can use keyword 'RAISE' followed by the exception name to raise that particular user-
defined/predefined exception. This can be used in both execution part and in exception
handling part to raise the exception.
Syntax Explanation:
Code Explanation:
Code line 19: Exception handler for sample_exception in the main block.
Code line 20: Printing the statement "Exception captured in the main block."
In function, an exception should always either return value or raise the exception further, else
Oracle will throw 'Function returned without a value' error at run-time.
Transaction control statements can be given at exception handling block.
SQLERRM and SQLCODE are the in-built functions that will give the exception message
and code.
If an exception is not handled then by default all the active transaction in that session will be
rolled back.
RAISE_APPLICATION_ERROR (-<error_code>, <error_message>) can be used instead of
RAISE to raise the error with user code and message. Error code should be greater than 20000
and prefixed with '-'.
TCL stands for Transaction Control Statements. It will either save the pending transactions or
roll back the pending transaction. These statements play the vital role because unless the
transaction is saved the changes through DML statements will not be saved in the database.
Below are the different TCL statements.
In PL/SQL, all the modifications done on data will be termed as a transaction. A transaction
is considered as complete when the save/discard is applied to it. If no save/discard is given,
then the transaction will not be considered as complete and the modifications done on the
data will not be made permanent in the server.
Irrespective of a number of modifications done during a session, PL/SQL will treat the whole
modification as a single transaction and saving/discard this transaction affects to the entire
pending changes in that session. Autonomous Transaction provides a functionality to the
developer in which it allows to do changes in a separate transaction and to save/discard that
particular transaction without affecting the main session transaction.
Syntax Explanation:
In the above syntax, the block has been made as an autonomous transaction.
Example 1: In this example, we are going to understand how the autonomous transaction is
working.
Package Specification
Package Body
Package Specification
Package specification consists of a declaration of all the public variables, cursors, objects,
procedures, functions, and exception.
The elements which are all declared in the specification can be accessed from outside of the
package. Such element are known as public element.
The package specification is a standalone element that means it can exist alone without
package body.
Whenever a package is referred an instance of the package is created for that particular
session.
After the instance is created for a session, all the package elements that are initiated in that
instance are valid till the end of the session.
Syntax Explanation:
Package Body
It consists of definition of all the elements that are present in the package specification. It can
also have definition of elements that are not declared in the specification, these elements are
called private elements and can be called only from inside the package.
It should contain definitions for all the subprograms/cursors that have been declared in the
specification.
It can also have more subprograms or other elements that are not declared in specification.
These are called private elements.
Syntax Explanation:
Now we are going to see how to refer package elements in the program.
Once the elements are declared and defined in the package, we need to refer the elements in
order to use them.
All the public elements of the package can be referred by calling the package name followed
by the element name separated by period i.e. '<package_name>.<element_name>'.
The public variable of the package can also be used in the same way to assign and fetch
values from them i.e. '<package_name>.<variable_name>'.
Now create the package body of the above package where the code of respective functions
and procedure specification is given above.
The package body will have the same name as package definition. In this example the
package has the name calculate2and note the package body also has the same.
end calculate2;
/
now the functions and procedures defined inside package body can be called with the syntax
declare
ans number(3);
Example 2: in this program inside the package called personel , two functions namely
get_empname and get_salary are defined. This is a package specification.
In the package body given below the code for the functions specification given in package
specification are written. In both package specification and package body the same package
name should be given. In this case the name given is personel
declare
n_salary number(7,2);
v_name varchar2(30);
n_emp_id number:=&emp_id;
begin
v_name:=personel.get_empname(n_emp_id);
n_salary:=personel.get_salary(n_emp_id);
if (v_name is not null and n_salary is not null) then
dbms_output.put_line('Employee: '||v_name);
dbms_output.put_line('Salary : '||n_salary);
end if;
end;
/
Step 1: the package specification to be executed first as:
SQL> @d:\sql_prgs\emp_pack_sp1.sql
Package created.
Step 2: the package body to be executed next
SQL> @d:\sql_prgs\emp_pack_body.sql
Package body created.
Step 3: the program in which the package is called to be executed.
SQL> @d:\sql_prgs\emp_pack_call.sql
SQL> /
Enter value for emp_id: 104
old 4: n_emp_id number:=&emp_id;
new 4: n_emp_id number:=104;
Employee: amala
Salary : 25000
Table used
declare
neid emp_rr.eid%type;
vname emp_rr.ename%type;
nsalary emp_rr.salary%type;
ncomm emp_rr.commission%type;
begin
hirefire.hire_employee(&neid,'&vname',&nsalary,&ncomm);
Output
SQL> @e:/plsql/emp_pack_call2.sql;
Enter value for neid: 112
Enter value for vname: janani
Enter value for nsalary: 30000
Enter value for ncomm: 1600
old 7: hirefire.hire_employee(&neid,'&vname',&nsalary,&ncomm);
6 rows selected.
Package Information
Once the package information is created, the package information such as package source,
subprogram details and overload details are available in the oracle data definition tables.
Below table gives the data definition table and the package information that is available in the
table.
PL/SQL Trigger
Trigger is invoked by Oracle engine automatically whenever a specified event occurs.Trigger
is stored into database and invoked repeatedly, when specific condition match.
Triggers are stored programs, which are automatically executed or fired when some event
occurs.
Triggers could be defined on the table, view, schema, or database with which the event is
associated.
Advantages of Triggers
Creating a trigger:
Here,
This trigger checks the value of salary before insert or updates statement and ensures that
salary below 20000 is not inserted. It acts before insertion or updation
Example 2: this example demonstrates use of trigger to keep information on deleted records.
First create a table to hold deleted records as backup by the following command.
Table created.
Now the trigger is created. Whenever a deletion takes place the deleted record is entered into
this back up table along with the time of deletion.
Execution of trigger.
SQL> @e:/books/sql_prgs/works_trig2.sql;
Trigger created.
1 row deleted.
8 rows selected.
Example 3: The following trigger execute BEFORE to convert empname field from lowercase
to uppercase.
1 row created.
12 rows selected.
Table created.
1 row created.
Example 5: out data base should allow to modify one’s dob. In this case the following trigger
helps to achieve this:
When the updation of dob field takes place the above trigger is triggered.
Create trigger:
Let's take a program to create a row level trigger for the CUSTOMERS table that would fire
for INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This
trigger will display the salary difference between the old values and new values:
After the execution of the above code at SQL Prompt, it produces the following result.
Trigger created.
Use the following code to get the old salary, new salary and salary difference after the trigger
created.
1. DECLARE
2. total_rows number(2);
3. BEGIN
4. UPDATE customers
5. SET salary = salary + 5000;
Output:
Note: As many times you executed this code, the old and new both salary is incremented by
5000 and hence the salary difference is always 5000.
After the execution of above code again, you will get the following result.
Following are the two very important point and should be noted carefully.
OLD and NEW references are used for record level triggers these are not avialable for table
level triggers.
If you want to query the table in the same trigger, then you should use the AFTER keyword,
because triggers can query the table or change it again only after the initial changes are
applied and the table is back in a consistent state.
Benefits of Triggers
Trigger Classification
Trigger Creation
The above syntax shows the different optional statements that are present in trigger creation.
BEFORE/ AFTER will specify the event timings.
INSERT/UPDATE/LOGON/CREATE/etc. will specify the event for which the trigger needs
to be fired.
ON clause will specify on which object the above mentioned event is valid. For example, this
will be the table name on which the DML event may occur in the case of DML Trigger.
Command "FOR EACH ROW" will specify the ROW level trigger.
WHEN clause will specify the additional condition in which the trigger needs to fire.
The declaration part, execution part, exception handling part is same as that of the other
PL/SQL blocks. Declaration part and exception handling part are optional.
In a row level trigger, the trigger fires for each related row. And sometimes it is required to
know the value before and after the DML statement.
Oracle has provided two clauses in the RECORD-level trigger to hold these values. We can
use these clauses to refer to the old and new values inside the trigger body.
:NEW – It holds new value of the columns of the base table/view during the trigger execution
:OLD – It holds old value of the columns of the base table/view during the trigger execution
These clause should be used based on the DML event. Below table will specify which clause
is valid for which DML statement (INSERT/UPDATE/DELETE).
INSTEAD OF Trigger
"INSTEAD OF trigger" is the special type of trigger. It is used only in DML triggers. It is
used when any DML event are going to occur on the complex view.
Consider an example in which a view is made from 3 base tables. When any DML event is
issued over this view, that will become invalid because the data is taken from 3 different
tables. So in this INSTEAD OF trigger is used. The INSTEAD OF trigger is used to modify
the base tables directly instead of modifying the view for the given event.
Example 1: In this example, we are going to create a complex view from two base table.
Then we are going to see how the INSTEAD OF trigger is used to issue UPDATE the
location detail statement on this complex view. We are also going to see how the :NEW
and :OLD is useful in triggers.
Output
Table Created
Step 2)Now since we have created the table, we will populate this table with sample values
and Creation of Views for the above tables
Output
Code Explanation
Output
View created
ZZZ HR USA
YYY SALES UK
Code Explanation
Code line 34-38: Update the location of "XXX" to 'FRANCE'. It raised the exception because
the DML statements are not allowed in the complex view.
Output
ORA-06512: at line 2
Step 5) In order to avoid the error encounter during updating view in the previous step, in this
step we are going to use "instead of trigger."
Code line 39: Creation of INSTEAD OF trigger for 'UPDATE' event on the
'guru99_emp_view' view at the ROW level. It contains the update statement to update the
location in the base table 'dept'.
Code line 44: Update statement uses ':NEW' and ': OLD' to find the value of columns before
and after the update.
Output
Trigger Created
Step 6) Update of view after instead-of trigger. Now the error will not come as the "instead
of trigger" will handle the update operation of this complex view. And when the code is
executed the location of employee XXX will be updated to "France" from "Japan."
Code Explanation:
Output:
ZZZ HR USA
YYY SALES UK
Compound Trigger
Compound trigger is a trigger that allows you to specify actions for each of four timing points
in the single trigger body. The 4 different timing point it supports is as below.
It provides the facility to combine the actions for different timing into the same trigger.
Example 1: In this example, we are going to create a trigger to auto-populate the salary
column with the default value 5000.
Code line 2-10: Creation of compound trigger. It is created for timing BEFORE ROW- level
to populate the salary with default value 5000. This will change the salary to default value
'5000' before inserting the record into the table.
Code line 11-14: Insert the record into 'emp' table.
Code line 16: Verifying the inserted record.
Output:
Trigger created
Triggers can be enabled or disabled. To enable or disable the trigger, an ALTER (DDL)
statement needs to be given for the trigger that disable or enable it.
Varrays
Syntax
TYPE TYPE_NAME IS {VARRAY | VARYING ARRAY} (SIZE_LIMIT)
OF ELEMENT_TYPE [NOT NULL]
Example 1: this program stores the string value of digits in varray and display it.
declare
type digit_name is varray(10) of varchar2(10) not null;
dn digit_name;
begin
dn:=digit_name('zero','one','two','three','four','five','six','seven','eight','nine');
for i in 1..10 loop
dbms_output.put_line(i || '->'||dn(i));
end loop;
end;
/
Output
SQL> @e:/books/sql_prgs/varrays_eg1.sql
1->zero
2->one
3->two
4->three
5->four
6->five
7->six
8->seven
declare
type namearray is varray(5) of varchar2(10);
type grades is varray(5) of integer;
names namearray;
marks grades;
total integer;
begin
names:=namearray('anitha','arthi','aparna','bindhu','banu');
marks:=grades(98,90,91,78,89);
total:=names.count;
dbms_output.put_line('Total '|| total ||' students');
for i in 1..total loop
dbms_output.put_line('student: '||names(i) ||' marks : '||marks(i));
end loop;
end;
/
Output:
Example : 3
declare
type auth_var is varray(10) of varchar2(30);
x_auth auth_var:=auth_var();
begin
x_auth.extend;
x_auth(1):='hello';
x_auth.extend;
x_auth(2):='world';
dbms_output.put_line(x_auth(1) || ' & '|| x_auth(2));
end;
/
Output
SQL> @e:/books/sql_prgs/varrays_eg4.sql
In the lines 2 and 3 we define the VARRAY type with a maximum of 10 elements. In line 4 we define the
variable x_auth of auth_var type and it also initializes the array. A VARRAY can not be used until it is
initialized. In line 4 the auth_var() function actually does the initialization.Once the array is initialized you can
extend it and add elements, which is done in lines 6 through 9. We access each element using the VARRAY
variable and the index number. When the PL/SQL block ends (or the array variable goes out of scope), the
memory used by the array is recovered automatically by the PL/SQL engine. Unlike a cursor, you do not close a
collection.
declare
type month_va is varray(13) of varchar2(20);
v_month_va month_va;
n_count number;
begin
v_month_va:=month_va('A','B','C','D','E','F','G');
dbms_output.put_line('length: ' ||v_month_va.count);
v_month_va.extend;
v_month_va(v_month_va.last):='H';
dbms_output.put_line('length: ' ||v_month_va.count);
for i in v_month_va.first..v_month_va.last
loop
dbms_output.put_line('v_month(i): ' ||v_month_va(i));
end loop;
dbms_output.put_line('maximum limit of array is : ' ||v_month_va.limit);
dbms_output.put_line('first subscript in the array is: ' ||v_month_va.first);
dbms_output.put_line('last subscript in the array is: ' ||v_month_va.last);
dbms_output.put_line('value returned by next(3) is: ' ||v_month_va.next(3));
v_month_va.trim(2);
dbms_output.put_line('after trim(2) the number of elements in arrays is: ' ||v_month_va.count);
dbms_output.put_line('the array elements are: ');
end;
/
Output
SQL> @e:/books/sql_prgs/varrays_eg2.sql
length: 7
length: 8
v_month(i): A
v_month(i): B
v_month(i): C
v_month(i): D
v_month(i): E
v_month(i): F
v_month(i): G
v_month(i): H
maximum limit of array is : 13
first subscript in the array is: 1
last subscript in the array is: 8
value returned by next(3) is: 4
after trim(2) the number of elements in arrays is: 6
the array elements are:
v_month(i): A
v_month(i): B
v_month(i): C
v_month(i): D
v_month(i): E
v_month(i): F
declare
type month_va is varray(13) of varchar2(20);
v_month_va month_va;
n_count number;
begin
v_month_va:=month_va('A','B','C','D','E','F','G');
dbms_output.put_line('length: ' ||v_month_va.count);
for i in v_month_va.first..v_month_va.last
loop
dbms_output.put_line('v_month(i): ' ||v_month_va(i));
end loop;
v_month_va.delete;
dbms_output.put_line('the no. of elements in array is: ' ||v_month_va.count);
end;
/
Elements of a varray could also be a %ROWTYPE of any database table or %TYPE of any database
table field. The following example illustrates the concept.
Example :
Output:
SQL> @e:/books/sql_prgs/varrays_eg5.sql
employee name: anitha
employee name: aiswarya
employee name: chandra
employee name: hema
employee name: lalitha
employee name: raman
employee name: harini
employee name: danush
employee name: david
employee name: ananthi
employee name: RAJAN
Tables
A table, like a record is a composite data structure in PL/SQL. It is a single dimensional structure with
a collection of elements that store the same type of value.
A PL/SQL table declaration is done in two steps, like a record declaration:
3. Declare a PL/SQL table type with a TYPE statement. The structure could use any of
the scalare data types.
4. Declare an actual table based on the type declared in the previous step.
Syntax
TYPE tabletypename IS TABLE OF
Datatype | variablename%TYPE | tablename.columnname%TYPE
[NOT NULL] INDEX BY BINARY_INTEGER;
For example
TYPE deptname_table_type IS TABLE OF dept.Deptname%TYPE
INDEX BY BINARY_INTEGER;
TYPE major_table_type IS TABLE OF VARCHAR2(50)
INDEX BY BINARY_INTEGER;
Index-By Table
An index-by table (also called an associative array) is a set of key-value pairs. Each key is unique and is used to
locate the corresponding value. The key can be either an integer or a string.
An index-by table is created using the following syntax. Here, we are creating an index-by table named
table_name, the keys of which will be of the subscript_type and associated values will be of the element_type
table_name type_name;