Oracle Print
Oracle Print
ORACLE INTRODUCTION
Database: A database is a collection of interrelated data and a set of programs to access those data. The
collection of data usually referred to as the database, information relevant to an enterprise. The primary goal of
database is to provide a way to store and retrieve database information that is both convenient and efficient.
In addition, the database system must ensure the safety of the information stored, despite system crashes or attempts
at unauthorized access. If data are to be shared among several users, the system must avoid possible anomalous
results.
The main differences between DBMS and RDBMS are given below:
2) In DBMS, data is generally stored in In RDBMS, the tables have an identifier called
either a hierarchical form or a primary key and the data values are stored in the
navigational form. form of tables.
4) DBMS does not apply any RDBMS defines the integrity constraint for the
security with regards to data purpose of ACID (Atomocity, Consistency, Isolation
manipulation. and Durability) property.
5) DBMS uses file system to store in RDBMS, data values are stored in the form of
data, so there will be no relation tables, so a relationship between these data
between the tables. values will be stored in the form of a table as well.
6) DBMS has to provide some uniform RDBMS system supports a tabular structure of the
methods to access the stored data and a relationship between them to access the
information. stored information.
PNo: 1
TECH IQ Technologies
9) Examples of DBMS are file Example of RDBMS are mysql, postgre, sql
systems, xml etc. server, oracle etc.
PNo: 2
TECH IQ Technologies
customers. The bank officer has now two choices, either obtain the list of al customers and extract the needed
information manually or ask a system programmer to write the necessary application program. Both
alternatives are obviously unsatisfactory. Suppose that such a program is written, and that, several days later,
the same officer needs to trim that list to include only those customers those have an account balance of 10,
000 or more.
The point here is that conventional file-processing environment does not allow needed data to be retrieved in a
convenient and efficient manner.
Data Isolation: Because data are scattered in various files, and files may be in different formats, writing new
application programs to retrieve the appropriate data is difficult.
Integrity problems: The data values stored in the database must satisfy certain types of consistency
constraints. For example, the balance of a bank account may never fall below a prescribed amount.
Atomicity problems: A computer system, like any other mechanical or electrical device, is subject to failure.
In many applications, it is crucial that, if a failure occurs, the data be restored to the consistent state that
existed prior to the failure. Consider a program to transfer 50 from account A to B. If a system failure occurs
during the execution of the program, it is possible that the 50 was removed from account A but was not
credited to account B, resulting in an inconsistent database state. Clearly, it is essential to database
consistency that either both the credit and debit occur, or that neither occur. That is, the funds transfer must
be atomic- it must happen in its entirety or not at all.
Security problems: Not every user of the database system should be able to access all the data. For
example, in a banking system, payroll personnel need to see only that part of the database that has
information about the various bank employees. They do not need access to information about customer
accounts. But, since application programs are added to the system in an ad hoc manner, enforcing such
security constraints is difficult.
Advantages of Database:
No Data redundancy and inconsistency
Reduces Data Isolation
Provides Security to the data
Saves the data permanently
PNo: 3
TECH IQ Technologies
View Level
Logical
Level
Physical
Level
Instance: The collection of information stored in the database at a particular moment is called an instance
of the database.
Schema: The overall logical structure or designed of the database is called as the schema.
PNo: 4
TECH IQ Technologies
Ellipses, which represent attributes
Diamonds, which represent relationships among entity sets
Lines, which link attributes to entity sets and entity sets to relationships.
Customer-Id City
B. Object Oriented Model: It consists of some data or variables and a collection of program code which
operate on the data. These program codes are called as method. Method of one object can invoke
the values of another object.
1.4.2 Record Based data model: It is used to describe data at physical level and logical level. In this
model, there are three different types of models.
A: Relational Model: The relational model uses a collection of tables to represent both data and
the relationships among those data. Each table has multiple columns, and each column has a unique
name.
PNo: 5
TECH IQ Technologies
The only special symbol allowed is underscore (_).
Blanks spaces are not allowed.
No two tables can have he same name.
Oracle reserved words cannot be used as table name.
A table name once given cannot be changed.
We specify a database schema by a set of definitions expressed by a special language called a data-definition
language (DDL).
For instance, the following statement in the SQL language defines the account table:
PNo: 6
TECH IQ Technologies
ORACLE: Oracle is the software through which we can retrieve or get the data from the database.
Data is retrieve from the database by using relationships.
Introduction to Oracle:
PNo: 7
TECH IQ Technologies
-------------------------
ORACLE: Oak Ridge Automatic Computer Logical Engine
Meaning: Prophesy or Prediction
Oracle is the most widely used Relational Database Management System (RDBMS) and was developed by
Oracle Corporation, USA in 1980s.
The Relational concept was evaluated by Dr.E.F.Codd in the year 1969. The Relational model comprises of
three major components:
• Structures, which define objects that contain data and are accessible to the users.
• Operators, which define actions that manipulate data or schema objects.
• Rules, which are the laws that govern how data can be manipulated and by whom.
A relational database is simply defined as a data model that is strictly viewed by its users as tables. A table
is a two dimensional matrix composed of rows and columns.
Oracle History
Oracle has a 3 decade history, outlasting many of its predecessors. This brief summary traces the
evolution of Oracle from its initial inception to its current status as the world moist flexible and
robust database management system.
Founded in August 1977 by Larry Ellison, Bob Miner, Ed Oates and Bruce Scott, Oracle was
initially named after "Project Oracle" a project for one of their clients, the C.I.A, and the company
that developed Oracle was dubbed "Systems Development Labs", or SDL. Although they may not
have realized it at the time, these four men would change the history of database management
forever.
PNo: 8
TECH IQ Technologies
In 1978 SDL was renamed Relational Software Inc (RSI) to market their new database.
The first commercial RDBMS was built using PDP-11 assembler language. Although they created
a commercial version of RDBMS in 1977, it wasn't available for sale until 1979 with the launch of
Oracle version 2. The company decided against starting with version 1 because they were afraid
that the term "version 1" might be viewed negatively in the marketplace. USA Air Force and then
CIA were the first customers to use Oracle 2.
In 1982 there was another change of the company?s name, from RSI to Oracle Systems
Corporation so as to match its popular database name. The current company name comes from a
CIA project that Larry Ellison had previously worked on code named ?Oracle?.
The Oracle version 3 was developed in 1983. This version was assembled using C programming
language and could run in mainframes, minicomputers, and PCs ? or any hardware with a C
compiler. It supported the execution of SQL statements and transactions. This version also included
new options of pre-join data to increase Oracle optimization.
Despite the advances introduced in version 3, demand was so great that Oracle was compelled to
improve the software even further with the release of version 4 in 1984. Oracle version 4 included
support for reading consistency, which made it much faster than any previous version. Oracle
version 4 also brought us the introduction of the export/import utilities and the report writer, which
allows one the ability to create a report based on a query.
With the introduction of version 5 in 1985, Oracle addressed the increasing use of the internet in
business computing. This version was equipped with the capability to connect clients? software
through a network to a database server. The Clustering Technology was introduced in this version
as well and Oracle became the pioneer using this new concept ? which would later be known as
Oracle Real Application Cluster in version 9i. Oracle version 5 added some new security features
such as auditing, which would help determine who and when someone accessed the database.
Oracle version 5.1 was launched in 1986 and allowed for supporting distributed queries. Later that
same year Oracle released SQL*Plus, a tool that offers ad hoc data access and report writing. 1986
also brought the release of SQL*Forms, an application generator and runtime system with facilities
for simple application deployment.
PNo: 9
TECH IQ Technologies
The PL/SQL language came with Oracle version 6 in 1988. This version provided a host of new
features including the support of OLTP high-speed systems, hot backup capability and row level
locking ? which locks only the row or rows being used during a writing operation, rather than
locking an entire table. Prior to the hot backup feature, database administrators were required to
shutdown the database to back it up. Once the hot backup feature was introduced, DBA?s could do
a backup while the database was still online.
Oracle Parallel Server was introduced in Oracle version 6.2 and was used with DEC VAX Cluster.
This new feature provided high availability because more than one node (server) could access the
data in database. With the increased availability this feature also accelerated the performance of the
system that was sharing users? connections between nodes.
1992 was a memorable year for Oracle. The company announced Oracle version 7, which was the
culmination of four years of hard work and two years of customer testing before release to
market. This version of Oracle provided a vast array of new features and capabilities in areas such
as security, administration, development, and performance. Oracle 7 also addressed security
concerns by providing full control of who, when, and what users were doing in the database.
Version 7 also allowed us to monitor every command, the use of privileges and the user?s access to
a particular item. With Oracle 7 users could use stored procedures and had triggers to enforce
business-rules. Roles were created at this version to make the security maintenance easier for users
and privileges. The two-phase commit was added to support distributed transactions.
Oracle7 Release 7.1 introduced some good new capabilities for database administrators, such as
parallel recovery and read-only tablespaces. For the application developments, Oracle inserted the
dynamic SQL, user-defined SQL functions and multiple same-type triggers. The first 64-bit DBMS
was introduced within this version as well as the VLM (Very Large Memory) option. The feature
Oracle Parallel Query could make some complex queries run 5 to 20 times faster.
In 1996 Oracle 7.3 was shipped, offering customers the ability to manage all kinds of data types;
including video, color images, sounds and spatial data. 1996 also brought the release of Oracle's
first biometric authentication for a commercially available database. This technology could
analyze human characteristics, both physical and behavioral, for purposes of authentication.
The Oracle 8 Database was launched in 1997 and was designed to work with Oracle's network
computer (NC). This version supported Java, HTML and OLTP.
PNo: 10
TECH IQ Technologies
Just one year later Oracle released Oracle 8i which was the first database to support Web
technologies such as Java and HTTP. In 2000 Oracle 8i Parallel Server was working with Linux
which eliminated costly downtime.
Oracle Real Application Cluster came with Oracle 9i Database in 2001. This feature provides
software for clustering and high availability in Oracle database environments. Supporting native
XML was also a new feature of Oracle 9i and this was the first relational database to have these
characteristics. Version 9i release 2 enabled Oracle to integrate relational and multidimensional
database. Despite the fact that hard disks were becoming cheaper, data was increasing very quickly
in databases and Oracle 9i came with a special technology named table compression that
reduced the size of tables by 3 to 10 times and increased the performance when accessing those
tables.
Although Oracle 9i had only been in the market for two years, Oracle launched version 10g in
2003. The release of 10g brought us the introduction to Grid Computing technology. Data centers
could now share hardware resources, thus lowering the cost of computing infrastructure. 10g was
also the first Oracle version to support 64-bit on Linux. With Oracle Database 10g and Real
Application Cluster it was now possible to move from very expensive SMP boxes and mainframes
to an infrastructure that relies on low costs such as UNIX or Windows servers, which have high
availability, scalability and performance.
Oracle has long strived to make their software products available through the internet; but this effort was only
enhanced with the creation of the 10g Express Edition. With the introduction of the 10g Express Edition in
2005, Oracle gave small business and startup corporations a viable option to integrate Oracle into the workplace
at no cost.
The latest version of Oracle Database is 11g which was released on July 11th 2007. This version
introduced more features than any other in Oracle history. This version includes:
Oracle Database Replay, a tool that captures SQL statements and lets you replay them all in
another database to test the changes before you actually apply then on a production database;
Transaction Management using Log Miner and Flashback Data Archive to get DML
statements from redo log files;
Virtual Column Partitioning;
Case sensitive passwords;
Online Patching;
Parallel Backups on same file using RMAN and many others.
PNo: 11
TECH IQ Technologies
Oracle is known for growth and change, which is why it is important to continually study its history
and previous lessons learned while embracing new features and functionality. Throughout its
history Oracle has acquired Database and Software Applications companies in order to provide
more complete solutions to its customers and increase the credibility of its products. Today Oracle
has more than 320,000 customers and is present in 145 countries making it one of the elite
companies in its field.
News Summary
As organizations embrace the cloud, they seek technologies that will transform business and improve their
overall operational agility and effectiveness. Oracle Database 12c is a next-generation database designed
to meet these needs, providing a new multitenant architecture on top of a fast, scalable, reliable, and
secure database platform. By plugging into the cloud with Oracle Database 12c, customers can improve
the quality and performance of applications, save time with maximum availability architecture and storage
management and simplify database consolidation by managing hundreds of databases as one.
News Facts
The latest generation of the world’s #1 database, Oracle Database 12c, is available for download from
Oracle Technology Network (OTN).
Oracle Database 12c introduces a new multitenant architecture that simplifies the process of consolidating
databases onto the cloud; enabling customers to manage many databases as one – without changing their
applications.
The foundation of Oracle Public Cloud Services, Oracle Database 12c can greatly benefit customers
deploying private database clouds and Software-as-a-Service (SaaS) vendors looking for the power of
Oracle Database in a secure multitenant model.
Oracle Database 12c, optimized on SPARC and Intel® Xeon® processors, is a major release. It introduces
500 additional features and is the result of 2,500 person-years of development and 1.2 million hours of
testing, plus an extensive beta program with Oracle’s customers and partners.
Oracle Database 12c is also co-engineered with Oracle’s world record setting SPARC T5 servers.
An Oracle Database 12c Webcast featuring SVP Database Server Technologies Andy Mendelsohn and
architect Tom Kyte is scheduled for July 10, 2013 at 9:00 am PT.
PNo: 12
TECH IQ Technologies
To help customers efficiently manage more data, lower storage costs and improve database performance, Oracle Database 12c
introduces new Automatic Data Optimization features.
A Heat Map monitors database read/write activity enabling Database Administrators to easily identify the data that is hot (very
active), warm (read-only) and cold (rarely read) stored in tables and partitions.
Using smart compression and storage tiering, Database Administrators can easily define server managed policies to automatically
compress and tier OLTP, Data Warehouse and Archive data based on the activity and age of data.
Oracle Database 12c includes more security innovations than any other previous Oracle database release; helping customers address
evolving threats and stringent data privacy regulations.
New Redaction capabilities allow organizations to protect sensitive data such as credit card numbers displayed in applications -
without changes to most applications. Sensitive data is redacted at run-time based on pre-defined policies and account session
information.
Oracle Database 12c also includes new Run-Time Privilege Analysis, enabling organizations to identify privileges and roles actually
being used, helping revoke unnecessary privileges and enforce least privilege with confidence that business operations will not be
disrupted.
Oracle Database 12c introduces several high availability features, as well as enhancements to existing technologies that enable
continuous access to enterprise data.
Global Data Services offers load balancing and failover to globally distributed database configurations.
Data Guard Far Sync extends zero-data-loss standby protection to any distance – not limited by latency.
Application Continuity complements Oracle Real Application Clusters and masks application failures from end-users by automatically
replaying failed transactions.
Seamless integration with Oracle Enterprise Manager 12c Cloud Control enables administrators to easily implement and manage new
Oracle Database 12c functionality including the new multitenant architecture and data redaction.
The comprehensive testing features of Oracle Real Application Testing can help customers validate upgrades and consolidation
strategies by concurrently testing and scaling real production workloads.
Oracle Database 12c enhances in-Database MapReduce capabilities for Big Data through SQL Pattern Matching that enable
immediate and scalable discovery of business event sequences such as financial transactions, network logs and clickstream logs.
Data scientists can better analyze enterprise information and Big Data with new in-database predictive algorithms and with further
integration of open-source R with Oracle Database 12c.
Supporting Quotes
“The innovations in Oracle Database 12c were developed with our customers’ cloud requirements very much in mind,” said Andrew
Mendelsohn, senior vice president, Database Server Technologies, Oracle. “The new multitenant architecture makes it easier for
customers to consolidate their databases and securely manage many as one. It also offers customers other capabilities for cloud
computing such as simplified provisioning, cloning and resource prioritization without resorting to major application changes.”
“Oracle's User Group Communities actively participated in the development and testing of Oracle Database 12c,” said Michelle
Malcher, President of the Independent Oracle Users Group (IOUG). “We are delighted to see across the board enhancements, and the
new architecture will make it so much easier for customers to consolidate their databases onto the cloud.”
“A key challenge facing enterprise data center managers today is the cost, complexity, and inflexibility represented by the large
numbers of production databases operating in fixed server configurations, most of which are substantially underutilized,” said Carl
Olofson, Research Vice President for Database Management and Data Integration software research at IDC. “It is in the nature of
most enterprise database server software that those databases cannot be moved about or redeployed easily, and attempting to
combine them through consolidation raises other manageability and complexity challenges for database administrators. Oracle
Database 12c offers an elegant solution to this problem that not only enables deployment flexibility and eases the administration of
multiple databases, but does so in a way that requires neither changes to applications nor a steep learning curve for DBAs. It also
sets up the data center well for any move in the direction of Cloud Computing.”
PNo: 13
TECH IQ Technologies
Oracle uses Structured Query Language (SQL) as its native language. SQL is the standard language for
relational database management systems as defined by the ANSI. It is simple and powerful, non-
procedural language for communicating with Oracle server. The Oracle uses SQL to create and manipulate
all Oracle database objects.
History:
1970 -- Dr. Edgar F. "Ted" Codd of IBM is known as the father of relational databases. He
described a relational model for databases.
1974 -- Structured Query Language appeared.
1978 -- IBM worked to develop Codd's ideas and released a product named System/R.
1986 -- IBM developed the first prototype of relational database and standardized by ANSI.
The first relational database was released by Relational Software and its later becoming
Oracle.
The SQL performs the following variety of tasks:
• Querying data
• Inserting, Updating and Deleting data
• Creating, Modifying and Deleting database objects
• Controlling access to the database
• Provides for data integrity and consistency
Introduction to SQL*Plus:
SQL*Plus is an Oracle product that provides an open window into the Oracle database. It provides
developers and end-users with the ability to interact directly with the database. SQL*Plus is a
commandline interpreter, where users can directly submit SQL and SQL*Plus commands and PL/SQL
blocks.
SQL*Plus enables the user to,
• Manage every aspect of the database
• Enter, Edit, Retrieve and Run SQL statements and PL/SQL blocks
• Create well polished formatted reports
• Display column definitions for any table
• Access and copy data between databases
• Send messages to and accept responses from an end user
• Generate SQL and SQL*Plus code dynamically
PNo: 14
TECH IQ Technologies
The commands in DCL are used to manage the access to the database objects.
Eg: GRANT and REVOKE
5) Data Retrieval Language (DRL):
The command in DRL is used to retrieve the data of the database object like a table, view, synonym etc.,
Eg: SELECT
Datatypes:
All data elements, variables and constants that are stored in the Oracle database are characterized by
their type and length. The characterization is defined as the object's datatype.
Datatype Description
---------------------------------------
1. CHAR(n) Fixed length character data of length n bytes. Maximum size is 255 bytes that
is it can take upto 2000 characters. Default size is 1 byte.
If the data value is shorter in length than the length defined for the column, blank spaces will be added to
the value. If the data value is longer than the length defined for the column, Oracle returns an error code.
Eg: Person_Name CHAR(10);
3. NUMBER(p,s) This datatype is used to store zero, positive and negative fixed and floating
point numbers. p is the precision or total number of digits. The precision range from 1 to s, where s is the
scale, or the number of digits to the right of the decimal point. The scale range from 84 to 127.
4. NUMBER(p) It is a fixed point number with precision p with scale. NUMBER is floating point
number with precision 38.
5. DATE Used to store date and time information. For each data value the following
information is stored:
Century, Year, Month, Day, Hour, Minute and Second. The default format for the date is 'DD-MMM-YY'.
Eg: '19-MAR-97’
We can add and subtract constants as well as dates from dates.
RAW The RAW and LONG RAW datatypes are used for byte oriented data (for example, binary data or
byte strings) to store character strings, floating point data, and binary data such as graphics images and
digitized sound. We cannot perform string manipulation on RAW data.
ROWID This datatype corresponds to the physical address of a row in a nonclustered Oracle table. It
is unique identifier of a row. A ROWID uses a binary representation of the physical address.
PNo: 15
TECH IQ Technologies
ROWID values contain information necessary to locate a row
which data block in the data file which row in the data block (First row is 0) which data file (first file is 1).
If we declare datatype as VARCHAR then it will occupy space for NULL values, In case of
VARCHAR2 datatype it will not occupy any space.
Name Varchar(10) - If you enter value less than 10, it utilize total 10 spaces.
Name Varchar2(10) - If you enter value less than 10 then remaining space is not utilize.
//Second way
Insert Into Student Values(&RNO,'&NAME',&S1,&S2,&S3);
//Retrieving data
SQL>Select Rno,name,s1,s2,s3 from Student;
SQL>Select rno,name,s3 from student;
SQL> SELECT * FROM STUDENT;
PNo: 16
TECH IQ Technologies
RNO NAME S1 S2 S3
---------- ---------- ---------- ---------- ----------
1 RAKESH 65 89 76
2 ALTAF 78 87 65
3 SANDEEP 89 98 76
4 TAHSEEN 65 35 89
-->Now adding two new columns that is (TOTAL and AVERAGE) to the STUDENT table using ALTER
command.
4. ALTER: This command is use to add new columns to an existing table and also use to modify structure of
the table.
SQL> ALTER TABLE STUDENT ADD(TOTAL NUMBER(3),AVG NUMBER(3));
->After ALTER command, the table will look like this
SQL> DESC STUDENT
Name Null? Type
----------------------------------------- -------- ------------
RNO NUMBER(3)
NAME VARCHAR2(10)
S1 NUMBER(2)
S2 NUMBER(2)
S3 NUMBER(2)
TOTAL NUMBER(3)
AVG NUMBER(3)
SQL> SELECT * FROM STUDENT;
RNO NAME S1 S2 S3 TOTAL AVG
---------- ---------- ---------- ---------- ---------- ---------- ----------
1 AKBAR 65 89 76
2 ALTAF 78 87 65
3 SIDDIQUE 89 98 76
4 TAHSEEN 65 35 89
//Updating data
SQL> UPDATE STUDENT SET TOTAL=(S1+S2+S3);
SQL> UPDATE STUDENT SET AVG=(TOTAL)/3;
//Renaming table
SQL> RENAME STUDENT TO STUDENTINFO;
->After RENAME command, the table will look like this
PNo: 17
TECH IQ Technologies
4 TAHSEEN 65 35 89 189 63
//Deleting record
SQL> DELETE FROM STUDENTINFO WHERE RNO=4;
PNo: 18
TECH IQ Technologies
Syntax:
CREATE TABLE tablename (columnname,columnname...) AS SELECT
columnname,columnname...
from tablename.
eg:
//Suppose table'Customer' table is already created
sql>create table customer(cno number,cname varchar2(15),product varchar2
PNo: 19
TECH IQ Technologies
Syntax:
eg:
PNo: 20
TECH IQ Technologies
create table c5(cno number,cname varchar2(15),product_name varchar2(15),how_many
number(5),amount number(5)) ;
3.DELETE OPERATIONS: Here we can remove all rows or a selected set of rows from a
table
Syntax:
DELETE FROM tablename;
Syntax:
DELETE FROM tablename WHERE search condition;
eg:
delete from emp1 where sal>4000;
Syntax:
UPDATE tablename set columname=expression,columname=expression;
eg:
update emp set sal=sal+500;
Syntax:
UPDATE tablename set columname=expression,columname=expression where
columname=expression;
eg:
update emp12 set job='CHAIRMAN' WHERE SAL>10000;
eg:
ALTER TABLE emp12 ADD(comm number,mgr number);
PNo: 21
TECH IQ Technologies
update emp12 set comm=450,mgr=540 where sal<6000;
Syntax:
ALTER TABLE tablename MODIFY (columnname newdata-type(new size));
eg:
ALTER TABLE EMP12 MODIFY(ENAME VARCHAR2(20));
Table Altered
6. RENAMING TABLES
To rename a table syntax is:
Syntax:
RENAME old-tablename TO new-tablename;
eg:
RENAME EMP12 TO EMP13;
Table Renamed
TRUNCATE TABLE:
-----------------------
TRUNCATE command lets you remove all the rows in the table and reclaim the space
for other uses without removing the table definition from the database.
The action of the truncate command cannot be rolled back or committed.
truncate table emp;
Syntax:
DROP TABLE tablename;
eg:
DROP TABLE EMP;
Table dropped
8. To find out how many tables are there in the system or to determine which
tables the user
has access to the syntax is:
PNo: 22
TECH IQ Technologies
eg: SELECT * FROM TAB;
OUTPUT:
SQL> SELECT * FROM TAB;
OUTPUT:
SQL> DESC EMP
Name Null? Type
----------------------------------------- -------- --------------
ENAME VARCHAR2(20)
ENO NUMBER
JOB VARCHAR2(20)
CITY VARCHAR2(12)
DOJ DATE
SAL NUMBER
COMM NUMBER
MGR NUMBER
SQL>RUN AA
SQL>START AA
SQL>@ AA
Default Values: By using ‘default’ keyword we can assign default values to a column when didn’t assign
any to it at run time.
Drop table emp77;
Create table emp77(eno number(5), ename varchar2(15),job varchar2(15),salary number(7)
default 7000);
Insert into emp77(eno,ename,job) values(1,’SAMI’,’MANAGER’);
Insert into emp77(eno,ename,job) values(2,’SURESH’,’DOCTOR’);
PNo: 23
TECH IQ Technologies
1. Arithmetic Operators:
Addition +
Subtraction -
Division /
Multiplication *
Exponentiation **
Enclosed operation ()
For example:
Increase the salary by 10%,mgr by 200 and comm by 125 of all the employees.
EMPNO NUMBER(3)
ENAME VARCHAR2(12)
JOB VARCHAR2(12)
CITY VARCHAR2(12)
HIREDATE DATE
SALARY NUMBER(5)
COMM NUMBER(3)
MGR NUMBER(3)
PNo: 24
TECH IQ Technologies
'15-AUG-2015',4555,374,653);
insert into emp13 values(7,'RAMESH SHARMA','DOCTOR','HYDERABAD',
'23-AUG-2014',6500,400,553);
insert into emp13 values(8,'JUNAID','ENGINEER','BOMBAY',
'10-JAN-2016',8900,220,553);
insert into emp13 values(9,'ZAHEER KHAN','SPORT','NEW DELHI',
'26-JUN-2015',5400,220,553);
insert into emp13 values(10,'KUMBLE','SPORT','BANGLORE',
'13-NOV-2015',8400,420,453);
insert into emp13 Values(&empno,'&ename','&job','&city','&hiredate',
&salary,&comm,&mgr);
PNo: 25
TECH IQ Technologies
//Actual Updation
SQL>UPDATE EMP13 SET SALARY=SALARY+(SALARY*0.2) WHERE SALARY>8000;
select * from emp13;
2. Logical Operators: Logical operators that can beused in SQL sentences are:
AND,OR,NOT,BETWEEN,LIKE, IN and NOT IN.
AND operator:The oracle engine will process all rows in a table and display the
result only when all of the
conditions specified using the 'AND' operator are satisfied.
Update Emp13 Set Job_Status='Not decided' Where Salary<5000 And Comm>300 And
Mgr>250 And Job_Status Is Null;
OR operator:The oracle engine will process all rows in a table and display the
result only when any of the conditions specified using the 'OR' operator are
satisfied.
PNo: 26
TECH IQ Technologies
NOT operator: The oracle engine will process all rows in a table and display the
result only when none of the
conditions specified using the 'NOT' operator are satisfied.
Range Searching:
In order to select data that is within a range of values, the BETWEEN operator is
used. The BETWEEN operator allows the selection of rows that contain values
within a specified lower and upper limit. The rage coded after the word BETWEEN
in inclusive.
eg:
SQL> select empno,ename,city,SALary from emp13 where SALary BETWEEN 4000 AND
7000;
Update Emp13 Set Salary=Salary+500 Where Hiredate Between '01-JAN-2013' And '31-
DEC-2015';
SELECT * FROM EMP13;
SELECT * FROM EMP13 WHERE HIREDATE BETWEEN '01-JAN-2014' AND '31-DEC-2015' AND
SALARY BETWEEN 5000 AND 7000;
eg: 1. Retrieve all information about employee whose name starts with 'SA'.
SELECT * FROM EMP13;
SELECT * FROM EMP13 WHERE ENAME LIKE 'SA%';
select * from emp13 where ename like ('%A');
select * from emp13 where ename like ('_A%');
select * from emp13 where ename like ('%S_');
eg: 2. Retrieve all information about employees where the third character of
names are either 'H' or 'N'.
SELECT * FROM EMP13 WHERE ENAME LIKE '__H%' OR ENAME LIKE '__N%';
PNo: 27
TECH IQ Technologies
2*2
----------
4
SYSDATE
---------
30-SEP-15
ORACLE FUNCTIONS: Oracle functions serve the purpose of manipulating data items
and returning a result. Functions are also capable of accepting user-supplied
variables or constants and operating on them. Such variables or constants are
called as argumens. Any number of arguments(or no arguments at all) can be passed
to a function in the following format:
Func_name(arg1,arg2....n).
Scalar Functions: Functions that act on only one value at a time are called as
Scalar Functions.
Aggregate Functions:
eg:
1. AVG
SQL> SELECT AVG(SALARY) "FINDING AVG" FROM EMP13;
AVERAGE
----------
6567.625
2. MIN
SQL> SELECT MIN(SALARY) "MINIMUM SALARY" FROM EMP13;
MINIMUM SALARY
--------------
4049
PNo: 28
TECH IQ Technologies
3. COUNT
SQL> SELECT COUNT(EMPNO) "No oF Employees" from emp13;
No oF Employees
---------------
8
4. COUNT(*)
5. MAX
SQL> SELECT MAX(SALARY) FROM EMP13;
MAX(SAL)
----------
13433
6. SUM
SQL> SELECT SUM(COMM) FROM EMP13;
SUM(COMM)
----------
3301
Numeric Functions:
1. ABS
SQL> SELECT ABS(-25) FROM DUAL;
ABS(-25)
----------
25
SQL>select abs(-10+3) from dual;
2. POWER
SQL> SELECT POWER(4,3) "SQUARE" FROM DUAL;
SQUARE
----------
16
3. SQRT
SQL> SELECT SQRT(25) "SQUARE ROOT" FROM DUAL;
SQUARE ROOT
-----------
5
String Functions:
1.LOWER
SQL> SELECT LOWER('NEW DELHI') "lower case" FROM DUAL;
lower cas
---------
new delhi
PNo: 29
TECH IQ Technologies
2. INITCAP
SQL> SELECT INITCAP('ABDUL MAJEED') "Title Case" FROM DUAL;
Title Case
------------
Abdul Majeed
3. UPPER
SQL> SELECT UPPER('junaid touseef') "Upper Case" from dual;
Upper Case
--------------
JUNAID TOUSEEF
4. SUBSTR
SQL> SELECT SUBSTR('NEW DELHI',5,9)"Substring" from dual;
Subst
-----
DELHI
5. LENGTH
SQL> SELECT LENGTH('SECUNDERABAD')"Length" FROM DUAL;
Length
----------
12
6. TRIM : This function removes characters from the beginning or end of character
literals, columns or expressions to yield one potentially shorter character item.
Syntax:
trim([trailing|leading|both]trimstring from s)
example
Select Trim(Leading '#' From '##Sachin') From Dual;
Left
----
ISHA
PNo: 30
TECH IQ Technologies
7. RTRIM
SQL> SELECT RTRIM('WAHEEDA','A') "Right" from dual;
Right
------
WAHEED
UPDATE EMP13 SET ENAME=RTRIM(ENAME,'N') WHERE ENAME IN('RAHMAN','KHAN');
8. LPAD : Attach characters to the existing string from left side.
SQL> SELECT LPAD('Page 1',10,'*') "Lpad" from dual;
Sql>UPDATE EMP SET ENAME=LPAD(ENAME,LENGTH(ENAME)+3,'Dr.') where job='DOCTOR';
Sql>Select * from emp13;
Lpad
----------
****Page 1
9. RPAD
SQL> SELECT RPAD(ENAME,10,'x') "Rpad" FROM EMP13 WHERE ENAME='SALIM';
Rpad
----------
ZAHEERxxxx
10.REPLACE
SQL> select replace('NEW DELHI','delhi') from dual;
NEW DELHI
PNo: 31
TECH IQ Technologies
UPDATE EMP13 SET COMPANY='MICRO SOFT' WHERE EMPNO IN (2,4);
NVL Function
-------------
NVL FUNCTION
The Oracle/PLSQL NVL function lets you substitute a value when a null value is
encountered.
SYNTAX
The syntax for the NVL function in Oracle/PLSQL is:
NVL( string1, replace_with )
Parameters or Arguments
'string1'
The string to test for a null value.
'replace_with'
The value returned if string1 is null.
EXAMPLE
Let's look at some Oracle NVL function examples and explore how to use the NVL
function in Oracle/PLSQL.
For example:
trunc(): This function is use to keep only limited digits after decimal point.
//without trunc() function
select (5000/66) from dual;
Extra Queries
------------------
SQL> select empno,ename,length(ename) from emp13;
SQL> select empno,ename,salary,length(salary) from emp13;
PNo: 32
TECH IQ Technologies
SQL> select empno,ename,lower(ename) from emp13;
SQL> update emp13 set ename=lower(ename) where salary<8000;
SQL> select * from emp13;
SQL> SELECT EMPNO,ENAME,SALARY,SUBSTR(ENAME,2,3) FROM EMP13 WHERE SALARY>8000;
SQL> SELECT * FROM EMP13;
SQL> SELECT EMPNO,ENAME,INITCAP(ENAME),SALARY FROM EMP13;
SQL> UPDATE EMP13 SET ENAME=INITCAP(ENAME) WHERE SALARY<8000;
SQL> SELECT EMPNO,ENAME,SALARY FROM EMP13;
SQL> SELECT * FROM EMP13;
SQL> UPDATE EMP13 SET JOB=LTRIM(JOB,(SUBSTR(JOB,1,2))) WHERE JOB LIKE('M%');
SQL> SELECT * FROM EMP13;
SQL> UPDATE EMP13 SET JOB=REPLACE('MANAGER',JOB) WHERE JOB LIKE('NA%');
SQL> SELECT * FROM EMP13;
SQL> UPDATE EMP13 SET JOB='MANAGER' WHERE job like('MA%');
SQL> UPDATE EMP13 SET ENAME=RTRIM(ENAME,'S') WHERE ENAME LIKE('%S');
SQL> UPDATE EMP13 SET JOB='MANAGER' WHERE job like('MA%');
SQL> SELECT * FROM EMP13;
SQL> UPDATE EMP13 SET ENAME=RTRIM(ENAME,'S') WHERE ENAME LIKE('%S');
SQL>SELECT * FROM EMP13;
SQL> SELECT LPAD('SACHIN',21,'MASTER BLASTER ') FROM DUAL;
SQL> SELECT RPAD('SACHIN',22,' MASTER BLASTER ') FROM DUAL;
SQL> SELECT * FROM EMP13;
SQL> UPDATE EMP13 SET ENAME=LPAD(ENAME,10,'Dr.') where job='DOCTOR';
SQL> SELECT * FROM EMP13;
SQL> UPDATE EMP13 SET ENAME=LPAD(ENAME,9,'Sr.') WHERE JOB='MANAGER';
SQL> SELECT * FROM EMP13;
Conversion Functions:
1. TO_NUMBER
SQL> UPDATE EMP13 SET SALARY=SALARY+TO_NUMBER(SUBSTR('$73452',2,3));
SQL>select * from emp13;
//Adding 10 dollars
update emp13 set
currency=concat('$',to_char(to_number(substr(currency,2,length(currency)-
1)+10)));
PNo: 33
TECH IQ Technologies
Char
---------
$017,145
3. TO_CHAR(date conversion)
1. ADD_MONTHS
eg:
SQL> SELECT ADD_MONTHS(SYSDATE,4) FROM DUAL;
update emp13 set hiredate=add_months(hiredate,5) where hiredate<'01-jan-2015';
ADD_MONTH
---------
PNo: 34
TECH IQ Technologies
31-JAN-16
2. LAST_DAY
SQL> SELECT SYSDATE,LAST_DAY(SYSDATE)"LAST" FROM DUAL;
SYSDATE LAST
--------- ---------
30-SEP-14 30-SEP-14
3. MONTHS_BETWEEN
SQL> SELECT MONTHS_BETWEEN('18-AUG-2015','15-FEB-2014')"MONTHS" FROM DUAL;
MONTHS
----------
6.09677419
select sysdate,hiredate,trunc(months_between(sysdate,hiredate),2) "No.of months
work" from emp13;
4. NEXT_DAY
NEXT DAY
---------
02-OCT-15
Using Pseudocolumns:
---------------------------
Pseudo-columns are used to pass additional information on a row. A
Pseudo-column is not actually part of rows like any other columns, but exist due
to the row property. Pseudo-columns cannot be updated or modified but are used
only for retrieval purpose. A user can refer to Pseudo-columns the same way as is
done to the ordinay columns of a table in 'SELECT' statements.
PNo: 35
TECH IQ Technologies
//so both original and duplicate deleted, but we want to delete only duplicate
PNo: 36
TECH IQ Technologies
ENO ENAME
---------- ------------
1 AHMED
2 BILAL
3 SURESH
1 AHMED
ENO ENAME
---------- ------------
1 AHMED
2 BILAL
3 SURESH
Pseudo-Column ROWNUM
------------------------------
It gives a sequence in which rows are retrieved from the database. In other
words, the pseudo-column rownum is used to add sequence number to the output.
ROWNUM EMPNO
---------- ----------
1 7
2 1
3 2
4 3
5 4
Pseudo-Column ROWSCN
------------------------------
It gives SCN when the row is last modified. SCN is the number generated by
Oracle to record the sequence of transaction. When the transaction is committed,
all the rows which are modified get SCN.
PNo: 37
TECH IQ Technologies
SQL> SELECT ORA_ROWSCN, ENAME FROM emp13;
ORA_ROWSCN ENAME
---------- ----------
2396812 AJAY
2396812 ASHOK
2396812 ANIL
2396812 YOGESH
2396812 VIJAY
Example : Displaying SCN for row which is last modified
SCN_TO_TIMESTAMP(ORA_ROWSCN) ENAME
----------------------------------------------------------- ----------
01-NOV-15 02.45.12.000000000 PM AJAY
01-NOV-15 02.45.12.000000000 PM ASHOK
01-NOV-15 02.45.12.000000000 PM ANIL
01-NOV-15 02.45.12.000000000 PM YOGESH
01-NOV-15 02.45.12.000000000 PM VIJAY
01-NOV-15 02.45.12.000000000 PM SUNIL
Pseudo-Column SYSDATE
------------------------------
It gives the current date and time of the system
SYSDATE ENAME
--------- ----------
01-NOV-15 AJAY
01-NOV-15 ASHOK
01-NOV-15 ANIL
01-NOV-15 YOGESH
01-NOV-15 VIJAY
01-NOV-15 SUNIL
01-NOV-15 AMIT
01-NOV-15 ABHAY
01-NOV-15 CHAIRMAN
Pseudo-Column UID
-------------------------
It gives a number that identifies the user, since Oracle is used in a multiuser
environment. UID is the way to identify a user.
UID
----------
PNo: 38
TECH IQ Technologies
5
Pseudo-Column USER
-------------------------
It is used for retrieving user name.
USER ENAME
------------------------------ ----------
SYSTEM AJAY
SYSTEM ASHOK
SYSTEM ANIL
SYSTEM YOGESH
SYSTEM VIJAY
SYSTEM SUNIL
SYSTEM AMIT
SYSTEM ABHAY
SYSTEM CHAIRMAN
DATA CONSTRAINS: Rules which are enforced on data being entered, and
prevents the user from entering invalid data into tables are called Constraints.
Thus, constraints super control data being entered in tables for permanent
storage.
Both the 'Create Table' and 'Alter Table' SQL verbs can be used to write SQL
sentences that attach constraints
to a table column.
PNo: 39
TECH IQ Technologies
5. Foreign key (child key)
PNo: 40
TECH IQ Technologies
Syntax:
column_name data-type(size) NOT NULL
Example:
Create a table client_master with following mandatory fields:
client_no,name,address1 and address2 columns.
PNo: 41
TECH IQ Technologies
The UNIQUE Constraint:
The purpose of the UNIQUE key is to ensure that information is the column(s) is
unique i.e, a value entered
in column(s) defined in the unique constraint must bot be repeated across the
column(s). A table may have many unique keys.
Syntax:
column-name data-type(size) UNIQUE
Examp:
Create a table client_master such that the contents of the column client_no are
unique across the entire column.
DEFAULT Constraint: Provides a default value for a column when none is specified.
Example:
For example, the following SQL creates a new table called CUSTOMERS and adds five columns.
Here, SALARY column is set to 5000.00 by default, so in case INSERT INTO statement does
not provide a value for this column, then by default this column would be set to 5000.00.
SQL> CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR2 (20) NOT NULL, AGE INT NOT NULL,
ADDRESS CHAR (25) , SALARY DECIMAL (18, 2) DEFAULT 5000.00, PRIMARY KEY (ID));
SQL> Insert into customers (id,name,age,address) values(1,’RASHED’,23,’GOLCONDA FORT’);
SQL> Insert into customers values(1,’RASHED’,23,’GOLCONDA FORT’,7599);
SQL> Select * from customers;
If CUSTOMERS table has already been created, then to add a DFAULT constraint to SALARY
column, you would write a statement similar to the following:
ALTER TABLE CUSTOMERS MODIFY SALARY DECIMAL (18, 2) DEFAULT 5000.00;
Drop Default Constraint: To drop a DEFAULT constraint, use the following SQL:
ALTER TABLE CUSTOMERS ALTER COLUMN SALARY DROP DEFAULT;
PNo: 42
TECH IQ Technologies
Syntax:
column-name data-type(size) PRIMARY KEY
Example:
Create a table client_master where the column client_no is its primary key.
//Inserting data
INSERT INTO CLIENT_MASTER VALUES('C1','AHMED','ST COLONY',
'KOTHI','HYDERABAD','AP',500043,564.23);
//Composite Primary key: When we want multiple column value to be same then we
will use composite primary key
Example:
Create a table sales_order_details where there is a composite primary key on the
column detlorder_no and product_no. Since the constraint spans across columns,
describe it at table level.
PNo: 43
TECH IQ Technologies
Table created
PNo: 44
TECH IQ Technologies
Create table emp1 (eno number(5) PRIMARY KEY, ename varchar2(15),
Job varchar2(15),salary number(7));
The table in which the foreign key is defined is called a Foreign table and the
table that defines the primary
or unique key and is referenced by the foreign key is called the Primary table.
Syntax:
column-name data-type(size) REFERENCES table-name (column-name) [ON DELETE
CASCADE] ;
eg:
Table for Primary key
----------------------
drop table emp_promotion;
drop table emp_loan;
drop table emp;
drop table dept;
PNo: 45
TECH IQ Technologies
PNo: 46
TECH IQ Technologies
insert into emp values(11,'KARTIK','SHIMLA','MANAGER',7985,'14-FEB-2016',101);
insert into emp values(12,'JAFFER','ADONI','T.INSPECTOR',8899,'12-JUN-2015',301);
//Retrieving data from both tables
SQL> SELECT E.ENO,E.ENAME,E.CITY,E.JOB,E.SALARY,e.hiredate,D.dept_NAME,D.DEPT_ID
FROM EMP E,DEPT D WHERE E.DEPT_ID=D.DEPT_ID;
SELECT E.ENO,E.ENAME,E.CITY,E.JOB,E.SALARY,e.hiredate,D.dept_NAME,D.DEPT_ID,
l.loan_amount,l.loan_date FROM EMP E,DEPT D,EMP_LOAN l WHERE E.DEPT_ID=D.DEPT_ID
and E.ENO=L.ENO;
SELECT E.ENO,E.ENAME,E.CITY,E.JOB,E.SALARY,D.dept_NAME,D.DEPT_ID,l.loan_amount,
l.loan_date,p.promotion,p.bonus,p.promotion_date FROM EMP E,DEPT D,EMP_LOAN
l,emp_promotion p WHERE E.DEPT_ID=D.DEPT_ID and E.ENO=L.ENO and e.eno=p.eno;
PNo: 47
TECH IQ Technologies
references emp(eno),foreign key (dept_id)references dept(dept_id) ON DELETE
CASCADE);
desc Emp_projects
SELECT
E.ENO,E.ENAME,E.CITY,E.JOB,E.SALARY,D.dept_NAME,D.DEPT_ID,l.loan_amount,l.loan_da
te,p.promotion,p.bonus,
p.promotion_date,i.projects,i.STARTING_DATE,i.END_DATE FROM EMP E,DEPT D,EMP_LOAN
l,emp_promotion p,Emp_projects i WHERE E.DEPT_ID=D.DEPT_ID and E.ENO=L.ENO and
e.eno=p.eno and e.eno=i.eno;
Dropping Constraints:
----------------------
Any constraint that you have defined can be dropped using the ALTER TABLE command
with the DROP CONSTRAINT option.
For example, to drop the primary key constraint in the EMPLOYEES table, you can
use the following command:
ALTER TABLE EMP DROP CONSTRAINT e1;
Insert Into Emp Values(13,'JAFFER','ADONI','INSPECTOR',8899,'12-JUN-2015',90);
insert into emp values(14,'PRADEEP','ADONI','INSPECTOR',8899,'12-JUN-2015',80);
PNo: 48
TECH IQ Technologies
CHECK constraint defined at the column level:
Syntax:
Column-name data-type(size) CHECK (logical expression)
Example:
Create a table client_master with the following check constraints:
->Data values being inserted into the column client_no must start with the
capital letter 'C'.
->Data values being inserted into the column name should be in upper case only.
->Only allow "Bombay","Delhi","Madras" and "Calcutta" as legitimate values for
the column city.
//Disabling constraint
alter table client_master2 disable constraint a;
insert into client_maste2 values('1005','PRADEEP','4/A,K.R Apts','Seven
Wonders','Chennai','Tamil Nadu');
//Enabling constraint
alter table client_master2 enable constraint a;
//Dropping constraint
alter table client_master2 drop constraint a;
PNo: 49
TECH IQ Technologies
Insert Into Election Values(101,'SACHIN','SHANTI NAGAR',20);
Insert Into Election Values(102,','LOWER S.R.NAGAR',18);
insert into election values(103,'K. RATHORE','KP COLONY',17);
insert into election values(103,'R. ARVIND','KP COLONY',17);
PNO NUMBER(5)
NAME VARCHAR2(7)
ADMISSION DATE
DISCHARGE DATE
DEPOSIT NUMBER(8)
ROOMFEES NUMBER(5)
DAYS NUMBER(4)
PAYMENT NUMBER(8)
CHARGES NUMBER(6)
BALANCE NUMBER(8)
BILL NUMBER(8)
Example 1
----------
PNo: 50
TECH IQ Technologies
DROP TABLE EMP;
3.List The Total Salary, Maximum And Minimum Salary And The Average Salary Of
Employees Job Wise ?
sql> select job, sum(sal), avg(sal), max(sal), min(sal) from emp group by job ;
Having Clause
-----------------
The having clause is used to specify which groups are to be displayed that means
it restricts the groups which returns on the basis of aggregate functions
(Or)
This is used to define condition on the columns used after the group by clause.
It is used to restrict the number of rows by specifying a condition with the
grouped columns
Examples :
4. List The average salary of all the Departments employing more than 5 people ?
sql> select deptno, avg(sal) from emp group by deptno having count(*)>5;
5. List the jobs of all the employees whose maximum salary is >=5000?
sql> select job, max(sal) from emp group by job having max(sal)>=5000;
Order By Clause
-------------------
The order by clause is used to arrange the rows in Ascending or indescending
order. By default the select statement displays in ascending order. If you want
to display in descending order, specify the “desc”keyword after the column name.
Multiple columns are ordered one within another, and the user can specify whether
to order them in ascending or in descending order.
PNo: 51
TECH IQ Technologies
7. List The Employee Name In Ascending Order And Their Salaries In Descending
Order?
sql> select ename ,sal from emp order by ename, sal desc;
Example: 2
drop table customer;
create table customer(CNO NUMBER,cNAME VARCHAR2(15),PRODUCT VARCHAR2(15),qTY NUMBER,
PRICE NUMBER,purchase_date date,BILL NUMBER,DISCOUNT NUMBER(9,2),
FINAL_AMT NUMBER(9,2));
(101,'JUNAID','BAG',7,390,'15-SEP-2009');
insert into customer(cno,cname,product,qty,price,purchase_date) values
(102,'SURESH','BOOK',15,90,'07-NOV-2015');
insert into customer(cno,cname,product,qty,price,purchase_date) values
(103,'PRADEEP','SHOES',12,450,'12-FEB-2014');
insert into customer(cno,cname,product,qty,price,purchase_date) values
(101,'JUNAID','CAP',25,150,'03-JUN-2013');
insert into customer(cno,cname,product,qty,price,purchase_date) values
(102,'SURESH','SHIFT',13,345,'06-MAY-2012');
insert into customer(cno,cname,product,qty,price,purchase_date) values
(101,'JUNAID','PENDRIVE',18,890,'09-AUG-2014');
insert into customer(cno,cname,product,qty,price,purchase_date) values
(103,'PRADEEP','BAG',15,410,'02-JUL-2014');
insert into customer(cno,cname,product,qty,price,purchase_date) values
(101,'JUNAID','CROCKERY',7,1200,'19-DEC-2015');
insert into customer(cno,cname,product,qty,price,purchase_date) values
(105,'MAHESH','FRUITS',15,90,'04-NOV-2014');
insert into customer(cno,cname,product,qty,price,purchase_date) values(106,'SAJID','BRAKE
LINER',25,880,'15-APR-2015');
commit;
PNo: 52
TECH IQ Technologies
order by cno;
Example 3:
drop table sales_order7;
create table sales_order7(pno number(5),
pname varchar2(12),quantity number(3));
insert into sales_order7 values(1,'MOBILE',7);
insert into sales_order7 values(2,'KEYBOARD',10);
insert into sales_order7 values(3,'MOUSE',5);
insert into sales_order7 values(4,'CAP',20);
insert into sales_order7 values(5,'BALL',12);
insert into sales_order7 values(2,'BOOK',15);
insert into sales_order7 values(2,'PEN',12);
insert into sales_order7 values(1,'SHOES',7);
insert into sales_order7 values(3,'BIKE',9);
insert into sales_order7 values(6,'BAG',14);
//Adding new column ‘adddate’
alter table sales_order7 add adddate date;
update sales_order7 set adddate='01-MAR-2009' where pno=1;
update sales_order7 set adddate='15-sep-2004' where pno=2;
update sales_order7 set adddate='12-nov-2010' where pno=3;
update sales_order7 set adddate='01-aug-2005' where pno=4;
update sales_order7 set adddate='15-MAR-2002' where pno=5;
//Adding column ‘City’
alter table sales_order7 add city varchar2(15);
update sales_order7 set city='HYDERABAD' where pno=2;
update sales_order7 set city='NAGPUR' where PNO=1;
update sales_order7 set city='AGARTALTA' where pno=4;
insert into sales_order7 values(1,'WATCH',5,'25-JUN-2009','DELHI');
insert into sales_order7 values(1,'BISCUITS',12,'15-SEP-2008','KANPUR');
insert into sales_order7 values(1,'UMBRELLA',5,'25-JUN-2004','JAIPUR');
select pno,adddate,CITY,sum(quantity) from sales_order7 group by
(pno,adddate,CITY) order by pno;
SELECT PNO,CITY,SUM(QUANTITY) FROM SALES_ORDER7 GROUP BY (PNO,city) HAVING PNO=1
AND CITY='NAGPUR';
SELECT PNO,CITY,SUM(QUANTITY) FROM SALES_ORDER7 GROUP BY (PNO,city) HAVING
CITY='HYDERABAD';
SELECT PNO,CITY,SUM(QUANTITY) FROM SALES_ORDER7 GROUP BY (PNO,city) HAVING PNO>=2
ORDER BY PNO;
PNo: 53
TECH IQ Technologies
1 SHOES 7
3 BIKE 9
6 BAG 14
1 CHAIR 14
SQL> select pno,sum(quantity) "Total Qty Ordered" from sales_order7 GROUP BY PNO;
PNo: 54
TECH IQ Technologies
insert into emp_company values('PRADEEP','VIRTUSA',
29439,'29-AUG-2004');
insert into emp_company values('SANDEEP','INFOSYS',
38484,'10-APR-2002');
Example 4: Displaying the names of companies and the maximum salary in that
company.
CNAME MAX(SALARY)
------------ -----------
ACC 8000
TATA 5003
TCS 9493
WIPRO 6940
CMC 1800
CNAME COUNT(ENAME)
PNo: 55
TECH IQ Technologies
------------ ------------
ACC 3
TATA 3
TCS 3
WIPRO 1
CMC 2
CNAME MAX(SALARY)
------------ -----------
ACC 8000
TATA 5003
TCS 9493
WIPRO 6940
CMC 1800
SUM(SALARY)
-----------
11894
HAVING Clause: The HAVING clause can be used in conjunction with the GROUP BY
clause. HAVING imposes a condition on the GROUP BY clause, which further filters
the groups created by the GROUP BY clause.
eg:
SQL> select pno,sum(quantity) "Total Qty" from sales_order7 GROUP BY pno HAVING
pno=3 or pno=5;
SQL> select pno,sum(quantity) "Total Qty" from sales_order GROUP BY pno HAVING
pno=1 or pno=4;
PNo: 56
TECH IQ Technologies
SQL> select cname,count(ename) from emp_company group by cname having
count(ename) > 1;
CNAME COUNT(ENAME)
------------ ------------
ACC 3
TATA 3
TCS 3
CMC 2
Example 3: Finding the average salary of each company
SQL> select cname,avg(salary) from emp_company group by cname;
CNAME AVG(SALARY)
------------ -----------
ACC 3964.66667
TATA 3348.66667
TCS 7810
WIPRO 6940
CMC 1750
Example 4: Displaying the average salary of each company except 'INFOSYS'.
CNAME AVG(SALARY)
------------ -----------
TCS 7810
WIPRO 6940
PNo: 57
TECH IQ Technologies
Example 5: Displaying the average salary of company only for employees living in
'Delhi'.
CNAME AVG(E.SALARY)
------------ -------------
TATA 5003
TCS 5000
Using 'WITH' Clause: Using 'With' clause, you can reduce the overheads for
computing the same queries. Suppose you want to use the result of a certain query
repeatedly. Then you can mark that query using 'WITH' clause. Internally, Oracle
forms temporary tables based on the result of query and use that table for the
rest of the query evaluation.
CNAME SUM(SALARY)
------------ -----------
ACC 11894
TATA 10046
TCS 23430
WIPRO 6940
CMC 3500
-> In the following query, the first and second query is named COMPANYSALARY and
COMPANYAVGSALARY respectively.
CNAME TOTALSAL
------------ ----------
ACC 11894
TCS 23430
ORDER BY clause: With 'ORDER BY' clause, you can order your output using order by
clause.
PNo: 58
TECH IQ Technologies
SUB QUERIES:
SUB QUERIES: A subquery is a form of an SQL statement that appears inside another
SQL statement. It
is also termed as nested query. The statement containing a subquery is called a
parent statement. The
parent statement uses the rows returned by the subquery.
The subquery can also be referred as nested SELECT, sub SELECT or inner SELECT.
In general, the subquery executes first and its output is used in the main query
or outer query.
1. Write a query to find the salary of employees whose salary is greater than the
salary of employee whose id is 5?
PNo: 59
TECH IQ Technologies
insert into emp1 values(6,'ANIL','DOCTOR','SUDHIR',9984,501);
insert into emp1 values(7,'YOUSUF','PROGRAMMER','SMITH',6982,101);
insert into emp1 values(8,'KALYAN','ACCOUNTANT','AUSTIN',4958,301);
insert into emp1 values(9,'RAHMAN','PROGRAMMER','SMITH',2345,101);
insert into emp1 values(10,'IMRAN','ACCOUNTANT','AUSTIN',6894,301);
insert into emp1 values(11,'SAJID','ANALYST','SANDEEP',3562,201);
insert into emp1 values(12,'RAJESH','MANAGER','RAHMAN',4987,401);
insert into emp1 values(13,'DANIEL','PROGRAMMER','SMITH',8603,101);
insert into emp1 values(14,'TAHER','ANALYST','SANDEEP',9846,201);
insert into emp1 values(15,'SUNIL','ACCOUNTANT','AUSTIN',6982,301);
insert into emp1 values(16,'SACHIN','DOCTOR','SANDEEP',9994,501);
SQL>SELECT Eno,ename, SALARY FROM EMP1 WHERE SALARY > ( SELECT SALARY FROM EMP1
WHERE Eno = 5 );
2. Write a query to find the departments in which the least salary is greater
than the highest salary in the department of id 101?
3. Write a query to list the department names which have at lease one employee?
4. Write a query to find the departments in which the least salary is greater
than the highest salary in the department of id 101?
1. Write a query to find the employees whose salary is equal to the salary of at
least one employee in department of id 301?
2. Write a query to find the employees whose salary is greater than at least one
employee in department of id 201?
SQL>SELECT Eno,ename, SALARY,dept_id FROM EMP1 WHERE salary not in (select salary
from emp1 where dept_id=201) and SALARY > ANY (SELECT SALARY FROM EMP1 WHERE
DEPT_ID = 201 );
PNo: 60
TECH IQ Technologies
3. Write a query to find the employees whose salary is less than the salary of
all employees in department of id 301?
SQL>SELECT Eno,ename, SALARY FROM EMP1 WHERE SALARY < ALL ( SELECT SALARY FROM
EMP1 WHERE DEPT_ID = 301 );
4. Write a query to find the employees who all are earning the highest salary?
5. Write a query to find the employees whose manager and department should match
with the employee of id 2,5,9,12,15 ?
eg: Retrieve all orders placed by a client named 'ALI' from the sales_order
table.
1. Table Sales_Order77
---------------------------
SQL> CREATE TABLE SALES_ORDER77(PRODUCT_NO NUMBER(5),
product varchar2(2),QUANTITY NUMBER(4),price number(7),
ORDERNO NUMBER(7),ORDERDATE DATE,CLIENT_NO VARCHAR2(7));
2. Table Client_Master1
-----------------------------
SQL> CREATE TABLE CLIENT_MASTER1(CLIENT_NO VARCHAR2(7),NAME
VARCHAR2(12),designation VARCHAR2(5));
PNo: 61
TECH IQ Technologies
2. Find out all the products that are not being sold from the product_master
table, based on the products actually sold as shows in the sales_order_detailts
table.
PNo: 62
TECH IQ Technologies
INSERT INTO SALES_ORDER2 VALUES('O10002','P00005',40,40);
INSERT INTO SALES_ORDER2 VALUES('O10003','P00003',2,2);
INSERT INTO SALES_ORDER2 VALUES('O10004','P00001',6,6);
INSERT INTO SALES_ORDER2 VALUES('010005','P00001',1,1);
INSERT INTO SALES_ORDER2 VALUES('O10006','P00008',8,8);
PRODUCT DESCRIPTION
------- ------------
P00004 FLOPPIES
P00009 COMPUTER
3. Retrieve the names of all personnel who work in Mr.ZAHEER's department and
have worked on an inventory control system
as well, from the tables emp and inv_sys.
eg:
PNo: 63
TECH IQ Technologies
INSERT INTO EMP1 VALUES(2,'JOSHI','D02');
INSERT INTO EMP1 VALUES(3,'LENNA','D01');
INSERT INTO EMP1 VALUES(11,'DADA','D03');
INSERT INTO EMP1 VALUES(4,'ZAHEER','D01');
INSERT INTO EMP1 VALUES(5,'PRADEEP','D01');
INSERT INTO EMP1 VALUES(6,'AMJAD','D02');
INSERT INTO EMP1 VALUES(7,'SALEEM','D03');
INSERT INTO EMP1 VALUES(8,'SANDEEP','D02');
INSERT INTO EMP1 VALUES(9,'PRASHANT','D01');
INSERT INTO EMP1 VALUES(10,'JUNAID','D02');
SQL> SELECT ENAME,DEPTNO FROM EMP1 WHERE DEPTNO IN(SELECT DEPTNO FROM EMP1 WHERE
ENAME='ZAHEER') AND
ENAME IN (SELECT ENAME FROM INV_SYS);
PNo: 64
TECH IQ Technologies
insert into emp values(1,'SANDEEP','ENGINEER','HYDERABAD','24-JUN-2014', 6000,
473, 2, 30);
2.Display details of all employees who are working in city ‘NEW DELHI’
A. select * from emp where city='NEW DELHI';3.
4 DisPlay list of all employees who has been hired between ’01-Jan-2013’ and ’31-
dec-2015’.
A. SELECT * FROM EMP WHERE HIREDATE BETWEEN'01-JAN-2014' AND '31-DEC-2015';
PNo: 65
TECH IQ Technologies
6.Display the names of all employees working as clerks and drawing a salary more
than 3000
A. SELECT * FROM EMP WHERE JOB='CLERK' AND SALARY > 3000;
7. Display the names of employees who are working in the company for the past 5
years
A.SELECT ENAME FROM EMP WHERE HIREDATE BETWEEN '01-JAN-2014' AND'01-JAN-2016';
9. Display the employee Number and name for employee working as clerk and
earning highest salary among the clerks?
A. SELECT EMPNO,ENAME,JOB,SALARY FROM EMP WHERE SALARY=(SELECT MAX(SALARY) FROM
EMP WHERE JOB IN('CLERK'));
10. Display the names of salesman who earns a salary more than the Highest Salary
of the Clerk?
A. SELECT * FROM EMP WHERE JOB='SALESMAN' AND SALARY > (SELECT MAX(SALARY) FROM
EMP WHERE JOB IN('CLERK'));
11. Display the names of clerks who earn a salary more than the lowest Salary of
any Salesman?
SELECT * FROM EMP WHERE JOB='CLERK' AND SALARY>(SELECT MIN(SALARY) FROM EMP
WHERE JOB IN('SALESMAN'));
12. Display the names of employees who earn a salary more than that of ZAHEER or
that of salary greater than that of RAMESH?
SELECT * FROM EMP WHERE SALARY >( SELECT MAX(SALARY) FROM EMP WHERE ENAME IN
('ZAHEER','RAMESH'));
13. Display the names of employees who earn Highest salary in their respective
departments?
A) SELECT DEPTNO, MAX(SALARY) FROM EMP GROUP BY DEPTNO;
14. Display the name of employees along with their annual salary(sal*12).
the name of the employee earning highest annual salary should appear first?
A)select empno,ename,salary "Monthly sal",salary+salary*12 "Annual Salary" from
emp order by salary desc;
Q)16. Display Department numbers and total number of employees working in each
Department?
PNo: 66
TECH IQ Technologies
A) select deptno,count(empno) from emp group by deptno order by deptno;
Q)17. Display the various jobs and total number of employees working in each job
group?
A) select job,count(empno) from emp group by job;
Q)18. Display department numbers and Total Salary for each Department?
A) select deptno,sum(salary) from emp group by deptno order by deptno;
Q)19. Display department numbers and Maximum Salary from each Department?
A) select deptno,max(salary) from emp group by deptno;
Q)20. Display various jobs and Total Salary for each job?
A) select job,sum(salary) from emp group by job;
Q)21. Display each job along with min of salary being paid in each job group?
A) select job,min(salary) from emp group by job;
Q)22. Display the department Number with more than three employees in each
department?
A) select deptno,count(deptno) from emp group by deptno having count(deptno)>3;
select deptno,count(deptno) from emp group by deptno having count(deptno)>2;
select deptno,count(deptno) from emp group by deptno having count(deptno)>=2;
Q)23. Display various jobs along with total salary for each of the job
where total salary is greater than 40000?
A) select job,sum(salary)from emp group by job having sum(salary)>20000;
Q)24. Display the various jobs along with total number of employees in each
job.The output should contain only those jobs with more than three employees?
A) select job,count(job) from emp group by job having count(job)>2;
Q)25. Display the job groups having Total Salary greater than the maximum salary
for Managers?
A) select job,sum(salary) from emp group by job having MAX(salary)>(select max
(salary) from emp where job='CLERK');
CORRELATED SUBQUERIES:
---------------------------------
Correlated SubQueries is another way to perform multi table joins.
A 'where' clause can contain a subquery 'select'. Subquery 'selects' can be
nested- that is, a 'where' clause in a subquery also can contain a 'where' clause
with a subquery,which can contain a 'where' clause with a subquery --On down for
more levels than you are ever likely to need.
The following example shows three 'select's, each connected to another through a
'where' clause.
PNo: 67
TECH IQ Technologies
Output:
PARENTCA SUBCATEGORY
-------- -------------
CHILDREN PICTURE BOOK
ADULT FICTION
ADULT REFERENCE
CHILDREN FICTION
ADULT NONFICTION
->The above query selects any categories containing books that have been checked
out. It does this simply by requesting a book whose Title is in the BookShelf
table and whose Checkout record is in the BookShelf_Checkout table. In a
subquery, Oracle assumes the columns to be from nested subquery, because for
every CategoryName in the main (outer) query, the CategoryName may be correlated
in the second 'where' clause.
Correlated SubQueries
----------------------------
CORRELATED SUBQUERIES: Is evaluated for each row processed by the Main query.
Execute the Inner query based on the value fetched by the Outer query. Continues
till all the values returned by the main query are matched. The INNER Query is
driven by the OUTER Query
SQL Correlated Subqueries are used to select data from a table referenced in the
outer query. The subquery is known as a correlated because the subquery is
related to the outer query. In this type of queries, a table alias (also called a
correlation name) must be used to specify which table reference is to be used.
The alias is the pet name of a table which is brought about by putting directly
after the table name in the FROM clause. This is suitable when any body wants to
obtain information from two separate tables.
Correlated sub query is used for row by row processing. The sub query is executed
for each row of the main query.
Co-Related Vs Nested-SubQueries.
Technical difference between Normal Sub-query and Co-related sub-query are:
1. Looping: Co-related sub-query loop under main-query; whereas nested not;
therefore co-related sub-query executes on each iteration of main query. Whereas
in case of Nested-query; subquery executes first then outer query executes next.
Hence, the maximum no. of executes are NXM for correlated subquery and N+M for
subquery.
2. Dependency(Inner to Outer vs Outer to Inner): In the case of co-related
subquery, inner query depends on outer query for processing whereas in normal
sub-query, Outer query depends on inner query.
3.Performance: Using Co-related sub-query performance decreases, since, it
performs NXM iterations instead of N+M iterations. ¨ Co-related Sub-query
Execution.
PNo: 68
TECH IQ Technologies
2. Write a query to list the department names which have at lease one employee?
PNo: 69
TECH IQ Technologies
insert into emp values(10,'SUDHAKAR','COCHIN','CLERK',301);
3. Write a query to find the departments which do not have employees at all?
//Second way
SELECT * FROM Emp1 E1 WHERE (4-1) = (SELECT COUNT(DISTINCT(E2.Salary))FROM Emp1 E2
WHERE E2.Salary > E1.Salary);
//Third way
select * from (select E1.*,row_number() over (order by Salary DESC) rownumb
from Emp1 E1) where rownumb = 2; /*n is nth highest salary*/
//Fourth way
select Eno,ename, Salary ,rank() over (order by Salary DESC) ranking from Emp1;
select * FROM ( select Eno,ename, Salary ,rank() over (order by Salary DESC)
ranking from Emp1 ) WHERE ranking = 2;
JOINS:
SQL Join is used to fetch data from two or more tables, which is joined to appear
as single set of data. SQL Join is used for combining column from two or more
tables by using values common to both tables. Join Keyword is used in SQL queries
for joining two or more tables. Minimum required condition for joining table,
is(n-1) where n, is number of tables
Types of Joins
------------------
1 Equijoin
2 Non-equijoin
3 Self join
4 Natural join
5 Cross join
6 Outer join
• Left outer
PNo: 70
TECH IQ Technologies
• Right outer
• Full outer
7 Inner join
8 Using clause
9 On clause
1. EQUI JOIN
A join which contains an equal to ‘=’ operator in the joins condition.
Ex:
SQL> select empno,ename,job,dname,loc from empe,dept d where e.deptno=d.deptno;
2. NON-EQUI JOIN
A join which contains an operator other than equal to ‘=’ in the joins
condition.
Ex:
SQL> select empno,ename,job,dname,location from empe,dept d where
e.deptno>d.deptno;
3. SELF JOIN
Joining the table itself is called self join.
Ex:
Displaying a list of employees living in the city where SUNIL is living.
PNo: 71
TECH IQ Technologies
INSERT INTO EMPLOYEE VALUES('SUNIL','BOMBAY');
INSERT INTO EMPLOYEE VALUES('SAMI','HYDERABAD');
INSERT INTO EMPLOYEE VALUES('NAZEER','BOMBAY');
INSERT INTO EMPLOYEE VALUES('JUNAID','BANGLORE');
INSERT INTO EMPLOYEE VALUES('VIJAY','DELHI');
INSERT INTO EMPLOYEE VALUES('PRAKASH','CALCUTTA');
4. NATURAL JOIN
Natural join compares all the common columns.
Ex:
SQL> select empno,ename,job,dname,location from emp natural join dept;
PNo: 72
TECH IQ Technologies
emp_company c where e.ename=c.ename;
Note: When you specify a 'NATURAL JOIN', a cartesian product is made and the
'where' condition is constructed using columns having the same name from both the
tables. But, if you qualifier name is 'NATURAL JOIN' then it will give error.
Using Clause:
----------------
If you want to perform a 'NATURAL JOIN' on a specified column name, you can use
'USING' clause.
Note: if you specify JOIN USING, you cannot specify NATURAL JOIN. The equality
condition in the 'where' clause is constructed by using the columns name
specified in 'where' condition.
ON Clause:
-------------
It is like 'where' clause and you can put multiple conditions in the 'ON' clause.
OUTER JOIN:
---------------
PNo: 73
TECH IQ Technologies
'OUTER JOIN' is used when you want to output all rows from one table. In the
NATURAL JOIN, the row is in the output only if it is joined with the
corresponding row row in another table. In this case, the row is joined with an
imaginary row of another table.
->In the above query, all rows from 'MANAGER' are produced and the row that
cannot be joined with row from EMP_SHIFT (like row of SUNIL), is joined with
imaginary row of EMP_SHIFT.
FULL OUTER JOIN: In case of full outer join, rows from both the tables rows are
produced.
PNo: 74
TECH IQ Technologies
5. CROSS JOIN
This will gives the cross product.
Ex:
SQL> select empno,ename,job,dname,loc from emp cross join dept;
6. OUTER JOIN
Outer join gives the non-matching records along with matching records.
Ex:
SQL> select empno,ename,job,dname,loc from emp e left outer join dept d
on(e.deptno=d.deptno);
Or
SQL> select empno,ename,job,dname,loc from empe,dept d where
e.deptno=d.deptno(+);
Ex:
SQL> select empno,ename,job,dname,loc from emp e right outer join dept d
on(e.deptno=d.deptno);
Or
SQL> select empno,ename,job,dname,loc from empe,dept d where e.deptno(+) =
d.deptno;
7. INNER JOIN
This will display all the records that have matched.
Ex:
SQL> select empno,ename,job,dname,loc from emp inner join dept using(deptno);
PNo: 75
TECH IQ Technologies
UNION Operation:
----------------------
Suppose there are two sets, S and R:
S={a,b,c}
R={x,y,z}
Then R union S will be
R U S= {a,b,c,x,y,z}
An important condition for performing operations on sets is that the elements of one set must
compatible with the elements of the other set. If the element of one set has only one part then the
set element of the other set must also have only one part, of course, with compatible data type.
DROP TABLE COMPANY;
create table company(cname varchar2(15),city varchar2(15));
insert into company values('ACC','BOMBAY');
insert into company values('TATA','BOMBAY');
insert into company values('ACC','NAGPUR');
insert into company values('CMC','BOMBAY');
insert into company values('CMC','MADRAS');
insert into company values('TATA','BOMBAY');
insert into company values('TCS','HYDERABAD');
insert into company values('CMC','HYDERABAD');
insert into company values('TATA','HYDERABAD');
insert into company values('ACC','BOMBAY');
insert into company values('TCS','DELHI');
insert into company values('ACC','PUNE');
insert into company values('ACC','AHMEDABAD');
insert into company values('TATA','BANGALORE');
SQL> SELECT * FROM COMPANY;
CNAME CITY
---------- ----------
ACC MADRAS
TATA BOMBAY
ACC NAGPUR
CMC BOMBAY
CMC MADRAS
TATA DELHI
TCS HYDERABAD
CMC HYDERABAD
TATA HYDERABAD
ACC HYDERABAD
TCS DELHI
Example: Getting the cities of companies ACC and TATA
PNo: 76
TECH IQ Technologies
MADRAS
NAGPUR
INTERSECT OPERATION:
-----------------------------
Intersect is used for finding out the common elements of sets.
Suppose you have two sets S and R.
S={a,b,c}
R={a,y,z}
Then intersect operation will produce the following result:
S intersect R = {a}
Example: Retrieving the name fo the city, that is common to companies ACC and TATA
SQL> select city from company where cname='ACC' INTERSECT select city from company where
cname='TATA';
CITY
----------
HYDERABAD
MINUS OPERATION:
------------------------
Minus is used for finding out elements that are present in one set but not in the other. Suppose
you have two sets S and R:
S = {a,b,c}
R = {a,y,z}
SQL> select city from company where cname='ACC' MINUS select city from company where
cname='TATA';
CITY
----------
MADRAS
NAGPUR
ACC={MADRAS,NAGPUR,HYDERABAD,PUNE,AHMEDABAD}
TATA={BOMBAY,DELHI,HYDERABAD,BANGALORE}
{MADRAS,NAGPUR,HYDERABAD,PUNE,AHMEDABAD}-{BOMBAY,DELHI,HYDERABAD,BANGALORE}
{BOMBAY,DELHI,HYDERABAD,BANGALORE}-{MADRAS,NAGPUR,HYDERABAD,PUNE,AHMEDABAD}
ACC-TATA
PNo: 77
TECH IQ Technologies
insert into emp_company values('SALIM','WIPRO',39948,'18-MAR-2006');
insert into emp_company values('SAJID','INFOSYS',43959,'24-JAN-2005');
insert into emp_company values('LATEEF','SATYAM',39839,'23-FEB-2005');
insert into emp_company values('WASEEM','ORACLE',48949,'16-MAY-2005');
insert into emp_company values('OMAR','WIPRO',49394,'17-SEP-2006');
insert into emp_company values('RAHMAN','TATA',83894,'23-APR-2004');
insert into emp_company values('HUSSAIN','TATA',83894,'23-APR-2004');
insert into emp_company values('FARID','TATA',83894,'23-APR-2004');
insert into emp_company values('SURESH','ACC',83894,'23-APR-2004');
insert into emp_company values('KALEEM','TATA',90894,'23-APR-2004');
insert into emp_company values('HAMED','INFOSYS',84444,'23-APR-2004');
ENAME CITY
------------ ------------
SUNIL BOMBAY
SAMI HYDERABAD
JUNAID BANGLORE
NAZEER BOMBAY
VIJAY DELHI
PRAKASH CALCUTTA
AJAY MADRAS
QUADEER MADRAS
AMJAD DELHI
ANIL NAGPUR
SHANKAR BOMBAY
ENAME CITY
------------ ------------
JAYA MADRAS
NAVED HYDERABAD
SQL> SELECT * FROM EMP_COMPANY;
ENAME CNAME SALARY DOJ
------------ ------------ ---------- ---------
ANIL ACC 1500 01-MAY-04
AMJAD TCS 5000 23-NOV-05
JUNAID WIPRO 6940 17-AUG-07
NAZEER TCS 9493 12-JUN-08
SHANKAR TATA 2043 10-JUL-03
JAYA CMC 1800 07-JUN-03
PNo: 78
TECH IQ Technologies
SUNIL CMC 1700 01-JAN-01
VIJAY TATA 5003 27-MAY-07
QUADEER TCS 8937 24-OCT-03
PRAKASH TATA 3000 27-MAY-09
AJAY ACC 8000 30-APR-04
SQL> SELECT ENAME FROM EMPLOYEE where city ='BOMBAY' INTERSECT select ename from
emp_company where cname='TATA';
SQL> SELECT CNAME FROM COMPANY WHERE CITY='BOMBAY' MINUS SELECT CNAME FROM
EMP_COMPANY WHERE SALARY>=83894;
ENAME
------------
CMC
Example: Displaying the names of employees living in BOMBAY but not working with company TATA
SQL> SELECT ENAME FROM EMPLOYEE where city ='BOMBAY' MINUS select ename from emp_company
where cname='TATA';
ENAME
------------
NAZEER
SUNIL
Example: Displaying the names of employees living in 'NAGPUR', working in ACC, and having shift A.
SQL> select ename from employee where city='NAGPUR' INTERSECT select ename from
emp_company where cname='ACC' INTERSECT select ename from emp_shift where shift='A';
ENAME
------------
ANIL
Example: Displaying the names of employees living in 'NAGPUR', working in ACC, and not having shift A.
SQL> select * from emp_shift;
ENAME SHIFT
------------ ----------
SUNIL B
ANIL A
VIJAY B
PRAKASH C
JUNAID A
SAMI B
QUADEER B
NAZEER A
AMJAD B
SQL> select ename from employee where city='NAGPUR' INTERSECT select ename from emp_company
where cname='ACC' MINUS select ename from emp_shift
where shift='A';
no rows selected
Example: Displaying the names of employees who are living in NAGPUR or BOMBAY.
PNo: 79
TECH IQ Technologies
SQL> select ename from employee where city='NAGPUR' UNION select ename from employee where
city='BOMBAY';
ENAME
------------
ANIL
NAZEER
SHANKAR
SUNIL
//Another Example
DROP TABLE COUNTRIES;
create table countries(name varchar2(15));
NAME
---------------
AFGHANISTAN
BANGLADESH
CAMBODIA
CHINA
DANISH
INDIA
NEPAL
PAKISTAN
SRI LANKA
SQL> select * from countries where name='INDIA' UNION ALL SELECT * FROM COUNTRIES WHERE
NAME NOT IN ('INDIA');
NAME
---------------
INDIA
AFGHANISTAN
BANGLADESH
CAMBODIA
CHINA
DANISH
NEPAL
PAKISTAN
SRI LANKA
xiii. INDEX
PNo: 80
TECH IQ Technologies
When the user fires a SELECT statement to search for a particular record, the Oracle engine must first
locate the table on the hard disk. The Oracle engine reads system information and locates the starting
location of a table's records on the current storage media. The Oracle engine then performs a sequential
search to locate records that match user-defined criteria.
INDEXES: Indexes are essential to improve the speed with which the records can be located and retrieved
from a table.
When data is inserted in the table, the Oracle engine inserts the data value in the index. For every data
value held in the index the Oracle engine inserts a unique rowid value. This is done for every data value in
to the index, withoud exception. This rowid indicates exactly where the record is stored in the table.
->The records in the index are sorted in the ascending order of the index columns.
->If the SELECT statement has where clause for th table column that is indexed, the Oracle engine will
scan the index sequentially looking for a match of the seach criteria rather than the table column itself.
Duplicate/Unique Index:
->Indexes that allow duplicate values for the indexed columns i.e Duplicate Index.
->Indexes that deny duplicate values for the indexed columns i.e Unique Index.
Creation of Index:
An index can be created on one or more columns. Based on the number of columns included in the index,
an index can be:
->Simple Index
->Composite Index
Syntax:
Create INDEX indexname ON tablename(column-name);
PNo: 81
TECH IQ Technologies
ENAME VARCHAR2(12)
JOB VARCHAR2(12)
CITY VARCHAR2(12)
HIREDATE DATE
SALARY NUMBER(5)
COMM NUMBER(3)
MGR NUMBER(3)
An unique index can also be created on one or more columns. If an index is created on a single column it is
called Simple Unique Index.
Syntax:
Create UNIQUE INDEX indexname ON tablename(columnname);
If an index is created on more than one column it is called Composite Unique Index.
Syntax:
Create UNIQUE INDEX indexname ON tablename(columname,columname);
Example:
Create UNIQUE INDEX idx_date ON emp13(hiredate);
Dropping Indexes:
Indexes associated with the tables can be removed by using the DROP INDEX command.
Syntax:
DROP INDEX indexname;
Example:
DROP INDEX idx_clientno;
Instances when the Oracle engine uses an index for data extraction:
->A SELECT statement with WHERE clause specified on the column on which an index exists.
->A SELECT statement with ORDER BY clause specified on the column on which an index exists.
Instances when the Oracle engine does not use an index for data extraction:
->A SELECT statement without search criteria and order by clause.
->A SELECT statement with WHERE clause specified on the column on which an index is not defined.
->A SELECT statement with ORDER BY clause specified on the column on which an index is not defined.
PNo: 82
TECH IQ Technologies
x) CLUSTERS:
Clustering is a method of storing tables that are intimately related and often joined together into the same
area on disk.
For example, instead of the BookShelf table being in one section of the disk and the BookShelf_Author
table being somewhere else, their rows could be interleaved together in a single area, called 'CLUSTER'.
->The cluster key is the column or columns by which the tables are usually joined in a query (for example,
Title for the BookShelf and BookShelf_Author tables).
->In the above, cluster name follows the table-naming conventions, and column datatype is the name and
datatype you will use as the cluster key. The column name may be any other valid name.
For example:
--------------
create cluster BookandAuthor(col1 varchar2(100));
->The above query creates a cluster( a space is set aside, as it would be for a table) with nothing in it. The
use of 'col1' for cluster key is irrelevant; you will never use it again. However, its definition should match
the primary key of the table to be added. Next, tables are created to be included in this are:
Note: Prior to inserting rows into BookShelf1 table, you must create a cluster index:
-->It is possible to have multiple cluster keys in the 'CREATE CLUSTER' statement, and to have multiple
columns stored in those keys in the 'CREATE TABLE' statement. Notice that nowwhere does either
statement say explicitly that the 'Title' column goes into the Col1 cluster key. The match up is done by
position only: 'Col1' and 'Title' were both the first objects mentioned in their respective cluster statements.
Multiple columns and cluster keys are matched first to first, second to second, third to third and so on.
->When these two tables are clustered, each unique 'Title' actually stored only once, in the cluster key. To
each 'Title' are attached the columns from both of these tables.
->The data from both of these tables is actually stored in a single location, almost as if the cluster were a
big table containing data drawn from both of the tables that make it up.
xi) SEQUENCES:
PNo: 83
TECH IQ Technologies
Oracle provides an object called a 'SEQUENCE' that can generate numeric values. The value generated can
have a maximum of 38 digits. A sequence can be defined to
->Generate numbers in ascending or descending
->Provide intervals between numbers
->Caching of sequence numbers in memory etc.
A sequence is an independent object and can be used with any table that requires its output.
Creating Sequences:
The minimum information required for generating numbers using a sequence is:
->The starting number
->The maximum number that can be generated by a sequence
->The increment value for generating the next number.
Syntax:
CREATE SEQUENCE seq_name
[INCREMENT BY integervalue
START WITH integervalue
MAXVALUE integervalue / NOMAXVALUE
MINVALUE integervalue / NOMINVALUE
CYCLE/NOCYCLE
CACHE integervalue NOCACHE
ORDER / NOORDER]
eg:
SQL> CREATE SEQUENCE order_seq INCREMENT BY 1 START WITH 1 MINVALUE 1 MAXVALUE 999 CYCLE;
SQL> SELECT order_seq.nextval FROM dual;
NEXTVAL
----------
1
SQL> SELECT order_seq.nextval FROM dual;
NEXTVAL
----------
2
SQL> SELECT order_seq.nextval FROM dual;
NEXTVAL
----------
3
->Another example:
Insert values for orderno,orderdate,clientno in the sales_order table. The 'order_seq' which is created above can be
used here to generate orderno and orderdate must be set to system date.
SQL> SELECT order_seq.currval FROM dual;
CURRVAL
----------
4
drop table sales_order1;
CREATE TABLE SALES_ORDER1(PNO NUMBER(3),PNAME VARCHAR2(15),
QUANTITY NUMBER(4),ORDERNO VARCHAR2(8),ORDERDATE DATE,
CLIENTNO VARCHAR2(15));
PNo: 84
TECH IQ Technologies
orderdate,clientno) values(order_seq.nextval,'BOOK',17,'A03',
'03-APR-2012','C003');
SQL> select * from sales_order;
PNO PNAME QUANTITY ORDERNO ORDERDATE CLIENTN
---------- ---------- ---------- ------- --------- -------
1 CAP 4 E37 02-AUG-08 C001
2MOBILE 6 C12 06-NOV-05 C006
3 BOOK 3 B01 18-JAN-07 C002
4 13-OCT-09 C001
5 13-OCT-09 C001
ALTERING a SEQUENCE:
A sequence once created can be altered. This is achieved by using the ALTER SEQUENCE statement.
SQL> ALTER SEQUENCE order_seq INCREMENT BY 2 CACHE 30;
SQL> select order_seq.nextval from dual;
NEXTVAL
----------
7
SQL> select order_seq.nextval from dual;
NEXTVAL
----------
9
SQL> select order_seq.nextval from dual;
NEXTVAL
----------
11
->Finally the 'DROP SEQUENCE' command is used to remove the sequence from the database.
eg:
SQL> DROP SEQUENCE order_seq;
Sequence dropped.
PNo: 85
TECH IQ Technologies
Objects that are created by a user are owned and controlled by that user. If a user wishes to acces any of
the objects belonging to another user, the owner of the object will have to give permissions or such
access. This is called 'Granting of Privileges'.
Privileges once given can be taken back by the owner of the object. This is called 'Revoking of Privileges'.
Syntax for Granting and Revoking is:
-----------------------------------------------------
The Grant statement provides various types of access to database objects such as tables, views and
sequences.
Syntax:
GRANT object_privilege ON objectname
TO username;
OBJECT PRIVILEGES:
Each object privilege that granted authorizes the grantee to perform some operation on the object. The
user can grant all the privileges or grant only specific object privileges.
The list of object privileges are:
----------------------------------------
->ALTER : Allows the grantee to change the table information with the ALTER TABLE command
->DELETE : Allows the grantee to remove the records from the table with the DELETE command
->INDEX : Allows the grantee to create an index on the table with the CREATE INDEX command.
->INSERT : Allows the grantee to add records to the table with the INSERT command
->SELECT : Allows the grantee to query the table with the SELECT command
->UPDATE : Allows the grantee to modify the records in the tables with the UPDATE command.
PNo: 86
TECH IQ Technologies
In 'ORBIT' user, execute following command
---------------------------------------------------------
update system.sales_order7 set PNAME='BOOK' WHERE PNO=5;
SQL>GRANT DELETE ON SALES_ORDER7 TO orbit;
In 'ORBIT' user, execute following command
---------------------------------------------------------
DELETE FROM SYSTEM.SALES_ORDER7 WHERE PNO=3;
Example 2: Give the user 'Mita' only the permission to view and modify records in the table client_master.
Exampe 2: Take back all privileges on the table emp from SURESH
PNo: 87
TECH IQ Technologies
Syntax:
REVOKE ALL ON emp FROM SYSTEM
Example 3: AHMED has the permission to view records from STUDENT table. Take back this permission.
Note that ORBIT is the original owner of STUDENT table.
Syntax:
REVOKE SELECT ON ORBIT.STUDENT FROM AHMED;
Syntax:
REVOKE object_privilege ON objectname FROM username;
xii)ORACLE TRANSACTIONS
Transaction: A series of one or more SQL statements that are logically related, or a series of operations
performed on Oracle tabledata is termed as a Transaction.
Oracle treats this logical unit as a single entity. Oracle tratschanges to table data as a two step process.
First, the changes requested are done. To make these changes permanent a COMMIT statement has to be
given at the SQL prompt.
A ROLLBACK statement given at the SQL prompt can be used to undo a part of or the entire transaction.
Specifically, a transaction is a group of events that occurs between any of the following events:
->Connecting to Oracle
->Disconnecting from Oracle
->Committing changes to the database table.
->Rollback.
Closing Transactions:
1. COMMIT: A COMMIT ends the current transaction and makes permanent any changes made during the
transaction. All transactional locks acquired on tables are released.
Syntax:
COMMIT;
2.ROLLBACK: It does exactly the opposite of COMMIT. It ends the transaction but undoes any changes
made during the transaction. All transactional locks acquired on tables are released.
Syntax:
ROLLBACK [WORK][TO[SAVEPOINT] savepoint]
SAVEPOINT: A SAVEPOINT is used to rollback a partial transaction, as far as the specified savepoint. It
marks and saves the current point in the processing of a transaction can be undone.
An active savepoint is one that is specified since the last COMMIT or ROLLBACK.
Syntax:
SAVEPOINT savepoint-name;
->A ROLLBACK can be fired with or without SAVEPOINT.
ROLLBACK without SAVEPOINT:
->Ends the transaction.
->Undoes all the changes in the current transaction.
->Erases all savepoints in that transaction.
->Releases the transactional locks.
ROLLBACK with SAVEPOINT:
->A predetermined portion of the transaction is rolled back.
->Retains the save point rolled back to, but loses those created after named savepoint.
->Releases all transactional locks that were acquired since the savepoint was taken.
xiii)VIEWS
After a table is created and populated with data, it may become necessary to
prevent all users from accessing all columns of a table, for data security
PNo: 88
TECH IQ Technologies
reasons. This would mean creating several tables having the appropriate number of
columns and assigning requirements very well but will give rise to a great deal
of redundant (duplicate date) data being resident in tables, in the database.
To reduce redundant data to the minimum possible, Oracle allows the creation of
an object called a VIEW.
A view is mapped, to SELECT sentence. The table on which the view is based is
described in the FROM clause of the SELECT statement. The SELECT clause consists
of a sub-set of the columns of the table.
The Oracle engine treats a View just a though it was a base table. However, a
query fired on a view will run slower that a query fired on a base table.
->If a view is used to only look at table data and nothing else then that view is
called 'Read-Only View'.
->If a view is used to look at table as well as Insert, Update and Delete table
data is called an Updateable View.
Creation of views:
Syntax:
CREATE VIEW viewname AS SELECT columnname,columnname FROM
tablename WHERE columnname=expression list;
//Creating a view
CREATE VIEW V1 AS SELECT eno,ename,job,salary from emp;
SELECT * FROM V1;
PNo: 89
TECH IQ Technologies
INSERT INTO V1 VALUES(6,'NARESH','TEACHER',9785);
//Insertion is allowed
insert into vc1 values('C0006','SACHIN');
PNo: 90
TECH IQ Technologies
//Creating view
Sql>drop view vc3;
Sql>CREATE VIEW vc3 AS SELECT client_no,name,address1,
bal_due from client_master;
Example:
View created.
Syntax:
SELECT columnname,columnname FROM viewname;
eg:
UPDATEABLE VIEWS: Views on which data manipulation can be done are called
Updateable views. When you give an updateable view name in the Update, Insert or
Delete SQL statement, modifications to data will be passed to the underlying
table.
PNo: 91
TECH IQ Technologies
Views defined from Single table:
->If the user wants to INSERT records with the help of a view, then the PRIMARY
KEY column/s and all the NOT NULL columns must be included in the view.
->The user can UPDATE, DELETE records with the help of view even if the PRIMARY
KEY column and NOT NULL column/s are excluded from the definition.
View created.
->A view can be created from more than one table. For the purpose of creating the
'VIEW' these tables will be linked by a join condition specified in the where
clause of the 'VIEW's definition.
->The behaviour of the 'VIEW' will vary for 'INSERT',UPDATE, DELETE and SELECT'
table operations depending upon the following:
PNo: 92
TECH IQ Technologies
CREATE VIEW VC3 AS SELECT ENO,ENAME,D.DNO,DNAME FROM EMP E,DEPT D WHERE E.DNO =
D.DNO;
SELECT * FROM VC3;
VIEW's Defined from Multiple tables (Which have been created with a Referencing
Clause):
-----------------------------------------------------------------
->If a 'VIEW' is created from multiple tables, which were created using a
'Referencing clause' that is , logical linkage exists between the tables, then
even though the PRIMARY KEY columns as well as NOT NULL columns are included in
the 'VIEW' definition the 'VIEW's behaviour will be as follows :
*An INSERT operation is not allowed
*The DELETE or MODIFY operations do not affect the master table.
*The VIEW can be used to MODIFY the columns of the detail table included
in the view.
*If a DELETE operation is executed on the view, the corresponding records from
the detail table will be deleted.
//Primary Table
DROP TABLE DEPT;
create table dept(dno number primary key,dname varchar2(15),location
varchar2(15));
PNo: 93
TECH IQ Technologies
//Insertion is not allowed throgh a view (when view created primary and foreign
tables)
SQL> INSERT INTO V3 VALUES(6,'PRASAD','SALESMAN',9485,'MARKETING','MADRAS',20);
//Dropping a view
drop view v3;
->Suppose you are having information on departmental sale in which you want to specify TIME, REGION,
DEPARTMENT and PROFIT from table SALE. You are interested in finding out department wise sale, plus the
region wise sale and then the total sale of the year, then you can use the facility of ROLLUP. If you want to
use the ROLLUP command, you will need to use the additional clause GROUP BY ROLLUP (Time, Region,
Dept). The output will display the department wise sale and then it will ROLLUP to the region. ROLLUP
means it will find out the total sale of the region.
->Suppose the third row in a table gives the total sale for region Central. After finding out the total sale for
each region, if we wish to find the total sale for the year 2010, we write another query. The same thing can
be repeated for the year 2011, and this becomes tiring. But, using the ROLLUP facility you can have the
aggregation in N dimensions without using additional queries.
PNo: 94
TECH IQ Technologies
SQL> SELECT year, REGION, DEPT, SUM(PROFIT) AS PROFIT FROM SALES GROUP BY year, REGION, DEPT;
->In the above query, the rows are produced by using 'GROUP BY' , but without using ROLLUP. The output
contains regular aggregation rows that would be produced by GROUP BY without using ROLLUP.
Therefore, you are having rows, which are having the same values of year, region and department.
Using ROLLUP
-----------------
SELECT year, Region, Dept, SUM(Profit) AS Profit FROM sales
GROUP BY ROLLUP(year,region,dept);
->ROLLUP produces rows, which give subtotals of aggregation across departments for each combination of
time and region. So you will have rows, like 2010, central region; 2010, eastern region.
->After producing the second-level subtotals of aggregation across region, department for each
combination with time, you will have rows for 2010, a2011. After aggregation of the second-level
subtotals, it will produce the grand total row. So the output contains the following:
*First-level subtotals aggregating across Department for each combination of Time and Region.
PNo: 95
TECH IQ Technologies
*Second-level subtotals aggregating across Region and Department for each Time value.
It indicates that the ROLLUP is specified as Region and Department. It will produce aggregation of Region
and Department sales for each value of time. So it will produce rows as 2010, central region, etc. Since no
ROLLUP is specified for the Time, you will not have the total aggregation of rows as a grand total row,
which was present earlier.
Example:
SELECT year, Region, Dept, SUM(Profit) AS Profit FROM sales
GROUP BY year, ROLLUP(Region, Dept);
20 rows selected.
PNo: 96
TECH IQ Technologies
Understanding CUBE:
-------------------------
->The CUBE function is use to generate subtotals for all combinations of the values in the GROUP BY
clause.
-> CUBE is used when you are interested infinding out aggregation of multiple dimensions or multiple
combination. Suppose we have a table containing TIME,REGION and DEPARTMENT and we want to find out
the total sale for the year 2010, or the table pen sales, or the total pen sales in the central region for all
time. That means we are interested in combinations of multiple dimensions. In such cases, cubes are very
useful. Using cube you will produce aggregations without writing multiple queries.
SELECT year,nvl(region,0) Region, Dept, SUM(Profit) AS Profit FROM sales GROUP BY CUBE(year, Region,
Dept);
PNo: 97
TECH IQ Technologies
i. SQL does not have any procedural capabilities i.e. SQL does not provide the programming techniques of
conditional checking, looping and branching that is vital for data testing before storage.
ii. SQL statements are passed to the Oracle Engine one at a time. Each time an SQL statement is executed,
a call is made to the engine's resources. This adds to the traffic on the network, thereby decreasing the
speed of data processing, especially in a multi-user environment.
iii. While processing an SQL sentence if an error occurs, the Oracle engine displays its own error messages.
SQL has no facility for programmed handling of eerors that arise during manipulation of data.
With blocks, we can group logically related declarations and statements. The declarations are local in state
and cease to exist when the block completes. PL/SQL blocks can appear any where that SQL blocks can
appear.
PL/SQL fully supports ANSI/ISO SQL data manipulation language commands and SQL datatypes. Complex
data is easily handled with PL/SQL's Boolean and Composite datatypes.
PL/SQL is processed by its own PL/SQL engine. This engine is incorporated into the following oracle
products.
• Oracle server with Procedural option
• SQL*Menus
• SQL*Forms
• SQL*Reports
• SQL*Graphics
PL/SQL is a complete transaction processing language that provides the following advantages.
• PL/SQL improves server performance by reducing the number of calls from the application to Oracle.
• The application can pass numerous SQL statements to Oracle at once, which reduces the network traffic
throughout.
• All PL/SQL code is portable to any operating system and platform, on which Oracle runs.
• Recompilations are minimized because packages don't need to be recompiled, if we redefine procedures
within the package.
• Disk I/O is reduced because related functions and procedures are stored together.
• PL/SQL enables conditional, iterative, and sequential control structures, thereby providing tremendous
programming flexibility.
• Modularity is promoted because PL/SQL lets us break an application down into manageable, well-defined
logic modules.
PNo: 98
TECH IQ Technologies
• Errors are easily detected and handled.
Without PL/SQL, the Oracle server must process each SQL statement individually. Each statement results
in high performance overhead due to the additional call to be made for each statement.
With PL/SQL, an entire block of statements can be send to Oracle at one time. This reduces the network
traffic between our application and the Oracle server. PL/SQL can also add procedural processing power to
Oracle tools, such as Developer 2000 to improve performance.
PL/SQL blocks:
-----------------
PL/SQL is a block structured language with procedural and error handling capabilities. These blocks are
composed of procedures, functions and anonymous blocks that are logically grouped together to solve a
specific problem.
PL/SQL basics:
-----------------
Comments:
-------------
The PL/SQL compiler ignores comments. We use comments to describe the purpose and use of each code
segment. PL/SQL supports two comment styles:
- Single-line comments: -- (double hyphen)
- Multi-line comments: /* */ (slash asterick and asterick slash)
Characterset:
---------------
• Upper and lower case letters A .. Z, a .. z
• Numerals 0 .. 9 and
• Symbols
Note: PL/SQL is not case-sensitive, so lowercase letters are equivalent to corresponding uppercase letters
except within string and character literals.
Datatypes (PL/SQL):
----------------------
Every constant and variable has a datatype, which specifies a storage format, constraints, and valid range
of values.
Note: PL/SQL supports all the SQL data types and more..
Attributes:
------------
PNo: 99
TECH IQ Technologies
1. %TYPE Attribute:
The %TYPE attribute provides the datatype of a variable, constant, or database column.
It is particularly useful when declaring variables that refer to database columns.
2. %ROWTYPE Attribute:
The %ROWTYPE attribute provides a record type that represents a row in a table (or view). The record can
store an entire row of data selected from the table or fetched by a cursor.
With blocks, we can group logically related declarations and statements. The declarations are local in state
and cease to exist when the block completes. PL/SQL blocks can appear any where that SQL blocks can
appear.
PL/SQL fully supports ANSI/ISO SQL data manipulation language commands and SQL datatypes. Complex
data is easily handled with PL/SQL's Boolean and Composite datatypes.
PL/SQL is processed by its own PL/SQL engine. This engine is incorporated into the following oracle
products.
• Oracle server with Procedural option
• SQL*Menus
• SQL*Forms
• SQL*Reports
• SQL*Graphics
PL/SQL is a complete transaction processing language that provides the following advantages.
• PL/SQL improves server performance by reducing the number of calls from the application to Oracle.
•PL/SQL is development tool that not only supports SQL data manipulation but also provides facilities of
conditional checking, branching and looping.
• The application can pass numerous SQL statements to Oracle at once, which reduces the network traffic
throughout.
• All PL/SQL code is portable to any operating system and platform, on which Oracle runs.
• Recompilations are minimized because packages don't need to be recompiled, if we redefine procedures
within the package.
• Disk I/O is reduced because related functions and procedures are stored together.
• PL/SQL enables conditional, iterative, and sequential control structures, thereby providing tremendous
programming flexibility.
• Modularity is promoted because PL/SQL lets us break an application down into manageable, well-defined
logic modules.
Without PL/SQL, the Oracle server must process each SQL statement individually. Each statement results
in high performance overhead due to the additional call to be made for each statement.
PNo: 100
TECH IQ Technologies
With PL/SQL, an entire block of statements can be send to Oracle at one time. This reduces the network
traffic between our application and the Oracle server. PL/SQL can also add procedural processing power to
Oracle tools, such as Developer 2000 to improve performance.
PL/SQL blocks:
-----------------
PL/SQL is a block structured language with procedural and error handling capabilities. These blocks are
composed of procedures, functions and anonymous blocks that are logically grouped together to solve a
specific problem.
DECLARE
Declarations of Memory
Variables, constants, cursors,
etc. in PL/SQL.
BEGIN
SQL executable statements PL/SQL
Executable statements.
EXCEPTION
SQL or PL/SQL code to handle errors that may arise
during the execution of the code block between BEGIN
and EXCEPTION section.
END;
PL/SQL basics:
-----------------
Comments:
PL/SQL Block structure
-------------
The PL/SQL compiler ignores comments. We use comments to describe the purpose and use of each code
segment. PL/SQL supports two comment styles:
- Single-line comments: -- (double hyphen)
- Multi-line comments: /* */ (slash asterick and asterick slash)
Characterset:
---------------
• Upper and lower case letters A .. Z, a .. z
• Numerals 0 .. 9 and
• Symbols
PNo: 101
TECH IQ Technologies
Note: PL/SQL is not case-sensitive, so lowercase letters are equivalent to corresponding uppercase letters
except within string and character literals.
Datatypes (PL/SQL):
----------------------
Every constant and variable has a datatype, which specifies a storage format, constraints, and valid range
of values.
Note: PL/SQL supports all the SQL data types and more..
Attributes:
------------
1. %TYPE Attribute:
The %TYPE attribute provides the datatype of a variable, constant, or database column.
It is particularly useful when declaring variables that refer to database columns.
2. %ROWTYPE Attribute:
The %ROWTYPE attribute provides a record type that represents a row in a table (or view). The record can
store an entire row of data selected from the table or fetched by a cursor.
DBMS_OUTPUT is a package that includes a number of procedure and functions that accumulate
information in a buffer so that it can be retrieved later. These functions can also be used to
display messages to the user.
PUT_LINE: Put a piece of information in the package buffer followed by an end-of-line marker. It
can also be used to display message to the user. ‘Put_line’ expects a single parameter of
character data type. If used to display a message ‘string’.
->To display messages to the user the SERVEROUTPUT should be set to ON.
->SERVEROUTPUT is a SQL*PLUS environment parameter that displays the information passed
as a parameter to the PUT_LINE function.
Syntax:
SET SERVEROUTPUT[ON/OFF]
Step 1:
ed aa [then press enter key] [or you can give any name]
PNo: 102
TECH IQ Technologies
a number(3):=&a;
b number(3):=&b;
c number(4);
begin
c:= a+b;
dbms_output.put_line('The sum ='||c);
end;
/*
--After typing the entire code then click on FILE & SAVE then EXIT
SQL> run aa
1
2 a number(3):=&a;
3 b number(3):=&b;
4 c number(4);
5 begin
6 c:= a+b;
7 dbms_output.put_line('The sum ='||c);
8* end;
Enter value for a: 3
old 2: a number(3):=&a;
new 2: a number(3):=3;
Enter value for b: 4
old 3: b number(3):=&b;
new 3: b number(3):=4;
The sum =7
SQL> start aa
Enter value for a: 2
old 2: a number(3):=&a;
new 2: a number(3):=2;
Enter value for b: 3
old 3: b number(3):=&b;
new 3: b number(3):=3;
The sum =5
PNo: 103
TECH IQ Technologies
add number(4);
product number(3);
average number(4,2);
begin
add:=a+b+c;
product:=a*b*c;
average:=add/3;
end;
OUTPUT:
SQL> set serveroutput on
SQL> @ a1
20 /
Enter value for a: 2
old 2: a number(3):=&a;
new 2: a number(3):=2;
Enter value for b: 3
old 3: b number(3):=&b;
new 3: b number(3):=3;
Enter value for c: 4
old 4: c number(3):=&c;
new 4: c number(3):=4;
The addition of three number is9
The multiplication of three no is24
The average of three numbers is3
declare
a number(3);
b number(2);
c number(5);
begin
a:=&a;
b:=&b;
c:=power(a,b);
PNo: 104
TECH IQ Technologies
declare
a number(3);
b number(2);
c number(5);
begin
a:=&a;
b:=&b;
c:=power(a,b);
dbms_output.put_line('The result is' ||c);
end;
OUTPUT:
SQL> @ a2
Enter value for a: 2
PNo: 105
TECH IQ Technologies
old 7: a:=&a;
new 7: a:=2;
Enter value for b: 3
old 8: b:=&b;
new 8: b:=3;
The result is8
EMPNO NUMBER(3)
ENAME VARCHAR2(12)
JOB VARCHAR2(12)
CITY VARCHAR2(12)
HIREDATE DATE
SALARY NUMBER(5)
COMM NUMBER(3)
MGR NUMBER(3)
commit;
PL/SQL CODE
declare
en number;
ena varchar2(10);
jb varchar2(10);
city varchar2(10);
PNo: 106
TECH IQ Technologies
dt date;
sal number;
c number;
m number;
del_eno number;
up_eno number;
begin
en:=&en;
ena:='&ena';
jb:='&jb';
city:='&city';
dt:='&dt';
sal:=&sal;
c:=&c;
m:=&m;
SQL> @ aa
PNo: 107
TECH IQ Technologies
old 20: up_eno:=&up_eno;
new 20: up_eno:=333;
1. PL/SQL allows the user of ‘IF’ statement to control the execution of a block of code.
Suppose the condition under the ‘IF’ is true, then the statements following the ‘IF’ will be executed.
Suppose the condition under the ‘IF’ is false, then control goes to the ELSE block and executes the
statements there.
Syntax:
IF <Condition> THEN
<action>
<action>
END IF:
Syntax:
FOR variable-name IN[REVERSE].start….end
Loop
<Action>
END Loop;
PNo: 108
TECH IQ Technologies
/*Program to find biggest of two numbers*/
declare
a number(3):=&a;
b number(3):=&b;
begin
if a>b then
dbms_output.put_line('The biggest number is' || a);
else
dbms_output.put_line('The biggest number is' || b);
end if;
end;
OUTPUT:
SQL> @ a3
Enter value for a: 6
old 2: a number(3):=&a;
new 2: a number(3):=6;
Enter value for b: 8
old 3: b number(3):=&b;
new 3: b number(3):=8;
The biggest number is8
declare
a number(3):=&a;
b number(3):=&b;
c number(4):=&c;
begin
if a>b and a>c then
dbms_output.put_line('a is greates of all threee numbers' || a);
elsif b>c and b>a then
dbms_output.put_line('b is greatest of all three numbers' || b);
else
dbms_output.put_line('c is greatest of all three numbers' || c);
end if;
end;
/
declare
a number;
begin
a:=&a;
if mod(a,2)=0 then
dbms_output.put_line(a||' is even number');
else
dbms_output.put_line(a||' is odd number');
end if;
end;
/
PNo: 109
TECH IQ Technologies
/*To find the tax on the total salary of an EMPLOYEE*/
commit;
declare
en number(3);
ena varchar2(12);
sal number;
c number;
rate number(6,2);
total number(7,2);
tax number(7,2);
begin
en:=&en;
select salary into sal from emp13 where empno=en;
select comm into c from emp13 where empno=en;
total:=sal+c;
if total<=5000 then
rate:=0.3;
dbms_output.put_line('THe tax rate is ' || (rate*100)||'%');
tax:=(total*rate);
dbms_output.put_line('Employees orginal salary is ' || sal);
dbms_output.put_line('The tax of the employee is ' || tax);
else
rate:=0.7;
dbms_output.put_line('THe tax rate is ' || (rate*100)||'%');
tax:=(total*rate);
PNo: 110
TECH IQ Technologies
dbms_output.put_line('Employees original salary is ' || sal);
dbms_output.put_line('The tax of the employee is ' || tax);
end if;
end;
/
PNo: 111
TECH IQ Technologies
/*Program to find the factorial of the given number*/
declare
x number;
i number;
fact number;
begin
x:=&x;
fact:=1;
for i in 1..x loop
fact:=fact*i;
end loop;
dbms_output.put_line('The factorial is :');
dbms_output.put_line(fact);
end;
/
/*Program to generate multiplication table*/
declare
a number;
b number;
i number;
begin
a:=&a;
for i in 1..10 loop
b:=a*i;
dbms_output.put_line(a || ' * ' || i || ' = ' || b);
end loop;
end;
/
/*Program to print numbers in reverse order*/
declare
a number;
begin
for a in REVERSE 1..10 loop
dbms_output.put_line(a);
end loop;
end;
/
iv)ORACLE TRANSACTIONS
A series of one or more SQL statements that are logically related, or a series of operations performed on Oracle table data is termed as
a 'Transaction'. Oracle treats this logical unit as a single entity. Oracle treats changes to table data as a two-step process. First, the
changes requested are done. To make these changes permanent a COMMIT statement has to be given at the a SQL prompt. A
ROLLBACK statment given at the SQL prompt can be used to undo a part of or the entire transaction.
A transaction begins with the first executable SQL statement after a commit, rollback or connection made to the Oracle engine. All
changes made to an Oracle table data via unit a transaction are made or undone at one instance.
Specifically, a transactionis a group of events that occurss between any of the follownig events:
*Connecting to Oracle
*Disconnecting from Oracle
*Committing changes to the database table
*Rollback
Closing Transaction:
-------------------------
A transaction can be closed by using either a commit or a rollback statement. By using these statements, table data can be changed or
all the changes made to the table data undone.
Using COMMIT:
PNo: 112
TECH IQ Technologies
------------------
A commit ends the current transactionand makes permanent any changes made during the transaction. All transaction locks acquired
on tables are released.
Syntax:
COMMIT;
Using ROLLBACK:
A ROLLBACK does exactly the opposite of COMMIT. It ends the transaction but undoes any changes made during the transaction.
All transactional locks acquired on tables are released.
Syntax:
------------
ROLLBACK [WORK] [TO [SAVEPOINT] savepoint]
where
WORK : is optional and is provided for ANSI compatibility.
SAVEPOINT : is optional and is used to rollback a partial transaction, as far as the specified savepoint
savepoint : is a savepoint created during the current transaction.
SAVEPOINT: It is used to rollback a partial transaction. It marks and saves the current point in the processing of a transaction. When
a SAVEPOINT is used with a ROLLBACK statement, parts of a transaction can be undone. An active SAVEPOINT is one that is
specified since the last COMMIT or ROLLBACK.
Syntax:
-----------
SAVEPOINT savepointname;
ROLLBACK can be fired from the SQL prompt with or without the SAVEPOINT clause. The implication of each is described below:
A ROLLBACK operation performed 'without' the SAVEPOINT clause amounts to the following:
*Ends the transaction
*Undoes all the changes in the current transaction
*Erases all savepoints in that transaction
*Releases the transactional locks
A ROLLBACK operation performed with the TO SAVEPOINT clause amounts to the following:
*A predetermined portion of the transaction is rolled back
*Retains the save point rolled back to, but loses those created after the named savepoint.
*Releases all transactional locks that were acquired since the savepoint was taken.
Write a PL/SQL block of code that first inserts a record in EMP77 table. Update the salaries of SALIM to 2000 and RASHEED to
3000. Then check to see that the total salary does not exceed 10000. If the total salary greater than 10000 then undo the updates made
to the salaries of SALIM and RASHEED.
TABLE: EMP
drop table emp;
PNo: 113
TECH IQ Technologies
COMMIT;
*/
declare
total_sal number(7);
begin
insert into emp values(9,'SACHIN','PRINCIPAL','MADRAS','23-JUL-2007',3000,650,150);
SAVEPOINT no_update;
if total_sal>45000 then
dbms_output.put_line('Cannot able to Increase the salary');
ROLLBACK To savepoint no_update;
ELSE
dbms_output.put_line('Record is updated as well as inserted');
end if;
commit;
end;
/
PNo: 114
TECH IQ Technologies
v)CURSOR:
The Oracle engine uses a work area for its internal processing in order to execute an SQL statement. This
work area is private to SQL's operations and is called a 'CURSOR'.
->The data that is stored in the cursor is called the 'Active Data Set'. Conceptually, the size of the cursor in
memory is the size required to hold the number of rows in the Active Data Set. The actual size however, is
determined by the Oracle engine's built in memory management capabillities and the amount of RAM
available. Oracle has a pre-defined area in main memory set aside, within cursors are opened. Hence the
cursor's size will be limited by the size of this pre-deined area.
->The values retrieved from the table are held in a cursor opened in memory on the Oracle Engine. This
data is then transferred to the client machine via the network. In order to hold this data, a cursor is opened
at the client end.
If the number of rows returned by the Oracle engine is more than the area available in the cursor opened
on the client, the cursor data and the retrieved data is swapped WINDOWS swap area and RAM under the
control of the client's operating sytem.
->When a cursor is loaded with multiple rows via a query the Oracle engine opens and maintains a 'row
pointer'. Depending on user requests to view data the row pointer will be relocated within the cursor's
Active Data Set. Additionally Oracle also maintains multiple cursor variables. The values held in these
variables indicate the status of the processing being done by the cursor.
Types of CURSOR:
------------------------
Cursor are classified depending on the circumstances under which they are opened. They are:
1. Implicit Cursor: If the Oracle Engine for its internal processing has opened a cursor they are known as
Implicit Cursors.
2. Explicit Cursor: When user opened the cursor for required processing then it is said to be 'Explicit
Cursor'.
---------------------------------------------------------------------------
Attribute Name | Description
---------------------------------------------------------------------------
%ISOPEN |:Returns TRUE if cursor is open, FALSE otherwise.
------------------| -------------------------------------------------------
%FOUND | :Returns TRUE if record was fetched |sucessfully, FALSE otherwise.
------------------ | ------------------------------------------------------
%NOTFOUND | Returns TRUE if record was not fetched successfully,FALSE otherwise
------------------| -------------------------------------------------------
%ROWCOUNT | Returns number of records processed from the cursor.
Implicit Cursor:
The Oracle Engine implicitly opens a cursor on the Server to process each SQL statement. Since the
implicit cursor is opened and managed by the Oracle engine internally, the function of reserving an area in
memory , populating this area with appropriate data, processing the data in memory area, releasing the
memory area when the processing is complete is taken care of by the Oracle engine. The resultant data is
PNo: 115
TECH IQ Technologies
then passed to the client machine via the network. A cursor is then opened inmemory on the client
machine to hold the rows returned by the Oracle engine. The number of rows held in the cursor on the
client is managed by the RAM and the WINDOWS swap area.
Implicit cursor attributes can beused to access informationa bout the status of last inser, tupdate, delete or
single-row select statements. This can be done by preceding the implicit cursor attribute with the cursor
name ( i. e SQL). The values of the cursor attributes always refer to the most recently executed SQL
statement, wherever the statement appears. If an attribute value is to be saved for later use, it must be
assigned to a(boolean) memory variable.
2. %FOUND Evaluates to TRUE, if an insert, update or delete affected one or more rows, or a single-row
select returned one or more rows. Otherwise, it evaluates to FALSE. The syntax for accessing this attribute
is SQL%FOUND.
3. %NOTFOUND Is the logical opposite of %FOUND. It evaluates to TRUE, if an insert, update or delete
affected no rows, or a single-row select returns no rows. Otherwise, it evaluaes to
FALSE. The syntax for accessing this attribute is SQL%NOTFOUNT.
4. %ROWCOUNT Returns the number of rows affected by an insert, update or delete, or select into
statement. The syntax for accessing this attribute is SQL%ROWCOUNT
/*Program on ‘CURSOR’ */
COMMIT;
PNo: 116
TECH IQ Technologies
2 SAMI DOCTOR 34952 23-MAY-08 10 DELHI 2
3 NARESH CLERKS 37832 02-JUN-06 20 HYDERABAD 4
4 AMJAD SALESMAN 84724 19-OCT-05 30 BANGLORE 1
5 SALIM SALESMAN 38944 12-APR-04 30 BOMBAY 5
6 RASHEED MANAGER 58348 29-AUG-08 40 MADRAS 3
7 PRADEEP ANALYSTS 47834 16-NOV-01 50 HYDERABAD 7
8 ZAHEER PRESIDENTS 39493 01-MAR-07 60 SHIMLA 5
9 SAMI TEACHER 25000 12-APR-04 20 DELHI 6
10 PRADEEP ENGINEER 45000 16-JUL-08 30 MADRAS 3
declare
emp_code number(4):=&emp_code;
begin
update emp33 set salary=salary+(salary*0.15) where eno=emp_code;
if SQL%FOUND then
dbms_output.put_line('Employee Record Modified Successfully');
else
dbms_output.put_line('Employee No. Does not Exist');
end if;
end;
/
OUTPUT:
SQL> @ abc
Enter value for emp_code: 3
old 2: emp_code number(4):=&emp_code;
new 2: emp_code number(4):=3;
Employee Record Modified Successfully
SQL>
PNo: 117
TECH IQ Technologies
10 PRADEEP ENGINEER 45000 16-JUL-08 30 MADRAS 3
declare
begin
update emp33 set salary=salary+3000 where city in('SHIMLA','PUNE','INDORE') and exp>7;
if SQL%NOTFOUND then
dbms_output.put_line('No. Exist with the above criteria');
else
dbms_output.put_line(' Employee Record Modified Successfully ');
end if;
end;
/
OUTPUT:
SQL> @ abc
No. Exist with the above criteria
SQL>
/*3. Example for SQL%ROWCOUNT:
The HRD manager decided to raise the salary of employees by 3000 whose job hiredate is less than 23-
jun-2015.
Write a PL/SQL block to accept the employee number and update the salary of that employee.
*/
SQL> select * from emp33;
ENO ENAME JOB SALARY HIREDATE DEPTNO CITY EXP
----- ------- ------- ---------- --------- ---------- ----- ----
1 SURESH CLERK 10000 15-SEP-06 10 DELHI 2
2 SAMI DOCTOR 34952 23-MAY-08 10 DELHI 2
3 NARESH CLERKS 37832 02-JUN-06 20 HYDERABAD 4
4 AMJAD SALESMAN 84724 19-OCT-05 30 BANGLORE 1
5 SALIM SALESMAN 38944 12-APR-04 30 BOMBAY 5
6 RASHEED MANAGER 58348 29-AUG-08 40 MADRAS 3
7 PRADEEP ANALYSTS 47834 16-NOV-01 50 HYDERABAD 7
8 ZAHEER PRESIDENTS 39493 01-MAR-07 60 SHIMLA 5
9 SAMI TEACHER 25000 12-APR-04 20 DELHI 6
10 PRADEEP ENGINEER 45000 16-JUL-08 30 MADRAS 3
declare
rows_affected char(4);
begin
update emp33 set salary=salary+3000 where HIREDATE<'23-JUN-2015';
rows_affected:=to_char(sql%rowcount);
if SQL%ROWCOUNT >0 then
dbms_output.put_line(rows_affected || 'Employee Record Modified Successfully ');
else
dbms_output.put_line('No. employee Exist with the above criteria ');
end if;
end;
/
OUTPUT:
SQL> ed abc
SQL> @ abc
3 Employee Record Modified Successfully
PNo: 118
TECH IQ Technologies
Explicit Cursor:
When individual records in a table have to be processed inside a PL/SQL code block a cursor is used. This
cursor will be declared and mapped to an SQL query in the 'Declare' section of the PL/SQL block and used
within the Executable section. A cursor thus created and used is known as an Explicit Cursor.
*Declare a cursor mapped to a SQL select statement that retrieves data or processing.
*Open the Cursor
*Fetch data from the cursor one row at a time into memory variables.
*Process the data held in the memory variables as required using a loop.
*Exit from the loop after processing is complete.
*Close the cursor.
Cursor Declaration:
A cursor is defined in the declarative part of a PL/SQL block. This is done by naming the cursor and
mapping it to a query. When a cursor is declared, the Oracle engine is informed that a cursor of the said
name needs to be opened. The declaration is only an intimation. There is no memory allocation at this
point in time. The three commands used to control the cursor subsequently are OPEN, FETCH and CLOSE.
->A FETCH statement then moves the data held in the Active Data Set into memory variables. Data held in
the memory variables can be processed as desired.
->The FETCH statementis placed inside a Loop ... End Loop construct, which causes the data bo be fetched
into the memory variables and processed until all the rows in the Active Data Set are processed. The
FETCH loop then exits. The exiting of the fetch loop is user controlled.
->After the FETCH loop exits, the cursor must be closed with the CLOSE statement. This will release the
memory occupied by the cursor and its Active Data Set. A PL/SQL block is necessary to declare a cursor
and create an Active Data Set. The cursor name is used to reference the Active Data Set.
Syntax:
----------
CURSOR cursorname IS
SQL Select statement;
Opening a Cursor:
-----------------------
Opening a Cursor executes the query and creates the active set that contains all rows, which meet the
query search criteria. An open statement retrieves records from a database table and places the records in
the cursor (i.e named private SQL area in memory). A cursor is opened in the Server's memory.
Syntax:
---------
OPEN cursorname;
PNo: 119
TECH IQ Technologies
Fetching a record from the Cursor:
-----------------------------------------
The fetch statement retrieves the rows from the active set opened in the Server into memory variables
declared in the PL/SQL code block on the client one row ata atime. The memory variables are opened on
the client machine. Each time a FETCH is executed, the cursor pointer is advanced to the next row in the
Active Data Set
A standard loop structure (Loop-End Loop) is used to fetch records from the cursor into memory variables
one row at a time.
Syntax:
----------
FETCH cursorname INTO variable1, variable2....;
Closing a Cursor:
--------------------
The CLOSE statement disables the cursor and the active set becomes undefined. This will release the
memory occupied by the cursor and its Data Set both on the client and on the Server.
Syntax:
---------------
CLOSE cursorname;
2. %FOUND Evaluates to TRUE, if the last fetch succeeded because a row was available; ro to FALSE, if
the last fetch failed because no more rows were available. The syntax for accessing this attribute is
cursorname%FOUND.
3. %NOTFOUND Is the logical opposite of %FOUND. It evaluates to TRUE, if the last fetch has failed
because no more rows were available; or to FALSE, if the last fetch returned a row. The syntax for
accessing this attribute is cursorname%NOTFOUND.
4. %ROWCOUNT Returns the number of rows fetched from the active set. It is set to zero when the cursor
is opened. The syntax for accessing this attribute is cursorname%ROWCOUNT.
PNo: 120
TECH IQ Technologies
Table: EMP_RAISE
/*5. The HRD manager has decided to raise the salary for all the employees in department number 20 by
15%. Whenever any such raise is given to the employees, a record for the same is maintained in the
emp_raise table. It includes the employee number, the date when the raise was given and the actual raise.
Write a PL/SQL block to update the salary of each employee and insert a record in the emp_raise table.*/
//pl/sql program
declare
begin
OPEN C_EMP;
if c_emp%ISOPEN then
loop
FETCH C_EMP into emp_code,salary;
exit when C_EMP%NOTFOUND;
update emp33 SET salary=salary+(salary*1.15) where eno=emp_code;
insert into emp_raise values(emp_code,sysdate,salary*1.15);
end loop;
commit;
close C_EMP;
else
dbms_output.put_line('Unable to open Cursor');
end if;
end;
OUTPUTZ:
SQL> drop table EMP_RAISE;
SQL>
//6. Write an explicit cursor ‘%FOUND’ to print details of all those employees getting highest salary in
descending order for starting 3 employees.
drop table emp;
create table emp(eno number(5),fname varchar2(15),lname varchar2(15),salary number(7));
insert into emp values(1,'Sachin','Tendulkar',6978);
insert into emp values(2,'Rahul','Dravid',8475);
PNo: 121
TECH IQ Technologies
insert into emp values(3,'Lateef','Khan',7948);
insert into emp values(4,'Sandeep','Patil',8899);
insert into emp values(5,'Anil','Kumble',9987);
insert into emp values(6,'Junaid','Khan',7795);
//pl/sql program
DECLARE
CURSOR c_high_sal IS SELECT *
FROM (SELECT eno,fname,lname,salary FROM emp ORDER BY salary DESC) WHERE ROWNUM < 4;
high_sal c_high_sal%ROWTYPE;
BEGIN
IF NOT c_high_sal%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE('Cursor is Closed');
END IF;
OPEN c_high_sal;
IF c_high_sal%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE('Cursor is open');
END IF;
LOOP
FETCH c_high_sal INTO high_sal;
IF c_high_sal%FOUND THEN
DBMS_OUTPUT.PUT_LINE(high_sal.eno||' '||high_sal.fname ||' '||high_sal.lname||' '||high_sal.salary);
ELSE
EXIT; -- the same as exit when c_high_sal%NOTFOUND;
END IF;
END LOOP;
DBMS_OUTPUT.PUT_LINE(' Number of rows fetched : '||c_high_sal%ROWCOUNT);
CLOSE c_high_sal;
/*The HRD manager has decided to raise the salary for all the employees in department number 20 by
0.05. Whenever any such raise is given to the employees, a record for the same is maintained in the
emp_raise table. It includes the employee number, the date when the raise was given and the actual raise.
Write a PL/SQL block to update the salary of each employee and insert a record in the emp_raise table.*/
PNo: 122
TECH IQ Technologies
3 AMJAD 7838 10
4 AHMED 11492 20
5 ZAHEER 9744 20
7 MAJEED 11473 10
8 JUNAID 6748 10
7 rows selected.
SQL>
SQL> delete from emp_raise;
3 rows deleted.
declare
CURSOR c_emp IS SELECT eno, salary from emp33 where deptno=20;
str_eno emp33.eno%type;
num_sal emp33.salary%type;
begin
OPEN c_emp;
if c_emp%ISOPEN then
LOOP
FETCH c_emp INTO str_eno,num_sal;
exit when c_emp%NOTFOUND;
update emp33 set salary=num_sal+(num_sal*0.05) where eno=str_eno;
OUTPUT:
select eno,ename,salary,deptno from emp33;
7 rows selected.
PNo: 123
TECH IQ Technologies
declare
rows_affected char(4);
begin
update emp33 set salary=salary*1.15 where job='DOCTOR';
rows_affected:=to_char(sql%rowcount);
if SQL%ROWCOUNT>0 then
dbms_output.put_line(rows_affected || 'Employee Records exist');
else
dbms_output.put_line('There are no employees working as DOCTOR');
end if;
end;
/
OUTPUT:
SQL> @ abc
2 Employee Records exist
A cursor FOR loop implicitly declares its loop index as a %ROWTYPE record, opens a cursor, repeatedly
fetches rows of values from the activeset into fields in the record, and closes the cursor when all rows have
been processed. This is an example of a machine defined loop exit i.e. when all the values in the FOR
construct are exhausted looping stops.
Syntax:
-----------
FOR memory variable IN cursorname
->Here, the verb FOR automatically creates the memory variable of the %rowtype. Each record in the
opened cursor becomes a value for the memory variable of the %rowtype.
->The FOR verb ensures that a row from the cursor is loaded in the declared memory variable and the loop
executes once. This goes on until all the rows of the cursor have been loaded into the memory variable.
After this the loop stops.
->Cursor can be closed even when an 'exit' or a 'goto' statement is used to leave the loop prematurely, or
if an 'exception' is raised inside the loop.
/*9.The HRD manager has decided to raise the salary for all the employees in department number 20 by
0.05. Whenever any such raise is given to the employees, a record for the same is maintained in the
PNo: 124
TECH IQ Technologies
emp_raise table. It includes the employee number, the date when the raise was given and the actual raise.
Write a PL/SQL block to update the salary of each employee and insert a record in the emp_raise table.*/
begin
/*Use of a cursor FOR loop*/
FOR emp_rec in c_emp LOOP
/*Updation of the salaries (raise by 0.05%) and insertino of each record into the new table keeping track of
the date of change of salary and the raise in salary*/
end loop;
commit;
end;
/
OUTPUT:
PNo: 125
TECH IQ Technologies
/*
PARAMETERIZED CURSORS:
---------------------------------
Till now, all the cursors that have been declared and used fetch a pre-determined set of records. Records,
which satisfy conditions, set int where condition of the SELECT statement mapped to the cursor. In other
words, the criteria on which the Active Data set is determined is hard coded and never changes.
->Commercial applications require that the query, which, defines the cursor, be generic and the data that
is retrieved from the table be allowed to change accroding to need.
->Oracle recognizes this and permits the creation of a parameterized cursor prior opening. Hence the
contents of the cursor will constantly change depeding upon a value passed.
->Since the cursor accepts values or Parameters it is called as Parameterized Cursor. The parameters can
be either a constant or a variable.
PNo: 126
TECH IQ Technologies
Insert into Item_Transaction values(4,'BOOK',10);
Insert into Item_Transaction values(5,'WATCH',16);
Insert into Item_Transaction values(6,'KEYBOARD',13);
Insert into Item_Transaction values(7,'RAM',8);
Commit;
DECLARE
CURSOR c_item_tran IS
SELECT itemid,description,quantity from ITEM_TRANSACTION;
/*Cursor c_itemchk accepts the value of itemid from the current row of cursor c_item_tran*/
mast_ins_uptd number(4);
BEGIN
/*Open c_item_tran cursor*/
OPEN c_item_tran;
LOOP
/*Fetch the records from the c_item_tran cursor*/
FETCH c_item_tran INTO itemidno,descrip,quantity;
EXIT WHEN c_item_tran%NOTFOUND;
/*If the record is found then update quantity else insert a record in the item_master table*/
IF c_itemchk%FOUND THEN
update ITEM_MASTER set Bal_Stock=Bal_Stock+Quantity WHERE itemid=itemidno;
dbms_output.put_line('Return value is ' || mast_ins_uptd);
ELSE
PNo: 127
TECH IQ Technologies
INSERT INTO Item_Master (itemid,description,Bal_Stock) VALUES (itemidno,descrip,quantity);
dbms_output.put_line('Return value is ' || mast_ins_uptd);
END IF;
CLOSE c_itemchk;
END LOOP;
CLOSE c_item_tran;
COMMIT;
END;
OUTPUT:
PL/SQL procedure successfully completed.
SQL> select * from item_transaction;
These transactions (whether SQT or MQT) access an Oracle table or tables. Since Oracle works on a multi-
user platorm, it is more than likely that several people will access data either for viewing or for
manipulating (insertin,upating and deleting records) from the same tables at the sme time via different
SQL statements. The Oracle table is thereore a global resource, i.e it is shared by several users.
Tables (i.,e. global resource) contain valuable data on which business decisions are based. There is a
definite need to ensure the integrity of data in a table is maintained each time that its data is accessed.
The Oracle Engine has to allow simultanesous access to table data wihout causing damage to the data.
The technique employed by the Oracle engine to protect table data when several people are accessing it is
called 'Concurrency Control'.
PNo: 128
TECH IQ Technologies
Oracle uses a method called 'LOCKING' to implement concurrency control when multiple users access a
table manipulate its data at the same time.
LOCKS:
Locks are mechanism used to ensure data integrity while allowing maximum concurrent access to data.
Oracle's locking is fully automatic and requires no user intervention. The Oracle engine automatically locks
table data while executing SQL statements. This type of locking is called 'IMPLICIT LOCKING'.
I. TYPES OF LOCKS: The type of lock to be placed on a resource depends on the operation being
performed on that resource.
Operations can be of two type:-
->Read Operation: SELECT statements
->Write Operation: INSERT, UPDATE, DELETE statements.
2. Exclusive Locks:
----------------------
a). Exclusive locks are placed on resources whenever 'Write' operations(INSERT, UPDATE and DELETE) are
performed.
b). Only one exclusive lock can be placed on a resource at a time i.e. the first user acquires an exclusive
lock will continue to have the sole ownership of the resource, and no other user can acquire an exclusive
lock on that resource.
Automatic application of locks on resources by the Oracle engine results in a high degree of data
consistency.
It would mean that more than oneuser can be working on a single record in a table i.e. each on a diffferent
field of the same record in the same table.
"Oracle does not provide a field level lock".
-> If the WHERE clause evaluates to only one row in the table, a row level lock is used.
-> If the WHERE clause evaluates to a set of data, a 'PAGE' level lock is used.
-> If there is no WHERE clause (entire table) a table level lock is used.
Although the Oracle engine, has adefault locking strategy in commercial application, explicit user defined
locking is often required.
PNo: 129
TECH IQ Technologies
-----------------------------------------
If two client computers (Client A and Client B) are entering sales orders, each time a sales-order is
prepared the qty on hand of the product for which the order is being generated needs to be updated in
the Product_Master table.
Now, if Client A fires an update command on a record in the Product_Master table, then Oracle will
implicitly lock the record so that no futher data manipulation can be done by any other user till the lock is
released. The lock will be released only when Client A fires a commit or rollback.
In the meantime, if Client B triees to view the same record, the Oracle engine will display the old set for
the record as the transaction for that record has not been completed by client A . This leads to wrong
information being displayed to Client B.
In such cases, Client A must explicitly lock the record such that, no other user can access the record even
for viewing purposes till Client A's transaction is completed.
Explicit Locking:
--------------------
The technique of lock taken on a table or its resources by a user is called Explicit Locking.
Oracle provides facilities by which the default locking strategy can be overriden.
Tables or rows can be explicitly locked by using either the 'select ...for update' statement or 'lock table'
statement.
Example:
i. Two client machines Client A and Client B are generating client_master simultaneously.
ii. Client A fires the following select statement
client A:
select * from client_master where cno=3 FOR UPDATE;
When the above select statement is fired, the Oracle engine locks the record '3' in client_master. This lock
is released when a commit or rollback is fired by client A.
client B:
select * from client_master where cno=3 FOR UPDATE;
Note: The client B has to wait till client A is done with either 'commit' or 'rollback'.
In order to avoid unnecessary waiting time, a 'NOWAIT' option can be used to inform the Oracle engine to
terminate the SQL statement if the record has already been locked. If htis happens the Oracle engine
terminates the running DML and comes up with a message indicating that the resource is busy.
If Client B fires the following select statement now with a NOWAIT clause.
PNo: 130
TECH IQ Technologies
OUTPUT:
---------
Since Client A has already locked the record O00001 when Client B tries to acquire a shared lock on the
same record the Oracle Engine displays the following message:
IN : decides what other locks on th same resource can exist simultaneously. For example, if there is
exclusive lock on the tale no user can update rows in the table. It can have any of the following values:
Exclusive : They allow query on the locked resource but prohibit any other
activity.
Share : It allows queries but prohibits updates to a table.
Row Exclusive: Row exclusive locks are the same as row share locks, also prohibit
locking in shared mode. These locks are acquired when updating, inserting or
deleting.
NOWAIT : Indicates that the Oracle engine should immediately return to the user with a
message, if the resources are busy. If omitted, the Oracle engine will wait till resources are available
forever.
PNo: 131
TECH IQ Technologies
Example On Locks:
Explicit Locking using SQL and the Behavior of the Oracle Engine:
The locking characteristics for the INSERT, UPDATE, DELETE SQL statements in a multi user environment
where real time processing takes place, is explained by taking an example of two client computers (Client
A and Client B in our example).
COMMIT;
SQL> select * from emp;
PNo: 132
TECH IQ Technologies
->Client A has locked the table in exclusive mode
CLIENT A:
-------------
SQL> LOCK TABLE EMP IN EXCLUSIVE MODE NOWAIT;
Table(s) Locked.
Inferences:
--------------
*When Client A locks the table EMP in exclusive mode the table is available only for querying to other
users. No other data manipulation (i.e. Insert, Update and Delete operation) can be performed on the EMP
table by other users.
*Since Client A has inserted a record in the EMP table and not committed the changes when Client B fires a
select statement the newly inserted record is not visible to Client B.
*As the EMP table has been locked when Client B tries to insert a record, the system enters into an
indefinite wait period till all locks are released by Client A taken on EMP table.
Releasing Locks:
PNo: 133
TECH IQ Technologies
---------------------
Locks are released under the following circumstances:
*The transaction is committed successfully using the 'Commit' verb.
*A ROLLBACK is performed
*A ROLLBACK to a SAVEPOINT will release locks set after the specified SAVEPOINT.
An UPDATE Operation:
-------------------------------
Focus:To check the behavior of the Oracle Engine in multi-user environment when an UPDATE operation is
performed.
1. In a scenario, where
* Client A performs an UPDATE operation on EMPNO=7 in the EMP table.
SQL> select empno,ename,job,sal,hiredate from emp;
EMPNO ENAME JOB SAL HIREDATE
---------- ------------ -------------- ---------- ---------
1 SAMI DOCTOR 36700 23-MAY-08
2 SURESH CLERKS 37832 02-JUN-06
3 AMJAD SALESMAN 84724 19-OCT-05
4 SALIM SALESMAN 38944 12-APR-04
5 RASHEED MANAGERS 58348 29-AUG-08
6 PRADEEP ANALYSTS 47834 16-NOV-01
44 SURESH DOCTOR 5000 12-OCT-05
55 SURESH DOCTOR 5000 12-OCT-05
7 ZAHEER ENGINEER 5000 02-APR-08
SQL> update emp set salary=salary+7000 where empno=7;
After Updation Operation, Data in Client A
--------------------------------------------------------
SQL> SELECT EMPNO,ENAME,JOB,SAL,HIREDATE FROM EMP;
EMPNO ENAME JOB SAL HIREDATE
---------- ------------ -------------- ---------- ---------
1 SAMI DOCTOR 36700 23-MAY-08
2 SURESH CLERKS 37832 02-JUN-06
3 AMJAD SALESMAN 84724 19-OCT-05
4 SALIM SALESMAN 38944 12-APR-04
5 RASHEED MANAGERS 58348 29-AUG-08
6 PRADEEP ANALYSTS 47834 16-NOV-01
44 SURESH DOCTOR 5000 12-OCT-05
55 SURESH DOCTOR 5000 12-OCT-05
7 ZAHEER ENGINEER 12000 02-APR-08
*Client B fires a select statement on the EMP table
Syntax:
---------
SQL> SELECT EMPNO,ENAME,JOB,SAL,HIREDATE FROM EMP;
output:
---------
EMPNO ENAME JOB SAL HIREDATE
---------- ------------ -------------- ---------- ---------
1 SAMI DOCTOR 36700 23-MAY-08
2 SURESH CLERKS 37832 02-JUN-06
3 AMJAD SALESMAN 84724 19-OCT-05
4 SALIM SALESMAN 38944 12-APR-04
5 RASHEED MANAGERS 58348 29-AUG-08
6 PRADEEP ANALYSTS 47834 16-NOV-01
44 SURESH DOCTOR 5000 12-OCT-05
55 SURESH DOCTOR 5000 12-OCT-05
7 ZAHEER ENGINEER 5000 02-APR-08
PNo: 134
TECH IQ Technologies
Observation:
----------------
*Client A can see the changes made to the record EMPNO=7 that was updated.
*Client B continues to see the old values of the updated record, as CLient A has not committed the
transaction.
Inferences:
--------------
->Client A has updated the record EMPNO=7 and not committed it. Hence, when Client B fires a select
staetment, Client B cannot see the changes made to record EMPNO=7.
2. In a scenario, where
*Client A selects all the records from the EMP table with the FOR UDPATE clause.
SQL> select empno,ename,job,salary,hiredate from emp FOR UPDATE;
* Client A performs an update operation on the EMPNO=3 in the EMP table.
Syntax:
---------
SQL> update emp set salary=salary-500 where empno=3;
SQL> select empno,ename,job,sal,hiredate from emp FOR UPDATE;
OUTPUT:
------------
Client B's SQL DML enters into a wait state waiting for Client A to release the locked resource by using a
"COMMIT" or 'Rollback" statement.
Observation:
----------------
*Client A can see the changes made to the record EMPNO=3 that was updated.
*Client B fires a SELECT command with FOR UPDATE clause, Oracle enters a WAIT state till Client A
releases the locks on the EMP table.
Inferences:
--------------
*The select FOR UPDATE fired by Client A acquires an exclusive lock on the records of the EMP table.
*Client A has not committed the record EMPNO=3 that was updated.
*The select statement fired by client B tries to acquire a lock on all the records of the EMP table.
*Since these records are already locked by client A, Client B enters into a wait state.
*When Client A fires a COMMIT or ROLLBACK, all locks are released by Client A. The records are now
available to Client B for locking.
* The select statement processing executed by Client B will now be completed as Client B would be see all
the records and lock them.
3. In a scenario, where
PNo: 135
TECH IQ Technologies
*Client A selects a record from the EMP table with the FOR UPDATE clause.
Syntax:
----------
SQL> select empno,ename,job,salary,hiredate from emp FOR UPDATE;
1 row updated.
SQL> select empno,ename,job,salary,hiredate from emp FOR UPDATE;
Syntax:
---------
SQL> SELECT EMPNO,ENAME,JOB,SALary,HIREDATE FROM EMP FOR UPDATE NOWAIT;
OUTPUT:
------------
ERROR at line 1:
ORA-00054: resource busy and acquire with NOWAIT specified
Observation:
----------------
*Client A can see the changes made to the record EMPNO=5 that was updated.
*When Client B fires a select command, Oracle checks to find if the record EMPNO=5 is available for a lock to be taken.
Since the record has already been locked by Client A the Oracle engine displays an appropriate error message.
Explicit Locking using PL/SQL and the Behavior of the Oracle Engine:
-------------------------------------------------------------------------------------------
The manner in which explicit locking can be used in a PL/SQL block of code and functionality of the Oracle engine in
processing the code block in a multi-user environment is explained with the help of the following example:
Table Name: ACCOUNTS
----------------------------------
DROP TABLE ACCOUNTS;
PNo: 136
TECH IQ Technologies
ACC_ID NAME BALANCE
-------- ---------- ----------
AC001 ANUJ 5000
AC002 ROBERT 10000
AC003 MITA 5000
AC004 SUNITA 15000
AC005 MELBA 5000
Example:
--------------
Write a PL/SQL code block that will accept:
*An account number, the type of transaction, the amount involved and whether the amount to be debited to or
credited to an account number.
*The balance in the ACCOUNTS table for the corresponding account number is updated
*Before the update is fired, the record is viewed in the FOR UPDATE NOWAIT mode so that a lock can be acquired on
the record to be updated and no other user has access to the same record till the transaction is completed.
DECLARE
acct_balance number(11,2);
acct_no varchar2(8);
trans_amt number(5);
oper char(1);
BEGIN
acct_no:='&acct_no';
trans_amt:=&trans_amt;
oper:='&oper';
select balance INTO acct_balance from ACCOUNTS where acc_id = acct_no FOR UPDATE NOWAIT;
If oper = 'D' THEN
update accounts set balance=balance-trans_amt where acc_id = acct_no;
elsif oper='C' THEN
update accounts set balance=balance+trans_amt where acc_id=acct_no;
End if;
End;
/
In scenario, where two users Client A and Client B are accessing the accounts table and Client A first executes the
PL/SQL block of code and enters AC001' as the ACC_ID, 2000 as the trans_amt and 'C' for oper:
->The table after PL/SQL executes successfully is shown below:
SQL> select * from accounts;
ACC_ID NAME BALANCE
-------- ---------- ----------
AC001 ANUJ 7000
AC002 ROBERT 10000
AC003 MITA 5000
AC004 SUNITA 15000
AC005 MELBA 5000
* Since Client A has not yet committed the record, the lock on the record still exists.
*Now if Client B fires the PL/SQL bolck of code for the same record 'AC001', the SELECT statement will fail to acquire
the lock as Client A already locked the record.
Since the NOWAIT clause has been specified in the SELECT sentence, the Oracle engine will come out of the PL/SQL
block and display the following message:
DECLARE
*
ERROR at line 1:
ORA-00054: resource busy and acquire with NOWAIT specified
ORA-06512: at line 13
PNo: 137
TECH IQ Technologies
Thus, by exclusively locking the row just before the UPDATE is fired in a PL/SQL block of code, concurrency control can
be maintained in a multi-user environment where multiple users would want to access the same resource at the same
time.
PNo: 138
TECH IQ Technologies
Exception Handlers:
----------------------
When an exception is raised, normal execution of the PL/SQL block or subprogram stops and control transfers to its exception
handling part.
Types of Exceptions:
• Pre-defined Exception
• Un-defined Exception
• User-defined Exception
Predefined Exceptions:
-------------------------
The Oracle server defines several errors with standard names. Although every Oracle error has a number, the errors must be
referenced by name.
Exception Error
ACCESS_INTO_NULL ORA-06530
COLLECTION_IS_NULL ORA-06531
CURSOR_ALREADY_OPEN ORA-06511
DUP_VAL_ON_INDEX ORA-00001
INVALID_CURSOR ORA-01001
INVALID_NUMBER ORA-01722
LOGIN_DENIED ORA-01017
NO_DATA_FOUND ORA-01403
NOT_LOGGED_ON ORA-01012
PROGRAM_ERROR ORA-06501
ROWTYPE_MISMATCH ORA-06504
SELF_IS_NULL ORA-30625
STORAGE_ERROR ORA-06500
SUBSCRIPT_BEYOND_COUNT ORA-06533
SUBSCRIPT_OUTSIDE_LIMIT ORA-06532
SYS_INVALID_ROWID ORA-01410
TIMEOUT_ON_RESOURCE ORA-00051
TOO_MANY_ROWS ORA-01422
VALUE_ERROR ORA-06502
ZERO_DIVIDE ORA-01476
If any of the exceptions in the list is raised, the associated sequence of statements is executed.
Eg:
DECLARE
ENO EMP.EMPNO%TYPE;
EMPREC EMP%ROWTYPE;
BEGIN
ENO:= &ENO;
SELECT INTO EMPREC FROM EMP WHERE EMPNO:=ENO;
DBMS_OUTPUT.PUT_LINE('NUMBER : ' || EMPREC.EMPNO);
DBMS_OUTPUT.PUT_LINE(‘NAME : ' || EMPREC.ENAME);
DBMS_OUTPUT.PUT_LINE(‘JOB : ' || EMPREC.JOB);
EXCEPTION WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('NO DATA FOUND');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('MANY ROWS FOUND');
END;
-------------------------------------------------------------------------------
Un-defined Exceptions:
The OTHERS exception used as a catch all error. OTHERS is normally used when the exact nature of the exception isn't important or
when the exception is unnamed.
Another way to handle an unnamed error is with the pragma exception_init compiler directive. This directive simply transfers
information to the compiler. The pragma statement tells the compiler to associate an exception name with an Oracle error number.
This enables us to refer to any internal exception by name and to write a specific handler for it.
The declaration of the pragma exception_init statement must appear in the declarative portion of the PL/SQL block, package, or
subprogram.
PNo: 139
TECH IQ Technologies
Syntax:
Pragma exception_init(exception_name,error_number);
Eg:
DECLARE
INSUFFICIENT_FUNDS EXCEPTION;
PRAGMA EXCEPTION_INIT(INSUFFICIENT_FUNDS,-2020);
BEGIN
EXCEPTION
WHEN INSUFFICIENT_FUNDS THEN
ROLLBACK;
END;
User-defined Exceptions:
--------------------------
Users can explicitly raise an exception with the RAISE command, the RAISE exception procedure should be used only when Oracle
does not raise its own exception or when processing is undesirable or impossible to complete.
RAISE statement:
-------------------
PL/SQL blocks and subprograms should RAISE an exception only when an error makes it undesirable or impossible to finish
processing. We can code a RAISE statement for a given exception anywhere within the scope of that exception.
In the following example, we alert the PL/SQL block with a user-defined exception named "OUT_OF_STOCK":
Eg:
DECLARE
OUT_OF_STOCK EXCEPTION;
NUMBER_ON_HAND NUMBER(4);
BEGIN
…
IF NUMBER_ON_HAND < 1 THEN
RAISE OUT_OF_STOCK;
END IF;
…
EXCEPTION
WHEN OUT_OF_STOCK THEN
-- Handle the Error
END;
For internal exceptions, SQLCODE returns the number of the associated Oracle error and SQLERRM returns the message associated
with the Oracle error that occurred.
Eg:
DECLARE
MSG CHAR(100);
BEGIN
FOR NUM IN 1 .. 9999 LOOP
MSG := SQLERRM(-NUM);
INSERT INTO ERRORS VALUES (MSG);
END LOOP;
END;
/*The 'sales_master' table records the salesman_no, name, comm_rate, actual_sales. The comm_amt and comm_paid_date along with
the salesman_no is calculated and recorded in comm_payable table.
PNo: 140
TECH IQ Technologies
Write a PL/SQL block of code such that depending upon the user entered salesman_no, the comm_amt is calculated
and inserted into the comm_payable table. If the user enters a salesman_no that is not the in the sales_master table,
then the PL/SQL block must display appropriate error message back to the user.
Creating Table SALESMAN_MASTER1
--------------------------------------------------
DROP TABLE SALESMAN_MASTER1;
create table salesman_master1(salesman_no varchar2(8),
salesman_name varchar2(10),rate_of_comm number(3),
target_sales number(4),actual_sales number(4));
Inserting Values In SALESMAN_MASTER1
-------------------------------------------------------
insert into salesman_master1 values('S001','KIRAN',5,100,50);
insert into salesman_master1 values('S002','MANISH',4,200,100);
insert into salesman_master1 values('S003','RAVI',3,200,100);
insert into salesman_master1 values('S004','ASHISH',7,200,150);
SQL> SELECT * FROM SALESMAN_MASTER1;
SALESMAN SALESMAN_N RATE_OF_COMM TARGET_SALES ACTUAL_SALES
-------- ---------- ------------ ------------ ------------
S001 KIRAN 5 100 50
S002 MANISH 4 200 100
S003 RAVI 3 200 100
S004 ASHISH 7 200 150
*/
DECLARE
sales_no salesman_master1.salesman_no%type;
sales_amt salesman_master1.actual_sales%type;
comm_rate salesman_master1.rate_of_comm%type;
BEGIN
SELECT salesman_no,rate_of_comm,actual_sales INTO sales_no,
comm_rate, sales_amt from salesman_master1 where salesman_no ='&sales_no';
END;
/
OUTPUT:
SQL> SELECT * FROM SALES_MASTER;
SQL> @ AB
PNo: 141
TECH IQ Technologies
14 /
Enter value for salesman_no: 3
old 6: SELECT salesman_no,comm_rate,actual_sales INTO sales_no, comm_rate, sale
_amt from sales_master where salesman_no =&salesman_no;
new 6: SELECT salesman_no,comm_rate,actual_sales INTO sales_no, comm_rate, sale
_amt from sales_master where salesman_no =3;
SQL> @ AB
14 /
Enter value for salesman_no: 7
old 6: SELECT salesman_no,comm_rate,actual_sales INTO sales_no, comm_rate, sale
_amt from sales_master where salesman_no =&salesman_no;
new 6: SELECT salesman_no,comm_rate,actual_sales INTO sales_no, comm_rate, sale
_amt from sales_master where salesman_no =7;
Salesman No is not present in the sales_master table
/*Two client machines (Client A and Client B) are accessing the same client_master table using
identical PL/SQL code blocks for updating the bal_due column of the table client_master
C0003 ABDUL SAMI WATER TANK DSNR BOMBAY MAHRASHTRA 400057 5000
PNo: 142
TECH IQ Technologies
resource_busy EXCEPTION;
PRAGMA EXCEPTION_INIT (resource_busy,-00054);
BEGIN
trans_amt:=&trans_amt;
cl_no:='&cl_no';
trans_type:='&trans_type';
SELECT bal_due INTO bal_amt FROM client_master WHERE client_no=cl_no FOR UPDATE NOWAIT;
IF trans_type='D' THEN
UPDATE client_master SET bal_due=bal_due-trans_amt WHERE client_no=cl_no;
dbms_output.put_line('For ' || cl_no ||' amount : ' ||trans_amt ||' is deduce from the account');
ELSIF trans_type='C' THEN
UPDATE client_master SET bal_due=bal_due+trans_amt WHERE client_no=cl_no;
dbms_output.put_line('For ' || cl_no ||' ' ||trans_amt ||' is added in bal_due column');
END IF;
EXCEPTION
WHEN resource_busy THEN
dbms_output.put_line('The row is in use by another user');
END;
/
BEGIN
SQL sentence;
IF <condition> THEN
RAISE <Exceptionname>;
END IF;
EXCEPTION
WHEN <Exceptionname> THEN
{User defined action to be taken};
Example:
----------------
The SALESMAN_MASTER1 table records the salesman_no, salesman_name, actual_sales, rate_of_commission along with the minimum
target_sales. A salesman is eligible for commission only when a salesman achives the target sales. When commission is paid the
commission amount along with the salesman_no and the date_of_payment is recorded in commission_payable table.
PNo: 143
TECH IQ Technologies
insert into salesman_master1 values('S003','RAVI',3,200,100);
insert into salesman_master1 values('S004','ASHISH',7,200,150);
SQL> SELECT * FROM SALESMAN_MASTER1;
SALESMAN SALESMAN_N RATE_OF_COMM TARGET_SALES ACTUAL_SALES
-------- ---------- ------------ ------------ ------------
S001 KIRAN 5 100 50
S002 MANISH 4 200 100
S003 RAVI 3 200 100
S004 ASHISH 7 200 150
Creating Table COMMISSION_PAYABLE Table:
------------------------------------------------------------
DROP TABLE COMMISSION_PAYABLE;
SQL> create table commission_payable(salesman_no varchar2(8),
date_of_payment date,comm_amount number(5));
DECLARE
less_than_target EXCEPTION;
sman_no salesman_master1.salesman_no%type;
tgt_sales salesman_master1.target_sales%type;
act_sales salesman_master1.actual_sales%type;
comm_rate salesman_master1.rate_of_comm%type;
BEGIN
sman_no:='&sman_no'; SELECT salesman_no,rate_of_comm,target_sales,actual_sales
INTO sman_no,comm_rate,tgt_sales,act_sales FROM salesman_master1 where
salesman_no=sman_no;
IF act_sales<tgt_sales THEN
RAISE less_than_target;
ELSE
INSERT INTO commission_payable values(sman_no,sysdate,act_sales*comm_rate*0.1);
dbms_output.put_line('Salesman Number ' || sman_no ||' is eligible for commission of ' ||
(act_sales*comm_rate*0.1));
END IF;
EXCEPTION
WHEN less_than_target THEN
dbms_output.put_line('Salesman No' || sman_no || 'is not entitled to get commission ' );
END;
/
PNo: 144
TECH IQ Technologies
viii)Function/Procedures:
A Procedure or Function is a logically grouped set of SQL and PL/SQL statements that perform a specific
task. A stored procedure or function is a named PL/SQL code block that have been compiled and stored in
one of the Oracle engine's system tables.
To make a procedure or function dynamic either of them can be passed parameters before execution. A
Procedure or Function can then change the way it works depending upon the parameters passed prior to
its execution.
Declarative Part:
-------------------------
The declarative part may contain the declarations of cursors, constants, variables, exceptions and
subprograms. These objects arelocal to the procedure or function. The objects become invalid once the
user exits from the procedure or the function.
Executable Part:
-------------------------
The executable part is a PL/SQL block consistaing of SQL and PL/SQL statements that assign values control
execution and manipulate data. The action that the procedure or function is expected to perform is coded
here. The data that is to be returned back to the calling environment is also returned from here. Variables
declared are put to use in this block.
2. Performance:
It improves database performance in the following ways:
*Amount of information sent over a network is less.
*No compilation step is required to execute the code.
*Once the procedure or function is present in the shared pool of the SGA retrieval from disk is not required
every time different users call the procedure or function i.e. reduction in disk i/o.
3. Memory Allocation:
The amount of memory used reduces as stored procedures or functions have shared memory capabilities.
Only one copy of procedure needs to be loaded for execution by multiple users. Once a copy of the
procedure or function is opened in the Oracle engine's memory, other users who have permissions may
access them when required.
4. Productivity:
By writing procedures and functions redundant coding can be avoided, increasing productivity.
PNo: 145
TECH IQ Technologies
5. Integrity: A procedure or function needs to be tested only once to guarantee that is returns an
accurate result. Since procedures and functinos are stored in the Oracle engine's they become a part of
the engine's resource. Hence the responsibility of maintaining their integrity rests with the Oracle engine.
The Oracle engine has high level of in-built security and hence integrity of procedures or functions can be
safely left to the Oracle engine.
*Procedure defining multiple OUT parameters in a procedure, multiple values can be passed to the caller.
The OUT variable being global by nature, its value is accessible by any PL/SQL code block including the
calling PL/SQL block.
BEGIN
PL/SQL subprogram body;
EXCEPTION
exception PL/SQL block;
END;
REPLACE: Recreates the procedure if it already exists. This option is used to change the definition of an
existing procedure without dropping, recreating and re-granting object privileges previously granted on it.
If a procedure is redefined the Oracle engine recompiles it.
schema: It is the schema to contain the procedure. The Oracle engine takes the default schema to be the
current schema, if it is omitted.
argument : It is the name of an argument to the procedure. Parentheses can be omitted if no arguments
are present
IN : Specifies that a value or the argument must be specified when calling the procedure.
OUT : Specifies that the procedure passes a value for this argument back to its calling
environment after execution.
IN OUT : Specifies that a value for the argument must be specified when calling the procedure and that the
procedure passes a value or this argument back to its calling environment after execution. By default it
takes IN.
PNo: 146
TECH IQ Technologies
--------------------------------------------------
CREATE OR REPLACE FUNCTION [schema.] functionname (argument IN data type,...)
RETURN data type {IS,AS}
variable declarations;
constant declarations;
BEGIN
PL/SQL subprogram body;
EXCEPTION
exception PL/SQL block;
END;
REPLACE: Recreates the function if it already exists. This option is used to change the definition of an
existing function without dropping, recreating and re-granting object privileges previously granted on it. If
a function is redefined the Oracle engine recompiles it.
schema: It is the schema to contain the function. The Oracle engine takes the default schema to be the
current schema, if it is omitted.
argument : It is the name of an argument to the procedure. Parentheses can be omitted if no arguments
are present
IN : Specifies that a value or the argument must be specified when calling the function.
OUT : Specifies that the function passes a value for this argument back to its calling environment after
execution.
IN OUT : Specifies that a value for the argument must be specified when calling the function and that the
procedure passes a value or this argument back to its calling environment after execution. By default it
takes IN.
PNo: 147
TECH IQ Technologies
SQL>ed fun_tot
FUN_TOT(10,20,30)
-----------------
60
declare
a number(5);
begin
a:=fun_tot(5,10,15) ;
dbms_output.put_line('Calculted value : ' || a);
end;
SQL> ed fun_avg
begin
average:=(a+b+c)/3;
return(average);
end;
/
SQL> @ fun_avg
Function created.
FUN_AVG(5,10,15)
----------------
10
PNo: 148
TECH IQ Technologies
-- Function to return the simple interest.
SQL> ed fun_si
begin
interest:=(p*r*t)/100;
return(interest);
end;
/
SQL> @ fun_si
declare
result number(7);
begin
result:=fun_si(8674,3,5);
dbms_output.put_line('Simple interest is ' || result);
end;
DOLLAR:=(48*D);
RETURN (DOLLAR);
END;
/
SQL>ed fun_gra
PNo: 149
TECH IQ Technologies
ave:=(a+b+c)/3;
SQL> @ fun_gra
Function Created
FUN_GRA(70,65,78)
----------------------------
B
//Write a PL/SQL program to find grade of a student and also insert grade into table
//Table
Drop table student;
create table student(rno number,name varchar2(15),s1 number,s2 number,s3
number,total number,avg number(5,2),grade varchar2(10));
insert into student (RNO,NAME)VALUES(1,'SAMI');
//Function
create or replace function fun_gra(rn number,nm varchar,a number, b number, c
number) return varchar is
total1 number;
grade1 char;
ave number(4,1);
begin
total1:=(a+b+c);
ave:=total1/3;
insert into student (rno,name,s1,s2,s3,total,avg)values(rn,nm,a,b,c,total1,ave);
dbms_output.put_line('Record is inserted');
if (a>=35 and b>=35 and c>=35) then
PNo: 150
TECH IQ Technologies
if (ave>=75 and ave<=100) then
grade1:='A';
update student set grade=grade1 where rno=rn;
elsif (ave>=60 and ave<75) then
grade1:='B';
update student set grade=grade1 where rno=rn;
elsif (ave>=50 and ave<60) then
grade1:='C';
update student set grade=grade1 where rno=rn;
elsif (ave>=35 and ave<50) then
grade1:='D';
update student set grade=grade1 where rno=rn;
end if;
else
grade1:='F';
update student set grade=grade1 where rno=rn;
end if;
return(grade1);
end;
/
//PL/SQL Program
declare
a char;
begin
a:=fun_gra(2,'FAISAL',92,38,98);
//Retrieve data
select * from student;
/*
Recursion: It refers to calling the same function within the subprogram again and again repeatedly.
*/
SQL> ed fact
PNo: 151
TECH IQ Technologies
end;
/
SQL> @ fact
Function created.
FACT(5)
----------
20
Write a PL/SQL block of code that would update the Bal_Stock in the 'Item_Master' table each time a
transaction takes place in the 'Item_Transaction' table. The change in the 'Item_Master' table depends on
the Itemid. If the itemid is already present in the 'Item_Master' table then an update operation is
performed to increase the Bal_Stock by the Quantity specified in the Item_Transaction' table. In case the
itemid is not present in the Item_Master table then the record is inserted into the 'Item_Master' table.
PNo: 152
TECH IQ Technologies
-----------------------------------
SQL> drop table item_master;
create table ITEM_MASTER(Itemid number(4) PRIMARY KEY,Description varchar2(20),Bal_stock number(5));
->To help simplify this process (of batch updating) a function called 'f_itemidchk' has been created. The
function checks for the existence of itemid in the table Item_Master. The function has one argument, which
receives a value. The unctionwill search for a matching value in the 'Item_Master' table when a value is
passed to it while calling it.
->The function will return value '1' indicating that a match is found and a value '0' indicating that no
match is found. This value returned by the function is used to make a decision to 'INSERT' or 'UPDATE' the
Item_Master table.
*/
dummyitem number(4);
BEGIN
SELECT itemid INTO dummyitem FROM item_master WHERE itemid=vitemidno;
RETURN 1;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN 0;
END;
/
SQL> @ f_itemidchk
Function Created
itemidno number(4);
descrip varchar2(12);
quantity number(4);
/*variable that stores the value returned by the f_itemidchk function i.e 0 or 1*/
valexists number(1);
BEGIN
OPEN scantable;
LOOP
FETCH scantable INTO itemidno,descrip,quantity;
EXIT WHEN scantable%NOTFOUND;
valexists:=f_itemidchk(itemidno);
IF valexists = 0 THEN
INSERT INTO item_master(itemid,description,bal_stock)
VALUES(itemidno,descrip,quantity);
Dbms_output.put_line(‘Record is inserted successfully for ‘ || itemidno);
PNo: 153
TECH IQ Technologies
UPDATE item_master SET bal_stock=bal_stock + quantity WHERE itemid=itemidno;
Dbms_output.put_line(‘Record is updated successfully for ‘ || itemidno);
END IF;
END LOOP;
CLOSE scantable;
COMMIT;
END;
/
When a lcient/server software is created, we observe two main parts of the software:
-->The first part represents the screens which accepts the input From the user and also display results to
the user. The program code that helps to create such screens is called 'Presentation logic'.
-->The second part represents the logic that converts the input into the output. It contains some business
procedures and calculations related to the activities of an organization, this is called 'Business logic'.
It is advisable to create presentatiion logic and business logic separately without mixing them together.
Step 2:
------- -
Write the following coding in the file
Step 3:
-------
Click on Save and Exit button
Step 4:
--------
In SQL> prompt type
Step 5:
--------
PNo: 154
TECH IQ Technologies
@ myproc or start myproc or run myproc
Step 6:
---------
exec myproc(5) from dual;
PNo: 155
TECH IQ Technologies
-- Procedure to insert the values into the table
//procedure
create or replace procedure proc_insert1(a number, b varchar, c number, d number, e number)
is
begin
insert into stud_info values(a,b,c,d,e);
commit;
end;
/
EXECUTION:
begin
proc_insert(2,'SAJID',89,93,45);
END;
PNo: 156
TECH IQ Technologies
select * from emp;
end;
/
PNo: 157
TECH IQ Technologies
OUTPUT:
SQL> @ a
Procedure created.
--create a procedure which gets the name and salary of the employee when the employee id is
passed.
PNo: 158
TECH IQ Technologies
insert into employee values(3,'JUNAID','WIPRO','DELHI',7482);
commit;
//Creating Procedure
DECLARE
A varchar(20);
B NUMBER(7);
CURSOR id_cur is SELECT eno,SALARY FROM employee;
BEGIN
FOR emp_rec in id_cur
LOOP
P1(emp_rec.eno, A,B); --calling procedure
dbms_output.put_line('The employee ' || A || ' has id ' || emp_rec.eno || ' and salary is ' || B);
END LOOP;
END;
tmp_sal number;
BEGIN
PNo: 159
TECH IQ Technologies
SELECT salary INTO tmp_sal FROM employee WHERE eno = eid;
--The below PL/SQL block shows how to execute the above 'emp_salary_increase' procedure.
DECLARE
CURSOR updated_sal is SELECT eno,salary FROM employee;
pre_sal number;
BEGIN
FOR emp_rec IN updated_sal LOOP
pre_sal := emp_rec.salary;
emp_salary_increase(emp_rec.eno, emp_rec.salary);
END;
PNo: 160
TECH IQ Technologies
Package: A package is an Oracle object, which holds other objects within it. Objects commonly held within
a package are procedures, functions, variables, constants, cursors and exceptions.
A package once written and debugged is compiled and stored in Oracle's system tables held in an Oracle
Database. All users who have execute permissions on the Oracle Database can use the package.
Packages can contain PL/SQL blocks of code, which have been written to perform some processs entirely
on their own. These PL/SQL blocks of code do not require any kind of input from other PL/SQL blocks of
code. These are the package's standalone subprorams.
Alternatively a package can contain a subprogram that requires input from another PL/SQL block to
perform its programmed processes successfully. These are also subprograms of the pacake but these
subprograms are not standalone.
Subprograms held within a package can be called from other stored programs,like triggers, precompilers,
or any other Interactive Oracle program like SQL*Plus.
Unlike the stored programs, the package itself cannot be called, passed parameters to, or nested.
Components of Package:
A package has usually twocomponents:
1. Package Specification
2. Package Body
->A package 'Specification' declares the types (variables of the record type), memory variables, constants,
exceptions, cursors, and subprograms that are available for use.
->A package's 'Body' fully defines cursors, functions, and procedures and thus implements the
specification.
Why Use Packages?
Packages offer the following advantages:
1. Packages enable the organization of commercial applications into efficient modules. Each package is
easily understood, and the interfaces between packages are simple, clear, and well defined.
2. Packages allow granting of privileges efficiently
3. A package's public variable and cursors persist for the duration of the session. Therefore all curosrs and
procedures that execute in this environment can share them.
4. Packages enable the overloading of procedures and functions when required.
5. Packages improve performance by loading multiple objects into memory at once. Therefore,
subsequently calls to related subprograms in the package require no I/O.
6. Packages promote code reuse through the use of libraries that contain stored procedures and functions,
thereby reducing redundant coding.
Package Specification:
The package specification contain datatypes, variables,exceptions, and subprogram declarations, which
are available to the user.
Thus package contains:
->Name of the package
->Names fo the datatypes of any arguments
->This declaration is local to the database and global to the package
This means that procedures, functions, variables, constants, cursors and exceptions and other objects,
declared in a package are accessible from anywhere in the package. Therefore, all the information a
package needs, to execute a stored subprogram, is contained in the package specifications itself.
PNo: 161
TECH IQ Technologies
The Package Body:
The body of the package contains the definition of public objects that are declared in the specification.
The body can also contain other object declarations that are private to the package.
The objects declared privately in the package body are not accessible to other objects outside the
package. Unlike package specification, the package body can contain subprogram bodies.
After the pacakge is written, debugged, compiled and stored in the database applications can reference
the package's types, call its subprograms, use its cursors, or raise its exceptions.
In addition to the object definitions for the declaration, the package body can also contain private
declarations, These private objects are for the internal workings of the package and are local in scope.
External PL/SQL blocks cannot reference or call internal declarations of the package.
3. Execute:
The package subprogram is executed.
To reference a package's subprograms and objects, you must use 'DOT Notation'.
->Package_name.type_name
->Package_name.object_name
->Package_name.subprogram_name
PNo: 162
TECH IQ Technologies
PACKAGE SPECIFICATION
COMMIT;
PACKAGE BODY
CREATE OR REPLACE PACKAGE BODY check_data IS
FUNCTION f_itemidchk(itemidno IN number) RETURN number IS
dummyitem number(4);
BEGIN
SELECT id into dummyitem FROM item_master WHERE id=itemidno;
RETURN 1;
EXCEPTION
WHEN no_data_found THEN
RETURN 0;
END;
BEGIN
INSERT INTO item_master (id,description,quantity)
PNo: 163
TECH IQ Technologies
values(itemidno,descrip,quantity);
END;
DECLARE
CURSOR scantable IS
SELECT itemid,description,quantity FROM item_transaction;
itemidno number(4);
descrip varchar2(30);
quantity number(5);
valexists number(1);
BEGIN
OPEN scantable;
LOOP
FETCH scantable INTO itemidno,descrip,quantity;
EXIT WHEN scantable%NOTFOUND;
valexists:=check_data.f_itemidchk(itemidno);
dbms_output.put_line(to_char(valexists));
IF valexists=0 THEN
check_data.proc_insert(itemidno,descrip,quantity);
dbms_output.put_line(‘Record is inserted’);
ELSE
check_data.proc_update(itemidno,quantity);
dbms_output.put_line(‘Record is updated’);
END IF;
END LOOP;
CLOSE scantable;
COMMIT;
END;
PNo: 164
TECH IQ Technologies
Multiple procedures that are declared with the same name are called "Overloaded Procedures" .
Similarly, multiple Functions that are declared with the same name are called "Overloaded Functions"
The code in the Overloaded functions or overloaded procedures can be same or completely different.
Example:
---------------
Create a package to check that a numeric value is greater than zero, and a date isless than or equal to
sysdate.
END;
-->Overloading can greatly simplify procedures and functions. The Overloading technique consolidates the
call interface for many similar programs into a single procedure or function. When executing the procedure
or function the Oracle engines chooses the procedure or function whose number of parameters and their
data type match the values passed by the caller.
Example:
----------------
Date_string:=TO_CHAR(sysdate,'DD/MM/YY');
Number_string:=TO_CHAR(10000,'$099,999');
Benefits of Overloading:
-------------------------------------
1. Overloading can greatly simplify the processing logic of a program by eliminating multiple IF constructs
or case constructs that would check the parameters passed and perform appropriate operations.
2. The overloading technique transfers the burden of knowledge from the developers to the software. For
example if multiple procedures with different names are written, the programmer will have to remember
the names of each of the procedures along with the parameters of each functions.
PNo: 165
TECH IQ Technologies
*Inside the declaration section of a PL/SQL
*Inside a package
***Standalone programs cannot be overloaded nor can two independent modules be created with the
same name but different parameter lists.
Example:
--------------
If an attempt is made to "create or replace" the following procedure of "revise estimates", the second
attempt will fail.
FIRST ATTEMPT:
---------------------------
CREATE PROCEDURE revise_estimates(date_in IN date) IS
BEGIN
----------
----------
END;
Procedure Created
SECOND ATTEMPT:
-------------------------------
CREATE PROCEDURE revise_estimates(dollars_in IN number) IS
BEGIN
----------
----------
END;
Because a procedure with the name used is present, PL/SQL rejected the attempt to replace it with the
procedure created in the second attempt.
Restrictions on Overloading:
------------------------------------------------
There are several restirctions on how the procedures and functions can be overloaded. The restrictions
apply since the PL/SQL engine compares overloaded modules (functions or procedure) before executing
the appropriate module.
1. The data subtype of at least one of the parameters of the overloaded function or procedure must differ
For example an overloaded procedure distinuished by parameters of different types of numeric data types
is not allowed. Similarly, an overloaded procedure distinguished by parameters with varchar2 and char
data types is not allowed.
Example:
--------------
CREATE PROCEDURE trim_and_center(string_in IN char, string_out OUT char) IS
BEGIN
----------
----------
END;
PNo: 166
TECH IQ Technologies
----------
----------
END;
2. The parameter list of overloaded functions must differ by more than name or
----------------------------------------------------------------------------------------------------------------------
parameter mode.
-------------------------
The parameter name is replaced by the values sent to the objects when the package is called, so
difference in name do not offer a guide to the overloaded objects that must be used.
Example:
-------------
A procedure definition will be as
END;
The name of the parameter is not available in the module call and thus PL/SQL interpreter cannot
distinguished objects by name.
Similarly, even if a parameter in the first module is IN and the same parameter is IN OUT in another
module, PL/SQL interpreter cannot distinguish using the package call.
3. Overloaded functions must differ by more than their return data type.
-----------------------------------------------------------------------------------------------------------
At the time that the overloaded functionsi called, the PL/SQL interpreter does not know what type of data
that function will return. The interpreter therefore cannot distinguish between different overloaded
functions based on the return data type.
4. All the overloaded modules must be defined within the same PL/SQL scope or block (PL/SQL block or
package)
Two modules cannot be overloaded across two PL/SQL blocks or across two packages.
PNo: 167
TECH IQ Technologies
Example:
---------------
When the above code interpreted, the PL/SQL interpreter displays the following error message.
Error in Line 12/Column 3:
PLS-0306: wrong number or type of arguments in call to 'REVISE_ESTIMATE'
PL/SQL displays the erros message because the scope and visibblity of both the procedures is different.
The scope od the date revise_estimates is the entire scope of the body develop_analysis. The scope of the
numeric revise_estimates is the inner block only and it takes precedence over the date revise_estimates.
A HRD manager generally gives raise of 0.05 in salary for the employees in a
specific department. The HRD manager can enter the department number or the
department so that the new salary is reflected in the employee table. Whenever
any such raise is given to the employees, an audit trail of the same is
maintained in the emp_raise table. The emp_raise table holds the employee number,
the date when the raise was given and the raise amount. Write a PL/SQL block to
update the salary of each employee of dept_no accepted from keyboard
appropriately and insert a record in the emp_raise table as well.
Table: EMP33
PNo: 168
TECH IQ Technologies
2 SURESH CLERKS 2123.08425 02-JUN-06 20 HYDERABAD 4 ACCOUNTS
3 AMJAD SALESMAN 2229.23846 19-OCT-05 30 BANGLORE 1 SALES
4 SALIM SALESMAN 2229.23846 12-APR-04 30 BOMBAY 5 SALES
5 RASHEED MANAGERS 2340.70039 29-AUG-08 40 MADRAS 3 PRODUCTION
6 PRADEEP ANALYSTS 2123.08425 16-NOV-01 50 HYDERABAD 7 COMPUTERS
7 ZAHEER PRESIDENTS 2123.08425 01-MAR-07 60 SHIMLA 5 CEO
8 SAMI TEACHER 2123.08425 20 DELHI 6 COMPUTERS
9 PRADEEP ENGINEER 2340.70039 16-JUL-08 30 MADRAS 3 PRODUCTION
10 SAMI DOCTOR 2123.08425 23-MAY-08 10 DELHI 2 HEART
Table: EMP_RAISE
Table : DEPT1
Solution:
Create a package spec and package body named employee_incentives that includes two procedures of the
same name. The procedure name is give_emp_raise. The first procedure accepts department number and
the second procedure accepts department name.
PNo: 169
TECH IQ Technologies
*/
BEGIN
OPEN c_emp(dept_no);
IF c_emp%ISOPEN THEN
LOOP
FETCH c_emp INTO str_emp_code,num_salary;
EXIT WHEN c_emp%NOTFOUND;
UPDATE emp33 set salary=num_salary+(num_salary*0.05)
where eno=str_emp_code;
INSERT INTO emp_raise values(str_emp_code,sysdate,num_salary*0.05);
END LOOP;
commit;
close c_emp;
ELSE
DBMS_OUTPUT.PUT_LINE('Unable to open cursor');
END IF;
END;
str_emp_code emp33.eno%type;
num_salary emp33.salary%type;
BEGIN
OPEN c_emp(dept_name);
IF c_emp%ISOPEN THEN
LOOP
FETCH c_emp INTO str_emp_code,num_salary;
EXIT WHEN c_emp%NOTFOUND;
UPDATE emp33 set salary=num_salary+(num_salary*0.05) WHERE
eno=str_emp_code;
INSERT into emp_raise values(str_emp_code,sysdate,num_salary*0.05);
END LOOP;
COMMIT;
CLOSE c_emp;
ELSE
DBMS_OUTPUT.PUT_LINE('Unable to open cursor');
END IF;
END;
END employee_incentives;
PNo: 170
TECH IQ Technologies
/
deptid number(3):=&deptid;
CURSOR scantable IS
SELECT deptno,dname FROM emp33 where
deptno=deptid;
dept_no number(2);
dept_name varchar2(12);
dept_type varchar2(10);
counter number(3);
BEGIN
dept_type:='&dept_type';
dbms_output.put_line('Entered department number is deptno ...... ' || deptid);
counter:=0;
OPEN scantable;
LOOP
FETCH scantable INTO dept_no,dept_name;
EXIT WHEN scantable%NOTFOUND;
counter:=counter+1;
IF dept_type='NO' THEN
employee_incentives.give_emp_raise(dept_no);
DBMS_output.put_line('Record is updated with number as its parameter');
END IF;
END LOOP;
CLOSE scantable;
COMMIT;
SYS.dbms_output.put_line('No. of records updated = ' || counter);
END;
/
xi)Trigger:
A trigger is a database object which will be automatically generated whenever any operation took place
on table data. The trigger will be generated when we use either INSERT, UPDATE and DELETE statement.
The trigger has generally two components:
1. A database trigger event
2. A PL/SQL block that will execute the trigger event.
The occurring of the database event is strongly bound to table data being changed.
Trigger will be created on the client machine and will stored on the server machine ie Oracle engine.
A trigger is acctually a procedure that will be implicitly executed by the oracle engine. It is similar to
procedures means it is also having block of statement that will be executed but the trigger will not have
any arguments and also it will not generated by the user but by the oracle engine implicitly.
PNo: 171
TECH IQ Technologies
Introduction:
The Oracle engine allows the user to deine procedures that are implicitly eecuted (i.e. executed by the
Oracle engine itself), when an insert, update or delete is issued against a table from SQL*Plus or through
an application. These porcedures are called database triggers. The major issue that make these triggers
stand-alone is that they are fired implicitly (i.e. internally) by the Oracle engine itself and not explicitly
called by the user.
Use of Database Triggers:
Since the Oracle engine supports database triggers it provides a highly customizable database
management system. Some of the uses to which the database triggers can be put, to customize
management information by the Oracle engine are as follows:
* A trigger can permit DML statements against a table only if they are issued, during regular business
hours or on predetermined weekdays.
* A trigger can also be used to keep an audit trail of a table (i.e. to store the modified and deleted records
of the table) along with the operation performed and the time on which the operation was performed.
[] It can be used to prevent invalid transactions
[] Enforce complex security authorizations
Note: 1. When a trigger is fired, an SQL statement inside the trigger's PL/SQL code block can also fire the
sameor some other trigger. This is called cascading, triggers.
2. Excessive use of triggers for customizing the database can result in complex interdependencies
between the triggers, which may be difficult to maintain in a large application.
2. Trigger Restriction:
---------------------------------
PNo: 172
TECH IQ Technologies
A trigger restriction specifies a Boolean (logical0 expression that must be TRUE for the trigger to fire. It is
an option available for triggers that are fired for each row. Its function is to conditionally control the
execution of a trigger. A trigger restriction is specified using a WHEN clause.
3. Trigger Action:
--------------------------
While defining a trigger, the number of times the trigger action is to be executed can be speficied. This can
be once for every row affected by the triggering statement (such as might be fired by an UPDATE
statement that updates many rows), or once for the triggering statement, no matter how many rows it
affects.
Types of Triggers:
----------------------------
Whle defining a trigger, the number of times the trigger action is to be executed can be specified. This can
be once for every row afected by the triggering statement (such as might be fired by an UPDATE
statement that updates many rows), or once for the triggering staement, no matter now many rows it
affects.
1. Row Trigger:
----------------------
A row trigger is fired each time a row in the table is affected by the triggering statement. For example, if
an UPDATE statement updates multiple rows of a table, a row trigger is fired once for each row affected by
the UPDATE statement. If the triggering statement affects no rows, the trigger is not executed at all. Row
triggers should be used when some processing is required whenever a triggering statement affects a
single row in a table.
2. Statement Triggers:
-------------------------------
A statement trigger is fired once on behalf of the triggering statement, independent of the number of rows
the triggering staement affects (even if no rows are affected). Statement triggers should be used when a
triggering statement afects rows in a table but the processing required is completerly independent of the
number of rows affected.
Before Triggers:
-----------------------
BEFORE triggers execute the trigger action before the triggering statement. These types of triggers are
commonly used in the following situation:
[] BEFORE triggers are used when the trigger action should determine whether or not the triggering
statement should be allowed to complete. By using a BEFORE trigger, you can eliminate unnecessary
processing of the triggering statement.
[] BEFORE triggers are used to derive sprcific column values before completing a triggering INSERT or
UPDATE statement.
Validation and security is implemented in the before trigger.
After Triggers:
---------------------
AFTER trigger executes the trigger action after the triggering statement is executed. These types of
triggers are commonly used in the following situation. Auditing and replication is done in the after trigger.
[] aAFTER triggers are used when you want the triggering statement is to complete before executing the
trigger action.
PNo: 173
TECH IQ Technologies
[] If a BEFORE trigger is already present, an AFTER trigger can perform different actions on the same
triggering statement.
Combinations Triggers:
---------------------------------
Using the options explained above, four types of triggers could be created:
OR REPLACE: Recreates the trigger if it already exists. This option can be used to change the definition of
an existing trigger without first dropping it.
schema : It is the schema to contain the trigger. If the schema is omitted, the Oracle engine creates the
trigger in the users own schema.
BEFORE : It indicates that the Oracle engine fires the trigger before executing the triggering
statement.
PNo: 174
TECH IQ Technologies
AFTER : Indicates that the Oracle engine fires the trigger after executing the triggering
statement.
DELETE : Indicates that the Oracle engine fires the trigger whenever a DELETE statement
removes a row from the table.
INSERT : Indicates that the Oracle engine fires the trigger whenever a INSERT statement adds a
row to the table.
UPDATE : Indicates that the Oracle engine fires the trigger whenever an UPDATE statement changes a
value in one of the columns specified in the OF clause. If the OF clause is omitted, the
Oracle engine fires the trigger whenever an UPDATE statement changes a value in
any column of the table.
ON : Specifies the schema and name of the table, which the trigger is to be created. If schema
is omitted, the Oracle engine assumes the table is in the users own schema. A trigger cannot be created
on a table in the schema SYS.
REFERENCING : Specifies correlaion names. Correlation names can be used in the PL/SQL block and
WHEN clause of a row trigger to refer specifically to old and new values of the current row. The default
correlation names are OLD and NEW. If the row trigger is associated with a table names OLD or NEW, this
clause can be used to specify different correlation names to avoid confusion between table name and the
correlation name.
FOR EACH ROW : Designates the trigger to be a row trigger. The Oracle engine fires a row trigger once
[] If the row trigger is not properly written then it generates the effect which depends on the order in
which rows are processed. Since the user cannot control the order in which rows are processed, such
triggers may generate unexpected data. A user has to take care that the trigger code should generate
effect, which is independent of the order in which rows are evaluated.
--Create a TRIGGER which does not allow any DML operations over the --EMP table, if the user is SYSTEM.
PNo: 175
TECH IQ Technologies
/
/*Create a trigger that allows no DML operation on EMP77 table to be performed on first day of every
month*/
create trigger a
before insert or update on EMP
declare
uname varchar2(20);
begin
select user into uname from dual;
if INSERTING then
if (to_char(sysdate,'DD')= '01')
then
Raise_application_error(-20111,'Insertion is not allowed
on first day');
end if;
end if;
if updating then
Raise_application_error(-20112,'Updation is not
allowed ');
end if;
end;
/
/*Trigger that will not allow any insertion of the record on EMP1 table if its new record is ENO=10*/
create trigger n
before insert or update or delete on emp1
for each row
when (new.eno=10)
declare
begin
if INSERTING then
end if;
if updating or deleting then
Raise_application_error(-20112,'Updation and Deletion is not
allowed ');
end if;
end;
/
PNo: 176
TECH IQ Technologies
//Another example program using ‘TRIGGER’
CLIENT_NO VARCHAR2(6)
NAME VARCHAR2(10)
BAL_DUE NUMBER(5)
OPERATION VARCHAR2(7)
USERID VARCHAR2(10)
ODATE DATE
PNo: 177
TECH IQ Technologies
bal_due:=:new.bal_due;
insert into audit_client values(client_no,name,bal_due,oper,user,sysdate);
end;
/
CLIENT_NO VARCHAR2(6)
NAME VARCHAR2(10)
BAL_DUE NUMBER(5)
OPERATION VARCHAR2(7)
USERID VARCHAR2(10)
ODATE DATE
CREATE OR REPLACE TRIGGER audit_trail AFTER UPDATE OR DELETE ON CLIENT_MASTER FOR EACH ROW
DECLARE
/* The value in the oper variable will be inserted into the operation field in the auditclient table */
oper varchar2(8);
/*These variables will hold the previous values of clientno,name and bal_due*/
CLIENT_NO varchar2(10);
NAME varchar2(10);
BAL_DUE number(5);
BEGIN
/*if the records are updated in client_master table then oper is set to 'update'*/
IF updating THEN
oper:='update';
END IF;
/*if the records are deleted in client_master table then oper is set to 'delete' */
IF deleting THEN
oper:='delete';
END IF;
/*Store: old.client_no,:old.name, and :old.bal_due into client_no,name and bal_due. These variables can
then be used to insert data into the auditclient table*/
CLIENT_NO :=:old.CLIENT_NO;
PNo: 178
TECH IQ Technologies
NAME :=:old.NAME;
BAL_DUE :=:old.BAL_DUE;
INSERT INTO auditclient VALUES(CLIENT_NO,NAME,BAL_DUE,oper,user,sysdate);
END;
/
Introduction:
-----------------
In a multi-user environment, to allow data entry operators to and enter a primary key to uniquely identify a
record, will always result a in a large number of records being rejected due to duplicate values being
keyed in. This will result in a time delay between the record being keyed and the record being accepted for
storage.
Simple but effective approaches that can be used to generate a primary key are:
1. Use a lookup table that stores the last primary key value. The new primary key value must be generated
from the value stored in the lookup table.
3. Use a Sequence.
As soon as the Oracle engine receives data to be inserted into tables, the Oracle engine must invoke a
program that generates the primary key value. The primary key value so generated is merged with the
data that has to be inserted into the table. This entire record, now consisting of the primary key as well as
the data is then posted into the table.
The program unit that fires automatically before or after any write operation is performed on the table is
called "Database Trigger". Thus a database trigger can be used to generate a primary key value. The
primary key value must be generated before the data is posted into the table. Thus the database trigger
must be written such that it executes before the data is posted into the table i.e. a BEFORE INSERT
database trigger.
PNo: 179
TECH IQ Technologies
DECLARE
primary_key_value varchar2(6);
BEGIN
select lpad(to_char(client_seq.nextval),5,'0')
INTO primary_key_value FROM dual;
:new.client_no:='C' || primary_key_value;
END;
/
The above code gets the next sequence value. The sequence value is then padded with 0's using LPAD
function and concatenated with 'C'. So the entire output will look like 'C00001' if the sequence value is 1.
The data in the last SQL statement can be classified as New values and Old values. When the user fires an
insert statement the values of the columns included in the insert statement can be read or set by
using :NEW.columnname.
Similarly if the user updates a record, the value before the updation can be read by
using :OLD.columnname. The new values set using an update statement will be referenced by using :
NEW.columnname.
In the current example, we need to set the value of client_no, which will be inserted into the table. Thus we
need the value of :new.client_no.
The sequence number value is then assigned to the column client_no by using :new.client_no.
PNo: 180
TECH IQ Technologies
Since the client_no is generated automatically, the must insert values in all columns except the client_no
column.
DECLARE
primary_key_value varchar2(6);
BEGIN
select lpad(to_char(client_seq.nextval),5,'0')
INTO primary_key_value FROM dual;
:new.client_no:='C' || primary_key_value;
END;
The above code gets the next sequence value. The sequence value is then padded with 0's using LPAD
function and concatenated with 'C'. So the entire output will look like 'C00001' if the sequence value is 1.
The data in the last SQL statement can be classified as New values and Old values. When the user fires an
insert statement the values of the columns included in the insert statement can be read or set by
using :NEW.columnname.
Similarly if the user updates a record, the value before the updation can be read by
using :OLD.columnname. The new values set using an update statement will be referenced by using :
NEW.columnname.
PNo: 181
TECH IQ Technologies
In the current example, we need to set the value of client_no, which will be inserted into the table. Thus we
need the value of :new.client_no.
The sequence number value is then assigned to the column client_no by using :new.client_no.
Since the client_no is generated automatically, the must insert values in all columns except the client_no
column.
Syntax:
----------
CREATE OR REPLACE TRIGGER product_no_generation
BEFORE INSERT
ON client_master
FOR EACH ROW
DECLARE
max_pkey_value varchar2(5);
new_pkey_value varchar2(5);
BEGIN
SELECT nvl(substr(max(client_no),2,5),0)
INTO max_pkey_value FROM client_master;
new_pkey_value:=lpad(to_char((to_number
(max_pkey_value+1))),5,'0');
:new.client_no:='C'||new_pkey_value;
END;
/
PNo: 182
TECH IQ Technologies
Since the product_no is generated automatically, the user must insert values in all columns except the
product_no column.
xii)OPERATIONS ON COLLECTIONS
We can do operations on collections as a whole. We can insert, update or delete collections using SQL DML
statement. We can reference collection using SELECT ... INTO statement.
Declaring a table
---------------------
CREATE TYPE tab_courselist AS
TABLE OF tab_course
/
In the above code, nested table clause is required to create a nested table. The table has column courses
with nested table data type using them.
INSERT Operations
-----------------------
Inserting Data:
UPDATE Statement
--------------------------
We can update collections using the update clause. We can use the constructor method to set new values.
Update tab_student
Set courses = tab_courselist(tab_course (10, 'Oracle'),
tab_course (25,'C')) where sname = 'Anil'
/
PNo: 183
TECH IQ Technologies
begin
X := tab_courselist (tab_course( 10, '.NET'), tab_course(25,'MS ACCESS'));
Update tab_student
Set courses = X
where sname = 'Anil';
end;
/
DELETE Statement:
-------------------------
Using this statement, we can delete rows having collection
delete tab_student
where sname = 'Anil'
/
PNo: 184
TECH IQ Technologies
Manipulating Individual Element in Nested Table
We can manipulate individual element in a nested table using INSERT, UPDATE or DELETE statement. The
required nested table is identified using THE operator
INSERT Statement:
-----------------------
Inserting additional element in nested table of student 'Anil'
INSERT INTO THE ( select courses from tab_student where sname= 'Sunil')VALUES (40,'Ada')
/
The subquery THE identifies the nested table on which you want to do data manipulation.
UPDATE Statement
-----------------------
The update operation can be performed similarly using THE operator
DELETE Statement
-----------------------
We can delete rows in nested table using the delete statement. The query of 'THE' identifies the nested
table on which data manipulation has to be performed.
SELECT.....INTO Statement
---------------------------------
We can retrieve data from the nested table using the SELECT...INTO statement.
declare
X varchar2(30);
begin
SELECT coursename
INTO X
from THE (select courses
from tab_student
where sname = 'Sunil')
where coursecode = 10;
dbms_output.put_line(X); --prints Oracle
end;
/
PNo: 185