[go: up one dir, main page]

0% found this document useful (0 votes)
64 views185 pages

Oracle Print

Hhg

Uploaded by

pavan mariserla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views185 pages

Oracle Print

Hhg

Uploaded by

pavan mariserla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 185

TECH IQ Technologies

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.

DBMS(Database Management System)


A DBMS is defined as “A software that provides an environment that is both convenient and efficient to use in storing
and retrieving the data of an enterprise.”
In short, A Database Management System means a system managing the database of a particular enterprise in both
the convenient and efficient manner.

RDBMS(Relational Database Management System)


A Relational database management system RDBMS is a database management system DBMS that
is based on the relational model as introduced by E. F. Codd.
In the relational model, a database is a collection of one or more relations, where each relation is a table with rows
and columns. The major advantages of the relational model over the older data models are its simple data
representation and the ease with which even complex queries can be expressed.

The main differences between DBMS and RDBMS are given below:

No. DBMS RDBMS


1) DBMS applications store data as RDBMS applications store data in a tabular form.
file.

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.

3) Normalization is not present in Normalization is present in RDBMS.


DBMS.

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

7) DBMS does not support RDBMS supports distributed database.


distributed database.

8) DBMS is meant to be for small RDBMS is designed to handle large amount of


organization and deal with small data. it supports multiple users.
data. it supports single user.

9) Examples of DBMS are file Example of RDBMS are mysql, postgre, sql
systems, xml etc. server, oracle etc.

1.1 Database System Applications


 Banking: For customer information, accounts, and loans and banking transactions.
 Airlines: For reservations and schedule information. Airlines were among the first to use databases in a
geographically distributed manner – terminals situated around the world accessed the central database
system through phone lines and other data networks.
 Universities: For student information, course registrations, and grades.
 Credit Card Transactions: For purchases on credit cards and generation of monthly statements.
 Telecommunication: For keeping records of calls made, generating monthly bills, maintaining balances on
prepaid calling cards, and storing information about the communication networks.
 Finance: For storing information about holdings, sales, and purchases of financial instruments.
 Sales: For customer, product, and purchase information.
 Human Resources: For information about employees, salaries, payroll taxes and benefits, and for generation
of paychecks.
1.2 Database Systems versus File Systems
Consider part of a savings-bank enterprise that keeps information about all customers and savings accounts. One way
to keep the information on a computer is to store it in operating system files. To allow users to manipulate the
information, the system has a number of application programs that manipulate the files, including
 A program to debit or credit an account
 A program to add a new account
 A program to find the balance of an account
 A program to generate monthly statements
System programmers wrote these application programs to meet the needs of the bank.
New application programs are added to the system as the need arises. For example, suppose that the savings bank
decides to offer checking accounts. As a result, the bank creates new permanent files that contain information about
all the checking accounts maintained in the bank, and it may have to write new application programs to deal with
situations that do not arise in savings accounts, such as overdrafts. Thus, as time goes by, the system acquires more
files and more application programs.
This typical”file-processing system” is supported by a conventional operating system. The system stores
permanent records in various files, and it needs different application programs to extract records from, and add
records to, the appropriate files. Before database management systems (DBMS) came along, organizations usually
stored information in such systems.
Keeping organizational information in a file-processing system has a number of disadvantages:
 Data redundancy and inconsistency: Since different programmers create the files and application
programs over a long period, the various files are likely to have different formats and the programs may be
written in several programming languages. Moreover, the same information may be duplicated in several
places (files). For example, the address and telephone number of a particular customer may appear in a file
that consists of savings-account records and in a file that consists of checking-accounts records. This
redundancy leads to higher storage and access cost. In addition, it may lead to data inconsistency; that is, the
various copies of the same data may no longer agree. For example, a changed customer address may be
reflected in savings-account records but not elsewhere in the system.
 Difficulty in Accessing Data: Suppose that one of the bank officers needs to find out the names of all
customers who live within a particular postal-code area. The officer asks the data-processing department to
generate such a list. Because the designers of the original system did not anticipate this request, there is no
application program on hand to meet it. There is, however, an application program to generate the list of all

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

1.3 View of Data


A major purpose of the database system is to provide users with an “abstract view” of data. That is, the system hides
certain details of how the data are stored and maintained.
1.3.1 Data Abstraction: For the system to be usable, it must retrieve data efficiently. The need for efficiency
has led designers to use complex data structures to represent data in the database. Since many database-
systems users are not computer trained, developers hide the complexity from users through several levels
of abstraction, to simplify users interactions with the system:
 Physical Level: This is the lowest level of data abstraction. It describes how the data are actually stored. The
physical level describes complex low-level data structures in detail.
 Logical Level: This is next higher-level of data abstraction which deals with what data is stored and what
is the relationship exist among those data.
 View Level: The highest level of data abstraction describes only part of the entire database. Even though the
logical level uses simpler structures, complexity remains because of the variety of information stored in a large
database. Many users of the database system do not need all this information; instead, they need to access
only a part of the database. The view level of abstraction exists to simplify their interaction with the system.

PNo: 3
TECH IQ Technologies

View Level

View 1 View 2 …. View n

Logical
Level

Physical
Level

Three levels of Data Abstraction

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.

1.4 Data Models


It is a collection of conceptual tools for describing data, data relationships, data semantics, and consistency
constraints.
There are three types of data models:
1.4.1 Object Based data model
This model is use to describe the data at the view level and logical level. It uses the concept of an object. The various
models which come under this category are:

A. Entity Relationship model:


The E-R model is based on a perception of a real world that consists of a collection of basic objects, called
entities, and of relationships among these objects.
An entity is a “thing” or “object” in the real world that is distinguishable from other objects.
For example, each person is an entity, and bank accounts can be considered as entities.
Entities are described in a database by a set of attributes. For example, customer-name, customer-street address
and customer-city may describe a customer entity.
A relationship is an association among several entities. For example, a depositor relationship associates a
customer with each account that he has. The set of all entities of the same type and the set of all relationships of
the same type are termed an entity set and relationship set, respectively.
The overall logical structure of a database can be expressed graphically by an E-R diagram, which is built up from
the following components:

 Rectangles, which represent entity sets

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.

Cust-Name Cust- Acc-No Balance


Street

Customer-Id City

Customer Depositor Account

A sample E-R diagram

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.

Customer-Id Customer-Name Street City

454-98989 Sam Fort Street Shimla


192-83-65 Johnson Park Avenue New Delhi
34-987-56 Smith Bank Street Mumbai

Rules for naming a table:


Maximum 30 characters are allowed.
The first character must be an alphabet
Special symbols and digits are not allowed.

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.

1.5 Database Languages


A database system provides a data definition language to specify the database schema and a data
manipulation language to express database queries and updates. In practice, the data definition ad
data manipulation languages are not two separate languages; instead they simply form parts ofa single
database language, such widely used SQL language.

1.5.1 Data-Definition Language(DDL)

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:

Create table account


(account-number char(10), balance number);
Execution of the above DDL statement creates the account table. In addition, it updates a special set of tables called
the data dictionary or data directory.

Some of the commands of the DDL are:


Create, alter, and drop.
1.5.2 Data Manipulation Language (DML):
A DML is a language that enables users to access or manipulate data as organized by the appropriate data
model.
While using DML we can perform the following types of operations:
 The retrieval of information stored in the database.
 The insertion of new information into the database.
 The deletion of information from the database.
 The modification of information from the database.

There are basically two types:


 Procedural DMLs require a user to specify what data are needed and how to get those data.
 Declarative DMLs (also non-procedural DMLs) require a user to specify what are needed
without specifying how to get those data.
Some of the commands of the DML are:
(SELECT, DELETE, UPDATE, AND INSERT).
A query is a statement requesting the retrieval of information. The portion of a DML that involves
information retrieval is called a query language.

1.5.3 Database Access from Application Programs


Application programs are programs that are used to interact with the database. Application
programs are usually written in a host language, such as COBOL, C, C++ and Java.

1.6 Database Users and Administrators


A primary goal of a database system is to retrieve information from and store new information in the
database. People who work with a database can be categorized as database users or database
administrators.

PNo: 6
TECH IQ Technologies

1.6.1 Database Users


There are four different types of database-system users, differentiated by the way they expect to interact
with the system.
i. Application Programmers: These types of users write programs in a host language such as C,
COBOL, Pascal etc by inserting DML commands in it. These DML commands are prefix by a special
character under compile b embedded DML compiler and then compiled by the host language
compiler.
ii. Sophisticated Users: These types of users do not write any programs but submit queries to the
system in order to retrieve the data.
iii. Specialized Users: These users write special programs to retrieve the data these programs may
be using computer aided designing, knowledge and expert base system.
iv. Naïve Users: These users retrieve the data by invoking programs already written by application
programmers or specialized users.
1.6.2 Database Administrator
One of the main reasons for using DBMSs is to have central control of both the data and the programs that
access those data. A person who has such central control over the system is called a database
administrator (DBA)
The function of DBA includes:
 Schema definition. The DBA creates the original database schema by executing a set of data
definition statements in the DDL.
 Storage structure and access-method definition.
 Schema and physical-organization modification: The DBA creates out changes to the schema and
physical organization to reflect the changing needs of the organization, or to alter the physical
organization to improve performance.
 Granting of authorization for data access: By granting different types of authorization, the
database administrator can regulate which parts of the database various users can access. The
authorization information is kept in a special system structure that the database system consults
whenever someone attempts to access the data in the system.
 Routine maintenance: Examples of the database administrator’s routine maintenance activities
are:
 Periodically backing up the database, either onto tapes or onto remote servers, to prevent loss of
data in case of disasters such as flooding.
 Ensuring that enough free disk space is available for normal operations, and upgrading disk space
as required.
 Monitoring jobs running on the database and ensuring that performance is not degraded by very
expensive tasks submitted by some users.

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.

Some of the software’s of databases are:


i. ORACLE
ii. MS ACCESS
iii. MYSQL
iv. SQL SERVER
v. SYBASE
vi. DB2
vii. Ingress
viii. Pointbase
ix. Derby
x. Informix
xi. MaxDB
xii. SQLite etc.

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.

The major features of Oracle:


• Oracle is an open system
• Oracle supports databases of all sizes from several bytes to gigabytes in size
• Oracle supports a large number of concurrent users. It minimizes data contentions and guarantees data
concurrence
• Oracle supports a true Client/Server environment. It enables processing to be split between database
server and the client application program
• Oracle uses its own internal optimizer to determine the fastest and best means of accessing data

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.

1979 - Oracle release 2

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?.

1983 - Oracle release 3

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.

1984 - Oracle release 4

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.

1985 - Oracle release 5

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.

1988 - Oracle release 6

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 - Oracle release 7

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.

1997 - Oracle release 8

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.

1998 - Oracle release 8i

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.

2001 - Oracle release 9i

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.

2003 - Oracle release 10g

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.

2007 - Oracle release 11g

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.

Oracle Announces General Availability of Oracle


Database 12c, the First Database Designed for the
Cloud
REDWOOD SHORES, Calif. – July 1, 2013

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.

New Multitenant Architecture for Database Consolidation on the Cloud


Oracle Database 12c addresses the key challenges of customers who are consolidating databases in a private cloud model by
enabling greatly improved efficiency and lower management costs, while retaining the autonomy of separate databases.
Oracle Multitenant is a new feature of Oracle Database 12c, and allows each database plugged into the new multitenant architecture
to look and feel like a standard Oracle Database to applications; so existing applications can run unchanged.
By supporting multi-tenancy in the database tier, rather than the application tier, Oracle Multitenant makes all ISV applications that
run on the Oracle Database ready for SaaS.
Oracle Multitenant manages many databases as one and can increase server resource utilization and reduce the time and effort
required for database upgrades, backup, recovery, and much more.
The multitenant architecture provides virtually instantaneous provisioning and cloning of databases, which makes it an ideal platform
for database test and development clouds.
Oracle Multitenant works with all Oracle Database features, including Real Application Clusters, Partitioning, Data Guard,
Compression, Automatic Storage Management, Real Application Testing, Transparent Data Encryption, Database Vault, and more.

PNo: 12
TECH IQ Technologies

Automatic Data Optimization

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.

Defense in Depth Security

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.

Maximum Availability for Database Clouds

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.

Efficient Database Management

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.

Simplifying Analysis of Big Data

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.”

SQL as the Database native language:

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

Categories of SQL commands:


The SQL instructions can be classified into the following categories:
1) Data Definition Language (DDL):
The commands in DDL are used to design, alter or drop the structures of database objects like tables,
views, synonyms etc.
i. CREATE : To creat the objects in the database
ii.ALTER : Alters the structure of the database
iii.RENAME : To rename the existing table or object with a new name in a database.
iv.DROP : To remove the table or object from database.
v. TRUNCATE: Remove all records from a table, including all spaces allocated for the
records are removed.
2) Data Manipulation Language (DML):
The commands in DML are used to manipulate the data of the existing database objects.
i. INSERT : Inserts data into a table.
ii. SELECT : Retrieve the data which is stored in a table
iii.UPDATE: Updates existing data within a table
iv.DELETE: Deletes all records from a table, the space for the records remain
v. CALL : Call a PL/SQL program3) Transaction Control Language (TCL):
The commands in TCL are used to manage all the changes made by the DML statements.
Eg: COMMIT, SAVEPOINT and ROLLBACK
4) Data Control Language (DCL):

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);

NCHAR: It can store all international characters upto 1000.

2. VARCHAR/VARCHAR2(n) Variable length character string having maximum length n bytes,


maximum size is 4000. If the data value is shorter in length than length defined for the column, no blank
spaces will be added to the value. It is a nonpadded data value. If the data value is longer than the length
defined for the column, Oracle returns an error code.
Eg: Person_Name VARCHAR2(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.

6. LONG to store variable length character strings contain in up to 2 gigabytes.


We can reference LONG columns in SQL statements in these places.
The use of LONG values is subject to some restrictions
A table cannot contain more than one LONG column.
LONG columns cannot appear in integrity constraints (except for NULL and NOT NULL constraints).
A procedure or stored function cannot accept a LONG argument.
A stored function cannot return a LONG value.
Within a single SQL statement, all LONG columns, sequences updated tables, and locked tables must be
located on the same database.
Also LONG columns cannot appear in certain parts of SQL Statement:
WHERE, GROUP BY, ORDER BY or CONNECT BY clauses or with the DISTINCT operator in SELECT
statements.

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).

int: It is a fixed point number with precision 126 with scale.


integer: It is a fixed point number with precision 126 with scale.
float: 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 from 1 to 126
integer and 1 to 138 in decimal points.

ROWID values have several important uses:


They are the fastest means of accessing a single tow
They can show us how a table's rows are stored
They are unique identifiers for rows in a table
A ROWID does not change during the lifetime of its row A ROWID value is represented in the following
format block.row file block is hexadecimal string identifying the data block of the data file containing row.
row is a four-digit hexadecimal string identifying the row in the data block file is a hexadecimal string
identifying database file containing the row.

What is difference between varchar and varchar2


 VARCHAR can store up to 2000 bytes of characters while VARCHAR2 can store up to 4000
bytes of characters.

 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.

Operation on database table using SQL commands are:


-----------------------------------------------------------------
//Creting Table
SQL> CREATE TABLE STUDENT(RNO NUMBER(3),NAME VARCHAR2(10),S1 NUMBER(2),S2 NUMBER(2),
S3 NUMBER(2));

SQL> DESC STUDENT


Name Null? Type
----------------------------------------- -------- ------------
RNO NUMBER(3)
NAME VARCHAR2(10)
S1 NUMBER(2)
S2 NUMBER(2)
S3 NUMBER(2)
//Inserting Data First way
Insert Into Student Values(1,’RAKESH’,65,89,76);
Insert into student values(2,’ALTAF’,78,87,65);
Insert into student values(3,’SANDEEP’,89,98,76);
Insert into student values(4,’TAHSEEN’,65,35,89);

//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;

SQL> SELECT * FROM STUDENT;


RNO NAME S1 S2 S3 TOTAL AVG
---------- ---------- ---------- ---------- ---------- ---------- ----------
1 AKBAR 65 89 76 230 77
2 ALTAF 78 87 65 230 77
3 SIDDIQUE 89 98 76 263 88
4 TAHSEEN 65 35 89 189 63

//Renaming table
SQL> RENAME STUDENT TO STUDENTINFO;
->After RENAME command, the table will look like this

SQL> SELECT * FROM STUDENTINFO;

RNO NAME S1 S2 S3 TOTAL AVG


---------- ---------- ---------- ---------- ---------- ---------- ----------
1 AKBAR 65 89 76 230 77
2 ALTAF 78 87 65 230 77
3 SIDDIQUE 89 98 76 263 88

PNo: 17
TECH IQ Technologies
4 TAHSEEN 65 35 89 189 63
//Deleting record
SQL> DELETE FROM STUDENTINFO WHERE RNO=4;

->Table data after deletion operation will be:


SQL> SELECT * FROM STUDENTINFO;
RNO NAME S1 S2 S3 TOTAL AVG
---------- ---------- ---------- ---------- ---------- ---------- ----------
1 AKBAR 65 89 76 230 77
2 ALTAF 78 87 65 230 77
3 SIDDIQUE 89 98 76 263 88
SQL> DROP TABLE STUDENTINFO;

Working on another table


drop table Emp;
create table Emp(empno number(4),name varchar2(15),
city varchar2(15),job varchar2(16),doj date,comm number(3),
salary number(6));

insert into emp values(&empno,'&name','&city',


'&job','&doj',&comm,&salary);

insert into emp values(1,'Junaid','Hyderabad','Doctor','26-oct-2010',593,8405);

insert into emp values(2,'Sandeep','Mangalore','Engineer','12-sep-2010',672,6475);

insert into emp values(3,'Pradeep','Paris','Super visor','03-sep-2010',134,6475);

insert into emp values(4,'Prakash','Delhi','Business','17-sep-2010',692,6222);

insert into emp values(5,'Aslam','Mangalore','Engineer','12-sep-2010',672,6475);

insert into emp values(6,'Sirish','ECIL','Engineer','26-mar-2010',435,3455);

insert into emp values(7,'Rahul','Bangalore','Doctor','16-mar-2011',434,7364);

insert into emp values(8,'NAVED','BANGALORE','DOCTOR','12-AUG-010',478,5938);

insert into emp values(9,'FARID','DELHI','MANAGER','23-JUN-2010',944,4850);

SQL> desc emp;


Name Null? Type
----------------------------------------- -------- ------------
EMPNO NUMBER
NAME VARCHAR2(12)
CITY VARCHAR2(12)
JOB VARCHAR2(13)
DOJ DATE
COMM NUMBER
SALARY NUMBER
VIEWING DATA IN THE TABLES:
1. Selected Columns and all Rows
The retrieval of selected columns from a table.
Syntax: SELECT columnname,columnname FROM table;

PNo: 18
TECH IQ Technologies

eg: select empno,name,job from emp;


EMPNO NAME JOB
----- ------------ -------------
101 HAMED MANAGER
102 ANSAR ENGINEER
103 ASLAM PRINCIPAL
104 SAJID BUSINESS
105 KALEEM MANAGER
106 ZAHEER ACCOUNTANT
107 JUNAID MANAGER
2. Selected Rows and all Columns
If information of a particular client must be retrieved from the table, its retrieval must be based on on a
specific condition.

Syntax: Select * from tablename where search condition;

eg: SQL> select * from emp where COMM>500;


EMPNO NAME CITY JOB DOJ COMM SALARY
---------- ---------- ------------ ------------ ------------- --------- ----------
104 SAJID SHIMLA BUSINESS 12-FEB-13 739 12933
105 KALEEM NEW DELHI MANAGER 31-DEC-14 893 7439
107 JUNAID BANGALORE MANAGER 16-APR-15 838 3858
3. Selected Columns and Selected Rows
To view a specific data set from the table and also a select number of columns the sysntax will be:

Syntax: Select columnname,columnname from tablename where search condition;


eg: SQL> select empno,name,city from emp where salary<40000;
EMPNO NAME CITY
---------- ------------ ------------
101 HAMED HYDERABAD
104 SAJID SHIMLA
105 KALEEM NEW DELHI
106 ZAHEER HYDERABAD
107 JUNAID BANGALORE
4. Elimination of Duplicates: A table could hold duplicate rows. In such a case, to see only unique rows the
syntax is:
Syntax: SELECT DISTINCT column-name1,column-name2 from tablename;
eg: Select DISTINCT city FROM emp;
5.CREATING A TABLE FROM ANOTHER TABLE:
-----------------------------------------
Here the source table is identified by 'SELECT' and target table is identified
by 'CREATE'.

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

Create Table C1 As Select


Cno,Cname,Product,Qty,Price,Bill,Discount_15per,Finalbill From Customer;

select * from c1;

create table c2 as select cno,cname,product,qty,bill from customer;

select * from c2;

create table c3 as select * from customer;

select * from c3;

create table c4 (clno,cmr_name,product_name,how_many,amount) as select


cno,cname,product,price, qty from customer;

select * from c4;

create table emp(eno number,ename varchar2(15),city varchar2(20));

Insert Into Emp Values(1,'SACHIN','MUMBAI');


Insert Into Emp Values(2,'KALEEM','DELHI');
Insert Into Emp Values(3,'RAHUL','HYDERABAD');
Insert Into Emp Values(4,'SUNIL','MUMBAI');
Insert Into Emp Values(5,'NAVED','BANGALORE');
Insert Into Emp Values(6,'NAVEEN','DELHI');
Insert Into Emp Values(7,'VENKAT','HDERABAD');
update emp set city='HYDERABAD' WHERE ENO=7;
Select * From Emp;

SELECT CITY FROM EMP;

//To display unique city values


SELECT DISTINCT CITY FROM EMP;

//applyging 'default value' to column of table


CREATE TABLE EMP1(ENO NUMBER,ENAME VARCHAR2(15),SALARY NUMBER DEFAULT 5000);

Insert Into Emp1 (Eno,Ename) Values(1,'SACHIN');


Insert Into Emp1 Values(2,'JUNAID',6894);
SELECT * FROM EMP1;

2.INSERTING DATA INTO A TABLE FROM ANOTHER TABLE


----------------------------------------------------
In addition to inserting data one row at a time into a table, it is quite
possible to populate a table with data that already exists in another table.

Syntax:

INSERT INTO tablename SELECT columnname,columnname FROM tablename;

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)) ;

select * from c5;

insert into c5 select cno,cname,product,qty,price from customer;

3.DELETE OPERATIONS: Here we can remove all rows or a selected set of rows from a
table

3.1. To delete all rows from a table

Syntax:
DELETE FROM tablename;

eg: delete from emp1;

3.2. To delete selected rows from a table

Syntax:
DELETE FROM tablename WHERE search condition;

eg:
delete from emp1 where sal>4000;

4. UPDATING THE CONTENTS OF A TABLE


The UPDATE command is used to change or modify data values in a table.

4.1 To update all the rows from a table

Syntax:
UPDATE tablename set columname=expression,columname=expression;

eg:
update emp set sal=sal+500;

4.2 To update selected rows in a table

Syntax:
UPDATE tablename set columname=expression,columname=expression where
columname=expression;

eg:
update emp12 set job='CHAIRMAN' WHERE SAL>10000;

5. MODIFYING THE STRUCTURES OF TABLES

Adding new columns:


Syntax: ALTER TABLE tablename ADD(newcolumname data-type(size),newcolumnname
data-type(size));

eg:
ALTER TABLE emp12 ADD(comm number,mgr number);

PNo: 21
TECH IQ Technologies
update emp12 set comm=450,mgr=540 where sal<6000;

5.1 MODIFYING EXISTING COLUMNS:

Syntax:
ALTER TABLE tablename MODIFY (columnname newdata-type(new size));

eg:
ALTER TABLE EMP12 MODIFY(ENAME VARCHAR2(20));

Table Altered

Some of the Restrictions on the ALTER COMMAND are:


1. You cannot change the name of the table.
2.You cannot decrease the size of a column if table data exists

Droppping a column from the existing table


------------------------------------------------------
It is possible to remove a column from the existing table by using the following
command as:
ALTER TABLE EMP DROP COLUMN CITY;

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;

7. DESTROYING TABLES: To delete or destroy a we will use 'DROP' command.

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;

9. Finding out the column details of a table created:


To find information about the columns defined inthe table use the following
syntax:

Syntax: DESCRIBE tablename;

eg: DESCRIBE EMP;


OR
DESC EMP;

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’);

Select * from emp77;

PNo: 23
TECH IQ Technologies

COMPUTATIONS ON TABLE DATA


We can use some of the operators in order to get data from a table or set the
data in a table.
For this, Arithmetic and logical operators give a new dimension to SQL sentences.

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.

Creating Table Emp


------------------------

drop table emp13;

Create table emp13(empno number(3),ename varchar2(20),job varchar2(12),


city varchar2(12),hiredate date,salary number(5),comm number(3),
mgr number(3));

SQL> desc emp13


Name Null? Type
----------------------------------------- -------- ----------------------------

EMPNO NUMBER(3)
ENAME VARCHAR2(12)
JOB VARCHAR2(12)
CITY VARCHAR2(12)
HIREDATE DATE
SALARY NUMBER(5)
COMM NUMBER(3)
MGR NUMBER(3)

insert into emp13 values(1,'SANDEEP SHARMA','ENGINEER','HYDERABAD','24-JUN-2014',


6000,473,274);
insert into emp13 values(2,'PRAKASH','DOCTOR','BANGLORE',
'03-JAN-2016',5000,374,242);
insert into emp13 values(3,'SALIM','CLERK','NEW DELHI',
'02-MAY-2014',7384,384,884);
insert into emp13 Values(4,'JUNAID','PILOT','BOMBAY','18-APR-2015',
3848,273,384);

insert into emp13 values(5,'SURESH','MANAGER','MADRAS',


'15-FEB-2015',3873,374,749);
insert into emp13 values(6,'SALMAN KHAN','MANAGER','NEW DELHI',

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);

SQL> SELECT * FROM EMP13;

EMPNO ENAME JOB CITY HIREDATE SALARY


---------- ------------ ------------ ------------ --------- ----------
COMM MGR
---------- ----------
1 SANDEEP ENG HYD 24-JUN-09 6000
473 274

2 PRAKASH DOCTOR BANGLORE 03-NOV-05 5000


374 242

3 SALIM CLERK NEW DELHI 02-MAY-08 7384


384 884

Data in the table before transaction is:


SQL> select ename,empno,salary,comm,mgr from emp13;

ENAME ENO SAL COMM MGR


-------------------- ---------- ---------- ---------- ----------
HAMED 101 5146 623 633
SAJID 104 13433 321 235
KALEEM 105 7939 167 278

Data in the table after transaction is:

SQL>select empno,ename,salary+(salary*0.10),comm+300,mgr+150 from emp13;

SQL> select empno,ename,salary,salary+(salary*0.10),comm,comm+300,mgr,mgr+150


from emp13;

ENO SAL*2 COMM+200 MGR+125


---------- ---------- ---------- ----------
101 10292 350 665
104 26866 376 271
105 15878 462 290
106 10718 667 665

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.

select * from emp13 where salary between 7000 and 10000;

eg:Select Empno,Ename,City,Job,Salary,comm,mgr From Emp13 Where Comm>350 And


Mgr>270;

SELECT EMPNO,ENAME,CITY,JOB,SALARY,comm,mgr FROM EMP13 WHERE comm>350 or MGR>270;

select * from emp13 where comm>350 and mgr>270;

select * from emp13 where salary>=5000 and comm>380;

Select * From Emp13 Where Salary>=6000 And Comm>=400 And Mgr>500;


select * from emp13 where salary>=6000 and comm>=400 or mgr>500;

Alter Table Emp13 Add Job_Status Varchar2(15);


select * from emp13;
Update Emp13 Set Job_Status='Permanent' Where Salary>6000 And Comm>=400 And
Mgr>500;
select * from emp13;

Update Emp13 Set Job_Status='Temporary' Where Salary<6000 And Comm<400 And


Mgr<500;
select * from emp13;

Update Emp13 Set Job_Status='Not decided' Where Salary<5000 And Comm>300 And
Mgr>250 And Job_Status Is Null;

select * from emp13;

SELECT EMPNO,ENAME,CITY,JOB,SALARY FROM EMP13 WHERE MGR>270 AND comm>450;

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.

SELECT EMPNO,ENAME,CITY,JOB,SALARY FROM EMP13 WHERE MGR>370 or comm>450;

eg: SQL> select empno,ename,city,job,salary,mgr from emp13 where salary>7000 or


mgr>500;

select * from emp13 where salary>7000 and comm>400 or mgr>200;

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.

select * from emp13 where city !='BOMBAY';

eg: SQL> SELECT EMPNO,ENAME,CITY,JOB FROM EMP13 WHERE CITY NOT


IN('HYDERABAD','BANGLORE');

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;

ENO ENAME CITY SAL


---------- -------------------- ------------ ----------
109 MAZHAR HYDERABAD 7003
104 SAJID SHIMLA 13433
SELECT * FROM EMP13;

select empno,ename,job,salary,HIREDATE from emp13 where hiredate between '01-JAN-


2013' AND '31-DEC-2015';

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;

Pattern Matching(LIKE operator): The LIKE predicate allows for a comparison of


one string value with another string value, which is not identical. This is
achieved with (% for matching any string and _ matches only single character).

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%';

The Oracle Table 'DUAL':


Dual is a small Oracle worktable, which consists of only one row and one column,
and contains the value x in that column.

SQL> select 2*2 from dual;

PNo: 27
TECH IQ Technologies

2*2
----------
4

SQL> select sysdate from dual;

SYSDATE
---------
30-SEP-15

SQL>SELECT SYSTIMESTAMP FROM DUAL;

SQL>select user,uid,sysdate,systimestamp,dummy from dual;

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).

Oracle functions can be classified depending upon whether they operate on a


single row or a group of rows retrieved from a table.

Group Functions(Aggregate Function): Functions that act on a set of values are


called as Group Functions.

Scalar Functions: Functions that act on only one value at a time are called as
Scalar Functions.

Functions can be classified corresponding to different data types as:


String Functions :Work for String Data type
Numeric Functions :Work for Number Data type
Conversions Functions :Work for Conversion of one Data type to another
Date Functions :Work for Date Data type

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

SELECT LOWER(CITY) FROM EMP13 WHERE CITY='NEW DELHI';

SQL> update emp13 set ename=lower(ename) where salary<5000;

PNo: 29
TECH IQ Technologies
2. INITCAP
SQL> SELECT INITCAP('ABDUL MAJEED') "Title Case" FROM DUAL;

Title Case
------------
Abdul Majeed

update empl13 set ename=initcap(ename) where salary>7000;

3. UPPER
SQL> SELECT UPPER('junaid touseef') "Upper Case" from dual;

Upper Case
--------------
JUNAID TOUSEEF

SELECT UPPER(CITY) FROM EMP13 WHERE CITY='NEW DELHI';

4. SUBSTR
SQL> SELECT SUBSTR('NEW DELHI',5,9)"Substring" from dual;

Subst
-----
DELHI

UPDATE EMPLOYEE SET ENAME=SUBSTR(ENAME,4,7);

5. LENGTH
SQL> SELECT LENGTH('SECUNDERABAD')"Length" FROM DUAL;

Length
----------
12

SQL> select eno,ename,length(ename) from employee where salary>7000;

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;

select trim(trailing '#' from 'Sachin##') from dual;

select trim(both '#' from '##Sachin####' ) from dual;


LTRIM
SQL> SELECT LTRIM('NISHA','N') "Left" from dual;

Left
----
ISHA

PNo: 30
TECH IQ Technologies

SQL> UPDATE EMP13 SET ENAME=LTRIM(ENAME,'J') ;


UPDATE EMP13 SET ENAME=LTRIM(ENAME,'A') where eno in(1,5);

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

SQL> update employee set ename=rpad(ename,12,'*') where ename='RAHMAN';

UPDATE emp13 set ename=rpad(ename,length(ename)+4,' Mgr') where job='MANAGER';

select * from emp13;


update emp13 set job_status='RETIRED' where job_status is null;

select * from emp13;

update emp13 set ename=rpad(ename,length(ename)+5,' Retd') where


job_status='RETIRED';

10.REPLACE
SQL> select replace('NEW DELHI','delhi') from dual;

NEW DELHI

//replacing ‘BOMBAY’ with ‘MUMBAI’


update emp13 set CITY=replace('MUMBAI',CITY) WHERE CITY='BOMBAY';

//Replacing Middle name


update emp13 set ename=replace(ename,'KHAN','PATHAN') ;
update emp13 set ename=replace(ename,'SHARMA','VERMA');

ALTER TABLE EMP13 ADD COMPANY VARCHAR2(30);

UPDATE EMP13 SET COMPANY='SUN MICROSYSTEM' WHERE EMPNO IN (1,3,5,7,9);

PNo: 31
TECH IQ Technologies
UPDATE EMP13 SET COMPANY='MICRO SOFT' WHERE EMPNO IN (2,4);

UPDATE EMP13 SET COMPANY='GOOGLE' WHERE EMPNO IN (6,8);


SELECT * FROM EMP13;

UPDATE EMP13 SET COMPANY=REPLACE('ORACLE CORP',COMPANY) WHERE COMPANY IN('SUN


MICROSYSTEM');

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:

drop table e1;


create table e1(eno number,ename varchar2(12),ADDRESS varchar2(20));
insert into e1 values(1,null,'GREEN LAND');
insert into e1 values(2,'ASLAM',NULL);
insert into e1 values(3,'DRAVID',NULL);
insert into e1 values(4,NULL,'TURNING STREET');
select ENO,nvl(ename,'No name found'),nvl(address,'Not Available') from e1;

concat(): This SQL function is use to combine two string values.


SQL>select CONCAT('COUNTRY ',UPPER(lower('NEW ZEALAND'))) FROM DUAL;
Update Emp13 Set Ename=Concat(Substr(Ename,1,6),' s/o Ahmed') Where Empno=8;

trunc(): This function is use to keep only limited digits after decimal point.
//without trunc() function
select (5000/66) from dual;

//with trunc() function


select trunc(5000/66,3) 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;

ALTER TABLE EMP13 ADD(CURRENCY VARCHAR2(15));


select * from emp13;

UPDATE EMP13 SET CURRENCY = CONCAT('$',trunc(salary/66,2));


select * from emp13;

//Adding 10 dollars
update emp13 set
currency=concat('$',to_char(to_number(substr(currency,2,length(currency)-
1)+10)));

select * from emp13;

2. TO_CHAR(Number Conversion): To convert number value to character format

SQL> SELECT TO_CHAR(17145,'$099,999')"Char" from dual;

PNo: 33
TECH IQ Technologies
Char
---------
$017,145

3. TO_CHAR(date conversion)

SQL> SELECT TO_CHAR(HIREDATE,'Month DD,YYYY')"New Date Format" from emp13 where


eno=7;

New Date Format


-----------------
April 16,2014

ALTER TABLE EMP13 add(SALINDOL VARCHAR2(100));

SELECT * FROM EMP13;

UPDATE EMP13 SET SALINDOL=SALARY/66;

UPDATE EMP13 SET SALINDOL=LPAD(SALARY,LENGTH(SALARY)+1,'$');

SELECT * FROM EMP13;

// UPDATE EMP13 SET


SALINDOL=TO_CHAR(TO_NUMBER(SUBSTR(SALINDOL,2,LENGTH(SALINDOL)-1)/63));

//UPDATE EMP13 SET SALINDOL=LPAD(SALINDOL,LENGTH(SALINDOL)+1,'$');

SELECT * FROM EMP13;

UPDATE EMP13 SET SALINDOL=TO_CHAR(TO_NUMBER(SUBSTR(SALINDOL,2,4))+10);


UPDATE EMP13 SET SALINDOL=TO_CHAR(TO_NUMBER(SUBSTR(SALINDOL,2,LENGTH(SALINDOL)-
1))+10);
SELECT * FROM EMP13;

UPDATE EMP13 SET SALINDOL=LPAD(SALINDOL,LENGTH(SALINDOL)+1,'$');

SELECT * FROM EMP13;

Date Conversion Functions:


The DATE data type is used to store date and time information. The DATE data type
has special properties
associated with it. It stores information about century, year, month, day, hour,
minute and second for
each date value.

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

SQL> SELECT NEXT_DAY('29-SEP-2015','FRIDAY')"NEXT DAY" FROM DUAL;

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.

Pseudo-Column LEVEL: It returns a level of row in a tree-strucutured query. It


returns level 1 for a root node, 2 for children, etc. It can be used in 'SELECT'
statement where CONNECT BY is used.

drop table emp77;

create table emp77(eno number(3),ename varchar2(12));

insert into emp77 values(1,'SAMI');


insert into emp77 values(2,'RAKESH');
insert into emp77 values(3,'ALI');
insert into emp77 values(4,'ANIL');
insert into emp77 values(1,'SAMI');
insert into emp77 values(2,'RAKESH');

SELECT * FROM EMP77;

DELETE FROM EMP77 WHERE ENO=1;


DELETE FROM EMP77 WHERE ENO=2;

PNo: 35
TECH IQ Technologies
//so both original and duplicate deleted, but we want to delete only duplicate

//Again create table and insert values


drop table emp77;

create table emp77(eno number(3),ename varchar2(12));

insert into emp77 values(1,'SAMI');


insert into emp77 values(2,'RAKESH');
insert into emp77 values(3,'ALI');
insert into emp77 values(4,'ANIL');
insert into emp77 values(1,'SAMI');
insert into emp77 values(2,'RAKESH');

Pseudo-Column ROWID: It gives the location in the database where row is


physically stored.

select rowid,eno,ename from emp77;

ROWID ENO ENAME


------------------ ---------- ------------
AAADycAABAAAKyiAAA 1 SAMI
AAADycAABAAAKyiAAB 2 RAKESH
AAADycAABAAAKyiAAC 3 ALI
AAADycAABAAAKyiAAD 4 ANIL
AAADycAABAAAKyiAAE 1 SAMI
AAADycAABAAAKyiAAF 2 RAKESH

//Deleting duplicate row using rowid() function


delete from emp77 where rowid='AAADycAABAAAKyiAAE';

SELECT * FROM EMP77;

select rowid,eno,ename from emp77;

ROWID ENO ENAME


------------------ ---------- ------------
AAADycAABAAAKyiAAA 1 SAMI
AAADycAABAAAKyiAAB 2 RAKESH
AAADycAABAAAKyiAAC 3 ALI
AAADycAABAAAKyiAAD 4 ANIL
AAADycAABAAAKyiAAF 2 RAKESH

Deleting the duplicate row value from the table.


----------------------------------------------------------
drop table emp;

create table emp(eno number(5),ename varchar2(12));

insert into emp values(1,'AHMED');


insert into emp values(2,'BILAL');
insert into emp values(3,'SURESH');
insert into emp values(1,'AHMED');

PNo: 36
TECH IQ Technologies

SELECT * FROM EMP;

ENO ENAME
---------- ------------
1 AHMED
2 BILAL
3 SURESH
1 AHMED

SQL> SELECT ROWID,ENO,ENAME FROM EMP;

ROWID ENO ENAME


------------------ ---------- ------------
AAADhuAABAAAKUaAAA 1 AHMED
AAADhuAABAAAKUaAAB 1 AHMED
AAADhuAABAAAKUaAAC 2 SURESH
AAADhuAABAAAKUaAAD 2 HAMED

SQL> DELETE FROM EMP WHERE ROWID='AAADhuAABAAAKUaAAA';

SQL> SELECT * FROM EMP;

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.

Example: Displaying the sequence of rows retrieved

SELECT ROWNUM,EMPNO FROM EMP13;

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.

Example: Displaying SCN with row which is last modified

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

SQL> SELECT SCN_TO_TIMESTAMP(ORA_ROWSCN), ename from emp13;

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

Example : Displaying the current date and time

SQL> select sysdate,ename from emp_company;

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.

Example : Identifying the user

SQL> SELECT UID FROM DUAL;

UID
----------

PNo: 38
TECH IQ Technologies
5

Pseudo-Column USER
-------------------------
It is used for retrieving user name.

Example: Retrieving user name

SQL> Select user,ename from emp13;

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.

Types Data Constraints:


There are two types of data constraints that can be applied to data being
inserted into an Oracle table.

1. First type of constraint is called an i/o constraint (input/output). This type


constraint determines the speed at wchich data can be inserted or extracted from
an Oracle table.

2. The CHECK Constraint:


-----------------------------
Business Rule validations can be applied to a table column by using CHECK
constraint.
CHECK constraints must be specified as a logical expression that evaluates either
to TRUE or FALSE.

I/O constraints consists of 5 constraints:


--------------------------------------------------
1. Not Null
2. Unique
3. Default
4. Primary key (parent key)

PNo: 39
TECH IQ Technologies
5. Foreign key (child key)

NULL value concept:


NULL means nothing is stored in a particular field in the table.
Often there may be records in a table that do not have values for every field.
A NULL value is different from zero (0) because zero is a value but NULL is not a
value but it is just NULL.

Principles of NULL values:


->Setting a NULL value is appropriate when the actual value is unknown, or when
a value would not be meaningful.
->A NULL value will evaluate to NULL in any expression e.g. NULL multiplied by 10
is NULL.
->NULL value can be inserted into columns of any data type.
->If the column has a NULL value, Oracle ignores the UNIQUE, FOREIGN KEY, CHECK
constraints that may be attached to the column.

drop table emp13;

Create table emp13(empno number(3),ename varchar2(12),


job varchar2(12),city varchar2(12),hiredate date,salary number(5),comm
number(3),mgr number(3),
address varchar2(15) default 'N/A');

insert into emp13 values(1,'SANDEEP','ENG','HYDERABAD',NULL,


6000,473,274,'LNG');

insert into emp13 values(2,'PRAKASH','DOCTOR','BANGLORE',


'03-NOV-2005',NULL,374,242,'DSNR');

insert into emp13 values(3,'SALIM',NULL,'NEW DELHI','02-MAY-


2008',7384,384,884,'KBH');

insert into emp13 Values(4,'JUNAID','PILOT','BOMBAY','18-APR-


2009',3848,273,384,'KTI');

insert into emp13 (empno,ename,job,city,hiredate,salary,comm,mgr)values(5,


'NAGENDER','DOCTOR',NULL,'18-APR-2009',5478,273,384);

insert into emp13 values(6,'SURESH','MANAGER','MADRAS','15-FEB-


2005',NULL,374,749,'MGRD');

insert into emp13 values(7,'SALMAN','MANAGER','NEW DELHI','15-AUG-


2005',4555,NULL,653,'HNE');

insert into emp13 (empno,ename,job,city,hiredate,salary,comm,mgr)values(8,


'KARTHIK','ENG','BANGLORE','26-OCT-2007',8539,371,451);

insert into emp13 values(9,'SAJID','MANAGER','','15-AUG-


2005',4555,NULL,653,'ADARCH');

insert into emp13 (empno,ename,job,city,hiredate,salary,


comm,mgr)values(10,'JUNAID',NULL,'BOMBAY','18-APR-2009',3848,273,384);

PNo: 40
TECH IQ Technologies

insert into emp13 Values(&empno,'&ename','&job','&city',


'&hiredate',&salary,&comm,&mgr);

SQL> desc emp13


Name Null? Type
----------------------------------------- -------- -------------
EMPNO NUMBER(3)
ENAME VARCHAR2(12)
JOB VARCHAR2(12)
CITY VARCHAR2(12)
HIREDATE DATE
SALARY NUMBER(5)
COMM NUMBER(3)
MGR NUMBER(3)
ADDRESS VARCHAR2(20)

Displaying rows where salary row is having NULL values


SQL> SELECT EMPNO,ENAME,SALARY FROM EMP13 WHERE SALARY IS NOT NULL;

SELECT * FROM EMP13 WHERE JOB IS NULL;


select empno,ename from emp13 where job is not null;

select * from emp13 where job is not null;

select * from emp13 where hiredate is not null;

select * from emp13 where address='N/A';

NOT NULL Constraint:


When a column is defined as not null, then that column becomes a mandatory
column.
Means it is compulsary or must for the user to enter some text into that field.

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.

Sql>drop table client_master;

Sql>CREATE TABLE CLIENT_MASTER(CLIENT_NO VARCHAR2(7) NOT NULL,


NAME VARCHAR2(10) NOT NULL,ADDRESS1 VARCHAR2(12) NOT NULL,
ADDRESS2 VARCHAR2(10) NOT NULL,CITY VARCHAR2(10),
STATE VARCHAR2(10),PINCODE NUMBER(6),BAL_DUE NUMBER(7,2));

Sql>insert into client_master values(’C001’,’SURESH’,’A12/D’,


'BLOCK 1’,’SHIMLA’,’HP’,23049,356);

//Cannot insert NULL value into NOT NULL column


Sql>insert into client_master values(NULL,’RAJESH’,’QUART/1’,
'BLOCK U’,’SHIMLA’,’HP’,5049,356);

insert into client_master values('&client_no','&name',


'&address1','&address2','&city','&state',&pincode,&bal_due);

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.

SQL> drop table client_master1;

SQL>create table client_master1(client_no varchar2(6) UNIQUE,


name varchar2(12),address1 varchar2(12), address2 varchar2(12),
city varchar2(15), state varchar2(12),pincode number,
bal_due number(6,2));

SQL>insert into client_master1 values('1','ahmed','dsnr',


'satoshngr','Hyderabad','AP',50003,300);

SQL>insert into client_master1 values('2','SAMI','LDRW',


'LB SPACE','Hyderabad','AP',50003,300);

SQL>insert into client_master1 values('2','JUNAID','DMRL',


'SECTOR 1','Agra', 'UP',20003,400);

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;

I/O constraint is further divided into two constraints:


Primary Key Constraints
Foreign Key Constraints

The PRIMARY KEY Constraint:

PNo: 42
TECH IQ Technologies

Primary Key concepts:


A primary key is one or more column(s) in a table used to uniquely identify each
row in the table.
A primary key column in a table has special attributes:
-> It defines the column as a mandatory column i.e. the column cannot be left
blank. Here the NOT NULL attribute is active.
-> The data held across the column MUST be UNIQUE.
-> The only function of a primary key in a table is to uniquely identify a row.
-> It will not accept not even single null value
->Only 1 primary key is allowed per table
PRIMARY KEY constraint defined at the column level:

Syntax:
column-name data-type(size) PRIMARY KEY

Example:
Create a table client_master where the column client_no is its primary key.

PRIMARY KEY constraint defined at the column level:


Syntax:
column-name data-type(size) PRIMARY KEY
Example:
Create a table client_master where the column client_no is its primary key.

DROP TABLE CLIENT_MASTER;

CREATE TABLE CLIENT_MASTER(CLIENT_NO VARCHAR2(7) PRIMARY KEY,


NAME VARCHAR2(10), ADDRESS1 VARCHAR2(12),ADDRESS2 VARCHAR2(10),
CITY VARCHAR2(10),STATE VARCHAR2(10),
PINCODE NUMBER(6),BAL_DUE NUMBER(7,2));

//Inserting data
INSERT INTO CLIENT_MASTER VALUES('C1','AHMED','ST COLONY',
'KOTHI','HYDERABAD','AP',500043,564.23);

INSERT INTO CLIENT_MASTER VALUES('C2','SALIM','BANK ST',


'MOGHALPURA','BANGALORE','KAR',560021,455.23);

INSERT INTO CLIENT_MASTER VALUES('C1','JUNAID','BT STREET',


'SULTAN COL','HYDERABAD','AP',500043,564.23);

PRIMARY KEY constraint defined at the table level:


Syntax:
PRIMARY KEY(column-name[,column-name,...])

//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.

DROP TABLE SALES_ORDER_DETAIL;

PNo: 43
TECH IQ Technologies

create table sales_order_detail(detlorder_no varchar2(6), product_no


varchar2(6),qty_ordered number(8),qty_disp number(8),product_rate
number(8),primary key(detlorder_no,product_no));

Table created

//Example table for 'composite primary key'

drop table t1;

create table t1(eno number,ename varchar2(15),sysid number, primary


key(eno,sysid));

Insert Into T1 Values(1,'SAMI',101);


Insert Into T1 Values(2,'SACHIN',102);
Insert Into T1 Values(1,'RAHUL',103);
Insert Into T1 Values(1,'GANGULY',101);
Insert Into T1 Values(3,'PRADEEP',101);
Insert Into T1 Values(2,'PRASAD',102);

SELECT * FROM T1;

Disabling Primary Key


-----------------------
Some implementations allow you to disable constraints. Instead of permanently
dropping a constraint from the database, you may want to temporarily disable the
constraint and then enable it later.

Sql>DROP table emp2;

Create table emp2 (eno number(5) PRIMARY KEY,


ename varchar2(15),Job varchar2(15),salary number(7));

Insert into emp2 values(1,'SAMI','MANAGER',4567);


Insert into emp2 values(2,'SURESH','PRESIDENT',4956);

//Disabling PRIMARY KEY of 'ENO'


Sql>Alter table emp2 disable primary key;

//It now accepts duplicate value for 'ENO' column


sql>Insert into emp2 values(2,'SURESH','PRESIDENT',4956);

//Enabling primary key


Sql> Alter table emp2 enable primary key;

Dropping Primary key


Some implementations may provide shortcuts for dropping certain constraints. For
example, to drop the primary key constraint for a table in Oracle, you can use
the following command:

drop table emp1;

PNo: 44
TECH IQ Technologies
Create table emp1 (eno number(5) PRIMARY KEY, ename varchar2(15),
Job varchar2(15),salary number(7));

Insert into emp1 values(1,'SAMI','MANAGER',4567);


Insert into emp1 values(2,'SURESH','PRESIDENT',4956);

ALTER TABLE EMP1 DROP PRIMARY KEY;


Insert into emp1 values(1,'SAMI','MANAGER',4567);
Insert into emp1 values(2,'SURESH','PRESIDENT',4956);

FOREIGN KEY Constraint:


FOREIGN KEY Constraint:
Foreign keys represent relationships between tables. A foreign key is a column
whose values are derived from
the primary key or unique key of some other table.

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.

Note: Use ON DELETE CASCADE.

Principle of Foreign Key/References constraint:


->Rejects an INSERT or UPDATE of a value, if a corresponding value does not
currently exist in the master key table.
->Must reference a PRIMARY KEY or UNIQUE KEY column(s) in primary table.
->Requires that the FOREIGN KEY column(s) and the CONSTRAINT column(s) have
matching data types.

FOREIGN KEY constraint defined at the column level:

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;

create table dept(dept_name varchar2(10),dept_id number primary key,location


varchar2(20));
INSERT INTO DEPT VALUES('SALES',101,'NEW DELHI');
INSERT INTO DEPT VALUES('HEALTH',201,'MUMBAY');
INSERT INTO DEPT VALUES('ACCOUNTS',301,'KOLKATA');
INSERT INTO DEPT VALUES('EDUCATION',401,'BANGALORE');
INSERT INTO DEPT VALUES('RESEARCH',701,'HYDERABAD');
INSERT INTO DEPT VALUES('FIRE',801,'GUWAHATI');
INSERT INTO DEPT VALUES('POLICE',901,'SHIMLA');

select * from dept;

PNo: 45
TECH IQ Technologies

Table for Foreign key


-----------------------
DROP TABLE EMP;

create table emp(eno number primary key,ename varchar2(10),


city varchar2(10),job varchar2(15),salary number(10),hiredate date,dept_id
number,
constraint e1 FOREIGN KEY(dept_id) references dept(dept_id));

insert into emp values(1,'SAMI','HYDERABAD','MARKETING',7896,'04-apr-2014',101);


insert into emp values(2,'ALI','BANGALORE','DOCTOR',6873,'28-aug-2013',201);
insert into emp values(3,'HAMEED','BOMBAY','ACCOUNTANT',4598,'23-nov-2002',301);
Insert into emp values(4,'JUNAID','MADRAS','TEACHER',9381,'15-feb-2015',401);
insert into emp values(5,'KALEEM','DELHI','DOCTOR',7792,'20-jan-2014',501);
insert into emp values(6,'FARID','HYDERABAD','MANAGER',5397,'08-oct-2014',601);
insert into emp values(7,'SURESH','NAGPUR','BUSINESS',3986,'19-may-2015',201);
insert into emp values(8,'PRAKASH','HYDERABAD','DOCTOR',8391,'01-jul-2015',201);
insert into emp values(9,'SACHIN','BOMBAY','SPORTS',6844,'03-dec-2014',101);
insert into emp values(10,'AMBANI','NAGPUR','BUSINESS',9481,'29-sep-2015',101);

select * from dept;


select * from emp;

//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;

//Now, try to delete data from 'dept' table


delete from dept where dept_id=201;

//Result of the above query


//We cannot delete any deptid=201 as it is referenced by foreign table by
eno(2,7,8)

Apply on 'ON DELETE CASCADE' on emp table or foreign table


---------------------------------------
DROP TABLE EMP;

create table emp(eno number primary key,ename varchar2(10),


city varchar2(10),job varchar2(15),salary number(10),HIREDATE DATE,dept_id
number,constraint e1 FOREIGN KEY(dept_id) references dept(dept_id) ON DELETE
CASCADE);

insert into emp values(1,'SAMI','HYDERABAD','MARKETING',7896,'04-apr-2014',101);


insert into emp values(2,'ALI','BANGALORE','DOCTOR',6873,'28-aug-2013',201);
insert into emp values(3,'HAMEED','BOMBAY','ACCOUNTANT',4598,'23-nov-2014',301);
Insert into emp values(4,'JUNAID','MADRAS','TEACHER',9381,'15-feb-2015',401);
insert into emp values(5,'KALEEM','DELHI','DOCTOR',7792,'20-jan-2015',501);
insert into emp values(6,'FARID','HYDERABAD','MANAGER',5397,'08-oct-2015',601);
insert into emp values(7,'SURESH','NAGPUR','BUSINESS',3986,'19-may-2015',201);
insert into emp values(8,'PRAKASH','HYDERABAD','DOCTOR',8391,'01-jul-2015',201);
insert into emp values(9,'SACHIN','BOMBAY','SPORTS',6844,'03-dec-2014',101);
insert into emp values(10,'AMBANI','NAGPUR','BUSINESS',9481,'29-sep-2014',101);

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;

//Now, we can delete dept_id=201


delete from dept where dept_id=201;

select * from dept;


select * from emp;

Retrieving Data from 3 tables


-------------------------------
drop table emp_loan;

create table emp_loan(eno number,ename varchar2(15),loan_amount


number(7),loan_date date,foreign key(eno) references emp(eno) ON DELETE CASCADE);

insert into emp_loan values(3,'HAMEED',1300,'12-jun-2015');


insert into emp_loan values(4,'JUNAID',4500,'02-FEB-2014');
insert into emp_loan values(7,'SURESH',900,'15-NOV-2014');
insert into emp_loan values(10,'AMBANI',3691,'23-JUL-2015');
insert into emp_loan values(12,'JAFFER',3000,'04-OCT-2015');

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;

Retrieving Data from 4 tables


--------------------------------
drop table emp_promotion;
create table emp_promotion(eno number(3),ename varchar2(20),promotion
varchar2(25),
bonus number(5),promotion_date date,constraint orl foreign key(eno) references
emp(eno) ON DELETE CASCADE);

insert into emp_promotion values(4,'JUNAID','VICE_PRINCIPAL',3000,'22-JUN-2015');


insert into emp_promotion values(7,'SURESH','ASSOCIATION_PRESIDENT',2500,'15-JAN-
2015');
insert into emp_promotion values(3,'HAMEED','CHEIF_ACCOUNTANT',4000,'04-SEP-
2014');
insert into emp_promotion values(10,'AMBANI','COMPANY_CEO',6059,'07-JUL-2015');

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;

//Retrieving data from 5 tables


-----------------------------------
drop table Emp_projects;
create table Emp_projects(eno number(5),ename varchar2(15),projects
number(3),starting_date date,end_date date,dept_id number(3),foreign key (eno)

PNo: 47
TECH IQ Technologies
references emp(eno),foreign key (dept_id)references dept(dept_id) ON DELETE
CASCADE);
desc Emp_projects

INSERt into Emp_projects values(3,'HAMEED',3,'20-MAY-2014','20-MAY-2018',301);


INSERt into Emp_projects values(10,'AMBANI',2,'01-JAN-2013','31-DEC-2016',101);

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;

//Again delete any record from dept table


Sql> delete from dept where dept_id=101;

select * from dept;


select * from emp;
select * from emp_loan;
select * from emp_promotion;
select * from emp_projects;

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);

drop table dept;


create table dept (dno number(3),dname varchar2(15), location varchar2(2),
primary key(dno,dname));

drop table emp;


create table emp(eno number,ename varchar2(15),job varchar2(15),salary
number(7),dno number,dname varchar2(15), foreign key(dno,dname) references
dept(dno,dname));

2. Second type constraint is called business rule constraint.

The CHECK Constraint:

Business Rule validations can be applied to a table column by using CHECK


constraint.
CHECK constraints must be specified as a logical expression that evaluates either
to TRUE or FALSE.

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.

DROP TABLE CLIENT_MASTER2;

create table client_master2 (client_no varchar2(7) constraint a


CHECK(client_no like 'C%'),
name varchar2(15) constraint b CHECK(name=upper(name)),
address1 varchar2(15), address2 varchar2(15),
city varchar2(15) constraint c CHECK(city
IN('Delhi','Mumbai','Kolkata','Chennai')),
state varchar2(15));

insert into client_master2 values('C1001','SAMI','1-2,KOTI','SHANTI


SEC','Mumbai','MAH');
insert into client_master2 values('C1002','RAMESH','3-2,M.G.ROAD','BIRDS
COL','Delhi','Delhi');
insert into client_master2 values('c1003','SADIQ','77,TREE RD','SEVEN
HILLS','Kolkata','West Bengal');
insert into client_master2 values('C1004','pradeep','4/A,K.R Apts','Seven
Wonders','Chennai','Tamil Nadu');

insert into client_master2 values('&client_no','&name','&address1',


'&address2','&city','&state');

//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;

//Another example using 'check constraint


Drop table Election;
create table Election(idno number(5),person_name varchar2(15),area
varchar2(20),age number, check(age>=18));

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);

Another Example on Primary and Foreign key relationship

SQL> desc patient


Name Null? Type
----------------------------------------- -------- ------------------------

PNO NOT NULL NUMBER(4)


PNAME VARCHAR2(10)
GENDER CHAR(1)
ADDRESS VARCHAR2(10)
MOBILE NUMBER(10)

SQL> desc register


Name Null? Type
----------------------------------------- -------- ------------------------
PNO NUMBER(5)
NAME VARCHAR2(7)
DISEASE VARCHAR2(15)
DOCTOR VARCHAR2(15)
WARDNO NUMBER(4)
BEDNO NUMBER(4)

SQL> desc billing


Name Null? Type
----------------------------------------- -------- ------------------------

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)

GROUPING DATA FROM TABLES IN SQL


GROUP BY: This GROUP BY is another section of the 'select' statement. This optional
clause tells Oracle
to group rows based on distinct values that exist for specified columns i.e. it creates a
data set, containing
several sets of records grouped together based on a condition.

Example 1
----------

PNo: 50
TECH IQ Technologies
DROP TABLE EMP;

create table emp(empno number primary key,ename varchar2(10),


city varchar2(10),job varchar2(15),sal number(10),hiredate date,deptno
number(5));

insert into emp values(1,'SAMI','HYDERABAD','MARKETING',7896,'04-apr-2014',101);


insert into emp values(2,'ALI','BANGALORE','DOCTOR',6873,'28-aug-2013',201);
insert into emp values(3,'HAMEED','BOMBAY','ACCOUNTANT',4598,'23-nov-2002',301);
Insert into emp values(4,'JUNAID','MADRAS','TEACHER',9381,'15-feb-2015',401);
insert into emp values(5,'KALEEM','DELHI','DOCTOR',7792,'20-jan-2014',501);
insert into emp values(6,'FARID','HYDERABAD','MANAGER',5397,'08-oct-2014',601);
insert into emp values(7,'SURESH','NAGPUR','BUSINESS',3986,'19-may-2015',201);
insert into emp values(8,'PRAKASH','HYDERABAD','DOCTOR',8391,'01-jul-2015',201);
insert into emp values(9,'SACHIN','BOMBAY','SPORTS',6844,'03-dec-2014',101);
insert into emp values(10,'AMBANI','NAGPUR','BUSINESS',9481,'29-sep-2015',101);

1.List The Department Numbers And Number Of Employees In Each Department ?


sql> select deptno, count(*) from emp group by deptno ;

2.List the jobs and number of employees in each job ?


sql> select job, count(*) from emp group by job;

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.

6. List The Empno,Ename,Sal In Ascending Order By Salary


sql> select empno,ename,sal from emp order by sal;

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));

insert into customer(cno,cname,product,qty,price,purchase_date) values

(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;

SELECT * from customer;


select * from customer order by cno;
update customer set bill=qty*price;
select * from customer order by cno;
update customer set discount=(bill*0.15);
select * from customer order by cno;
update customer set final_amt=bill-discount;

select * from customer order by cno;

select cno,cname,sum(bill) from customer group by cno,cname order by cno;

select cno,cname,sum(bill),sum(discount),sum(final_amt) from customer group by cno,cname

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;

SQL> SELECT * FROM SALES_ORDER7;

PNO PNAME QUANTITY


---------- ------------ ----------
1 MOBILE 7
2 KEYBOARD 10
3 MOUSE 5
4 CAP 20
5 BALL 12
2 BOOK 15
2 PEN 12

PNo: 53
TECH IQ Technologies
1 SHOES 7
3 BIKE 9
6 BAG 14
1 CHAIR 14

SQL> SELECT * FROM SALES_ORDER7 ORDER BY PNO;

PNO PNAME QUANTITY


---------- ---------- ----------
1 MOBILE 5
1 BAG 5
1 MOUSE 6
1 KEYBOARD 4
2 PEN 3
2 MOBILE 6
3 BAG 6
3 BOOK 7
3 PEN 8
4 KEYBOARD 5
4 BOOK 3

PNO PNAME QUANTITY


---------- ---------- ----------
4 BIKE 4
5 CHAIR 4
5 CAP 4
6 PEN 7

select * from sales_order7 order by quantity desc;

SQL> select pno,sum(quantity) "Total Qty Ordered" from sales_order7 GROUP BY PNO;

PNO Total Qty Ordered


---------- -----------------
1 20
6 7
2 9
4 12
5 8
3 21

select pno,sum(quantity) from sales_order7 GROUP BY pno order by pno;

CREATING TABLE EMP_COMPANY


-----------------------------------------
drop table emp_company;

create table emp_company(ename varchar2(12),cname varchar2(12),


salary number(5),doj date);

insert into emp_company values('SURESH','WIPRO',


67953,'12-OCT-2009');
insert into emp_company values('MAHESH','SATYAM',
39489,'05-JUN-2008');

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');

insert into emp_company values('PRAKASH','WIPRO',


39948,'18-MAR-2006');
insert into emp_company values('RAJU','INFOSYS',
43959,'24-JAN-2005');
insert into emp_company values('PRASAD','SATYAM',
39839,'23-FEB-2005');
insert into emp_company values('AMAR','ORACLE',
48949,'16-MAY-2005');
insert into emp_company values('KUMAR','WIPRO',
49394,'17-SEP-2006');
insert into emp_company values('SHEKHAR','INFOSYS',
83894,'23-APR-2004');

SQL> SELECT * FROM EMP_COMPANY;

ENAME CNAME SALARY DOJ


------------ ------------ ---------- ---------
SURESH WIPRO 67953 12-OCT-09
MAHESH SATYAM 39489 05-JUN-08
PRADEEP VIRTUSA 29439 29-AUG-04
SANDEEP INFOSYS 38484 10-APR-02
PRAKASH WIPRO 39948 18-MAR-06
RAJU INFOSYS 43959 24-JAN-05
PRASAD SATYAM 39839 23-FEB-05
AMAR ORACLE 48949 16-MAY-05
KUMAR WIPRO 49394 17-SEP-06
SHEKHAR INFOSYS 83894 23-APR-04

Example 4: Displaying the names of companies and the maximum salary in that
company.

SQL> select cname,max(salary) from emp_company group by cname;

CNAME MAX(SALARY)
------------ -----------
ACC 8000
TATA 5003
TCS 9493
WIPRO 6940
CMC 1800

Example 3: Calculate the number of employees for each company.

SQL> select cname,count(ename) from emp_company group by cname;

CNAME COUNT(ENAME)

PNo: 55
TECH IQ Technologies
------------ ------------
ACC 3
TATA 3
TCS 3
WIPRO 1
CMC 2

SQL> select cname,max(salary) from emp_company group by cname;

CNAME MAX(SALARY)
------------ -----------
ACC 8000
TATA 5003
TCS 9493
WIPRO 6940
CMC 1800

SQL> select * from emp_company where cname='INFOSYS';

ENAME CNAME SALARY DOJ


------------ ------------ ---------- ---------
ANIL ACC 1500 01-MAY-04
AJAY ACC 8000 30-APR-04
AMOL ACC 2394 17-MAR-02

SQL> SELECT SUM(SALARY) FROM EMP_COMPANY WHERE CNAME='INFOSYS';

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;

PNO Total Qty


---------- ----------
5 8
3 21

SQL> select pno,sum(quantity) "Total Qty" from sales_order GROUP BY pno HAVING
pno=1 or pno=4;

PNO Total Qty


---------- ----------
1 20
4 12
Example 2: Displaying the companies having more than one employee

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'.

SQL> select cname,avg(salary) from emp_company where cname !='INFOSYS' group by


cname;
CNAME AVG(SALARY)
------------ -----------
TATA 3348.66667
TCS 7810
WIPRO 6940
CMC 1750
Example 5: Finding the name of companies having average salary more than 6000
SQL> select cname,avg(salary) from emp_company where cname !='INFOSYS' group by
cname having avg(salary)
> 6000;

CNAME AVG(SALARY)
------------ -----------
TCS 7810
WIPRO 6940

DROP TABLE EMPLOYEE;

CREATE TABLE EMPLOYEE(ENAME VARCHAR2(16),CITY VARCHAR2(20),CNAME VARCHAR2(20));

INSERT INTO EMPLOYEE VALUES('SURESH','DELHI','WIPRO');


INSERT INTO EMPLOYEE VALUES('PRAKASH','HYDERABAD','WIPRO');
INSERT INTO EMPLOYEE VALUES('SANDEEP','DELHI','INFOSYS');
INSERT INTO EMPLOYEE VALUES('AMAR','DELHI','ORACLE');
INSERT INTO EMPLOYEE VALUES('SHEKHAR','BANGALORE','INFOSYS');
INSERT INTO EMPLOYEE VALUES('RAJU','DELHI','INFOSYS');

PNo: 57
TECH IQ Technologies
Example 5: Displaying the average salary of company only for employees living in
'Delhi'.

SQL> select cname,avg(e.salary) from emp_company e where e.ename in (select


l.ename from employee l where l.city='DELHI') group by e.cname;

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.

SQL> select cname,sum(salary) from emp_company group by cname;

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.

SQL> with companysalary as(select cname,sum(salary) totalsal from emp_company


group by cname),companyavgsalary as(select avg(totalsal) avgsal from
companysalary) select cname,totalsal from companysalary where totalsal> (select
avgsal from companyavgsalary)
/

CNAME TOTALSAL
------------ ----------
ACC 11894
TCS 23430

ORDER BY clause: With 'ORDER BY' clause, you can order your output using order by
clause.

Example 1: Sorting your output on 'ename'.

SQL> select ename,cname from emp_company order by ename;

Example 2: Displaying the output in descending order

SQL> select ename,cname from emp_company order by 1 desc;

->We can mention multiple columns in 'ORDER BY' clause.

PNo: 58
TECH IQ Technologies

Example: Sorting on cname in ascending order, and if cname is same, then it is


sorted on ename in descending order

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.

A subquery is a SELECT statement which is used in another SELECT statement.


Subqueries are very useful when you need to select rows from a table with a
condition that depends on the data of the table itself. You can use the subquery
in the SQL clauses including WHERE clause, HAVING clause, FROM clause etc.

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.

Types of Sub queries:

There are two types of subqueries in oracle:


• Single Row Subqueries: The subquery returns only one row. Use single row
comparison operators like =, >etc while doing comparisions.
• Multiple Row Subqueries: The subquery returns more than one row. Use multiple
row comparison operators like IN, ANY, ALL in the comparisons.

It can be used by the following commands:

->To insert records in a target table.


->To create tables and insert records in the table created.
->To update records in a target table.
->To provide values for conditions in WHERE,HAVING, IN etc. used with
SELECT,UPDATE and DELETE statements.

Single Row Subquery Examples

1. Write a query to find the salary of employees whose salary is greater than the
salary of employee whose id is 5?

drop table emp1;

create table emp1(eno number,ename varchar2(15),job varchar2(15),manager_name


varchar2(20),
salary number,dept_id number);

insert into emp1 values(1,'JUNAID','PROGRAMMER','SMITH',9583,101);


insert into emp1 values(2,'PRADEEP','ANALYST','SANDEEP',6843,201);
insert into emp1 values(3,'ZAHEER','ACCOUNTANT','AUSTIN',6592,301);
insert into emp1 values(4,'SANDEEP','MANAGER','RAHMAN',9586,401);
insert into emp1 values(5,'HAMED','PROGRAMMER','SMITH',7958,101);

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?

SQL>SELECT DEPT_ID,MIN(SALARY)FROM EMP1 GROUP BY DEPT_ID HAVING MIN(SALARY) >


(SELECT MAX(SALARY) FROM EMP1 WHERE DEPT_ID = 101 );

3. Write a query to list the department names which have at lease one employee?

SQL>select dept_id from emp1 group by dept_id having count(dept_id)>0;

SQL>select count(dept_id) from emp1 group by dept_id having dept_id>0;


SQL>select dept_id,count(dept_id) from emp1 group by dept_id having
count(dept_id)>3;

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?

SQL>SELECT DEPT_ID,MIN(SALARY) FROM EMP1 GROUP BY DEPT_ID HAVING MIN(SALARY) >


( SELECT MAX(SALARY) FROM EMP1 WHERE DEPT_ID = 101 );

Multiple Row Subquery Examples

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?

SQL>SELECT Eno,ename, SALARY,dept_id FROM EMP1 WHERE dept_id!=301 and SALARY IN


(SELECT SALARY FROM EMP1 WHERE DEPT_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?

SQL>select eno,ename,salary,dept_id from emp1 where salary in(select max(salary)


from emp1 group by dept_id);

5. Write a query to find the employees whose manager and department should match
with the employee of id 2,5,9,12,15 ?

SELECT Eno,ename,MANAGER_name, DEPT_ID FROM EMP1


WHERE (MANAGER_name,DEPT_ID) IN ( SELECT MANAGER_name,DEPT_ID FROM EMP1
WHERE Eno IN (2,5,9,12,15) );

//Details of employee who is getting highest salary


SELECT Eno, SALARY FROM EMP1 WHERE SALARY = (SELECT MAX(SALARY) FROM emp1 );

eg: Retrieve all orders placed by a client named 'ALI' from the sales_order
table.

DROP TABLE SALES_ORDER77;

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));

SQL> DESC SALES_ORDER7


Name Null? Type
----------------------------------------- -------- ----------------------------
PRODUCT_NO NUMBER(5)
PRODUCT VARCHAR2(20)
QUANTITY NUMBER(4)
PRICE NUMBER(7)
ORDERNO NUMBER(7)
ORDERDATE DATE
CLIENT_NO VARCHAR2(7)

SQL> DESC CLIENT_MASTER1;

PNo: 61
TECH IQ Technologies

INSERT INTO CLIENT_MASTER1 VALUES('C001','SURESH','DOCTOR');


INSERT INTO CLIENT_MASTER1 VALUES('C002','MAZHAR','MANAGER');
INSERT INTO CLIENT_MASTER1 VALUES('C003','ALI','BUSINESS');
INSERT INTO CLIENT_MASTER1 VALUES('C004','AKBAR','ENGINEER');
INSERT INTO CLIENT_MASTER1 VALUES('C005','PRADEEP',364,'PILOT');

SQL> SELECT * FROM CLIENT_MASTER1;

INSERT INTO SALES_ORDER77 VALUES(100,'BAG',5,470,2,'12-DEC-2014','C001');


INSERT INTO SALES_ORDER77 VALUES(101,'CABLE WIRE',10,340,3,'25-JUN-
2015','C003');
INSERT INTO SALES_ORDER77 VALUES(102,'KEYBOARD',10,400,4,'23-JUL-2014','C004');
INSERT INTO SALES_ORDER77 VALUES(101,'MOBILE',10,3890,5,'16-AUG-2015','C001');
INSERT INTO SALES_ORDER77 VALUES(102,'SHIRT',12,560,6,'17-SEP-2015','C003');
INSERT INTO SALES_ORDER77 VALUES(101,'PERFUMES',12,540,7,'17-OCT-2014','C002');
INSERT INTO SALES_ORDER77 VALUES(102,'HEAD LIGHT',10,350,6,'15-NOV-
2015','C003');
INSERT INTO SALES_ORDER77 VALUES(104,'SCREW DRIVERS,9,120,8,'18-FEB-
2015','COO4');

SQL>Alter table sales_order77 add bill number(9);

SQL>update sales_order77 set bill=quantity*price;

SQL> SELECT * FROM SALES_ORDER77;

SQL> SELECT * FROM CLIENT_MASTER1;

SQL> SELECT * FROM SALES_ORDER77 WHERE CLIENT_NO=(SELECT CLIENT_NO FROM


CLIENT_MASTER1 WHERE NAME='ALI');

SQL> SELECT * FROM CLIENT_MASTER1;

SQL> SELECT * FROM SALES_ORDER77;

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.

CREATING TABLE SALES_ORDER2


----------------------------------------

drop table sales_order2;

CREATE TABLE SALES_ORDER2(DETORDER VARCHAR2(12),


PRODUCT VARCHAR2(15),QTY_ORDER NUMBER(3),QTY_DISP NUMBER(4));

INSERT INTO SALES_ORDER2 VALUES('O10001','P00001',20,15);


INSERT INTO SALES_ORDER2 VALUES('O10001','P00007',30,30);
INSERT INTO SALES_ORDER2 VALUES('O10001','P00006',40,20);
INSERT INTO SALES_ORDER2 VALUES('O10002','P00002',25,24);

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);

SQL> SELECT * FROM SALES_ORDER2;

CREATING TABLE PRODUCT_MASTER1


----------------------------------------

SQL>DROP TABLE PRODUCT_MASTER1;

SQL>CREATE TABLE PRODUCT_MASTer1(PRODUCT VARCHAR2(12),


DESCRIPTION VARCHAR2(15));

INSERT INTO PRODUCT_MASTER1 VALUES('P00001','FLOPPIES');


INSERT INTO PRODUCT_MASTER1 VALUES('P00002','MONITORS');
INSERT INTO PRODUCT_MASTER1 VALUES('P00003','MOUSE');
INSERT INTO PRODUCT_MASTER1 VALUES('P00004','FLOPPIES');
INSERT INTO PRODUCT_MASTER1 VALUES('P00005','KEYBOARD');
INSERT INTO PRODUCT_MASTER1 VALUES('P00006','CD DRIVE');
INSERT INTO PRODUCT_MASTER1 VALUES('P00007','HDD');
INSERT INTO PRODUCT_MASTER1 VALUES('P00008','FDRIVE');
INSERT INTO PRODUCT_MASTER1 VALUES('P00009','COMPUTER');

SQL> SELECT * FROM SALES_MASTER1;

SQL> Select product,description from product_master1 where


product NOT IN (Select product from sales_order2);

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:

Creating Table 1 : EMP1


--------------------

DROP TABLE EMP1;

CREATE TABLE EMP1(EMPNO NUMBER(3),


ENAME VARCHAR2(12),DEPTNO VARCHAR2(4));

INSERT INTO EMP1 VALUES(1,'RAHUL','D01');

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 * FROM EMP1;

Creating Table 2: INV_SYS


---------------------------------

DROP TABLE INV_SYS;

CREATE TABLE INV_SYS(ENAME VARCHAR2(12),PERFORMANCE VARCHAR2(10));

SQL> INSERT INTO INV_SYS VALUES('&ENAME','&PERFORMANCE');

INSERT INTO INV_SYS VALUES('RAHUL','GOOD');


INSERT INTO INV_SYS VALUES('AMJAD','GOOD');
INSERT INTO INV_SYS VALUES('JUNAID','EXCELLENT');
INSERT INTO INV_SYS VALUES('LENNA','GOOD');
INSERT INTO INV_SYS VALUES('PRADEEP','GOOD');
INSERT INTO INV_SYS VALUES('JOSHI','ABCD');
INSERT INTO INV_SYS VALUES('PRASHANT','GOOD');
INSERT INTO INV_SYS VALUES('SANDEEP','ABCD');
INSERT INTO INV_SYS VALUES('PRITAM','AJD');
INSERT INTO INV_SYS VALUES('ZAHEER','ABCD');

SQL> SELECT * FROM INV_SYS;

SQL> SELECT ENAME,DEPTNO FROM EMP1 WHERE DEPTNO IN(SELECT DEPTNO FROM EMP1 WHERE
ENAME='ZAHEER') AND
ENAME IN (SELECT ENAME FROM INV_SYS);

Some more sub queries


SQL Test1
Table
drop table emp;

Create table emp (empno number(3),ename varchar2(12),job varchar2(12),


city varchar2(12),hiredate date,salary number(5),comm number(3),exp number(3),
deptno number(3));

PNo: 64
TECH IQ Technologies
insert into emp values(1,'SANDEEP','ENGINEER','HYDERABAD','24-JUN-2014', 6000,
473, 2, 30);

insert into emp values(2,'PRAKASH','DOCTOR','BANGLORE', '03-NOV-2015', 5000, 374,


6, 10);

insert into emp values(3,'SALIM','CLERK','NEW DELHI', '02-MAY-2014', 7384, 384,


8, 30);

insert into emp Values(4,'JUNAID','CLERK','BOMBAY','18-APR-2015', 3848, 273, 5,


40);

insert into emp values(5,'SURESH','MANAGER','MADRAS', '15-FEB-2015', 8873, 983,


9, 30);

insert into emp values(6,'SALMAN','CLERK','NEW DELHI', '15-AUG-2015', 6555, 775,


6, 30);

insert into emp values(7,'RAMESH','DOCTOR','HYDERABAD', '23-AUG-2013', 6500, 400,


6, 10);

insert into emp values(8,'JUNAID','ENGINEER','BOMBAY', '10-JUN-2012', 8900, 220,


5, 30);

insert into emp values(9,'ZAHEER','SPORT','NEW DELHI', '12-JAN-2016', 5400, 220,


7, 20);
insert into emp values(10,'ALTAF','DOCTOR','MADRAS', '15-NOV-2015', 7800, 350, 3,
30);
insert into emp values(11,'SRINIVASAN','SALESMAN','MADURAI', '08-JAN-2014', 7766,
480, 8, 40);
insert into emp values(12,'SALMAN','CLERK','NEW DELHI', '13-SEP-2015',2130, 883,
6, 30);
insert into emp values(13,'SAJID','DOCTOR','NEW DELHI', '10-OCT-2015', 7981, 375,
9, 10);
insert into emp values(14,'ANIL','SALESMAN','JAIPUR', '25-JUL-2015', 8300, 450,
6, 30);
insert into emp values(15,'JAFFER','CLERK','BANGALORE', '07-JAN-2016', 5400, 520,
7,30);

Write the queries for the following questions

1.Display employee maximum salary.


A. select max(salary) from emp;

2.Display details of all employees who are working in city ‘NEW DELHI’
A. select * from emp where city='NEW DELHI';3.

3.Display details of all employees who are working in department 30.


A.SELECT * FROM EMP WHERE DEPTNO=30;

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

5.Change initial’s as ‘Dr’ of all those who are working as ‘DOCTOR’.


A.UPDATE EMP SET ENAME=LPAD(ENAME,LENGTH(ENAME)+3,'Dr.') where job='DOCTOR';

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';

8. Update salary by 10% of all those employees whose experience is >5;


UPDATE EMP SET SALARY=SALARY+SALARY*0.10 WHERE EXP > 5;

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)15. Display name,salary,Hra,pf,da,TotalSalary for each employee.


The out put should be in the order of total salary ,hra 15% of salary ,
DA 10% of salary .pf 5% salary Total Salary will be (salary+hra+da)-pf?
A) select empno,ename,salary "Monthly sal",salary*0.15 Hra,salary*0.1
Da,salary*0.05 pf,(salary*0.15+salary*0.1+salary)-(salary*0.05) Totalsalary from
emp;

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.

SQL> select distinct C.ParentCategory, C.subCategory from category C where


CategoryName in (select CategoryName from BookShelf
where Title in(select Title from BookShelf_Checkout));

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.

In a SQL database query, a correlated subquery (also known as a synchronized


subquery) is a subquery (a query nested inside another query) that uses values
from the outer query. The subquery is evaluated once for each row processed by
the outer query.

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

Correlated SubQueries Examples

1. Write a query to find the highest earning employee in each department?


drop table emp1;
create table emp1(eno number,ename varchar2(15),job varchar2(15),salary
number,dept_id number);
insert into emp1 values(1,'JUNAID','PROGRAMMER',9583,101);
insert into emp1 values(2,'PRADEEP','ANALYST',6843,201);
insert into emp1 values(3,'ZAHEER','ACCOUNTANT',6592,301);
insert into emp1 values(4,'SANDEEP','MANAGER',9586,401);
insert into emp1 values(5,'HAMED','PROGRAMMER',7958,101);
insert into emp1 values(6,'ANIL','DOCTOR',9984,501);
insert into emp1 values(7,'YOUSUF','PROGRAMMER',5563,101);
insert into emp1 values(8,'KALYAN','ACCOUNTANT',4958,301);
insert into emp1 values(9,'RAHMAN','PROGRAMMER',7594,101);
insert into emp1 values(10,'IMRAN','ACCOUNTANT',6894,301);
insert into emp1 values(11,'SAJID','ANALYST',4496,201);
insert into emp1 values(12,'RAJESH','MANAGER',4987,401);
insert into emp1 values(13,'DANIEL','PROGRAMMER',8603,101);
insert into emp1 values(14,'TAHER','ANALYST',9846,201);
insert into emp1 values(15,'SUNIL','ACCOUNTANT',6982,301);

SELECT ename,DEPT_ID,ENO,SALARY FROM EMP1 E1 WHERE 1=


SQL>

( SELECT COUNT(DISTINCT SALARY) FROM EMP1 E2


WHERE E1.DEPT_ID = E2.DEPT_ID AND E1.SALARY <= E2.SALARY );

2. Write a query to list the department names which have at lease one employee?

drop table emp;


drop table dept;

create table dept(name varchar2(10),dept_id number primary key);

INSERT INTO DEPT VALUES('SALES',101);


INSERT INTO DEPT VALUES('HEALTH',201);
INSERT INTO DEPT VALUES('ACCOUNTS',301);
INSERT INTO DEPT VALUES('EDUCATION',401);
INSERT INTO DEPT VALUES('MEDIA',701);
INSERT INTO DEPT VALUES('PRODUCTION',801);
DROP TABLE EMP;
create table emp(eno number,ename varchar2(10),
city varchar2(10),job varchar2(10),dept_id number,
constraint acb FOREIGN KEY(dept_id) references dept(dept_id)
ON DELETE CASCADE);
insert into emp values(1,'SAMI','HYDERABAD','MARKETING',101);
insert into emp values(2,'ALI','BANGALORE','DOCTOR',201);
insert into emp values(3,'HAMEED','BOMBAY','ACCOUNTANT',301);
insert into emp values(4,'JUNAID','MADRAS','TEACHER',401);
insert into emp values(5,'KALEEM','DELHI','DOCTOR',201);
insert into emp values(6,'FARID','HYDERABAD','MANAGER',101);
insert into emp values(7,'SANDEEP','BOMBAY','DOCTOR',201);
insert into emp values(8,'NARESH','DELHI','BUSINESS',101);
insert into emp values(9,'PRADEEP','BANGALORE','DOCTOR',201);

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?

SELECT DEPT_ID,NAME FROM DEPT D WHERE NOT EXISTS


( SELECT 1 FROM EMP E WHERE E.DEPT_ID = D.DEPT_ID);
Finding Hishest and Lowest Salaries
--------------------------------------------
//First way
SELECT MAX(Salary) FROM Emp1 WHERE Salary NOT IN (SELECT MAX(Salary) FROM Emp1
);

//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;

//To display starting 3 highest salaries


SELECT * FROM( SELECT * FROM emp1 ORDER BY Salary desc ) WHERE rownum<=3 ORDER BY
Salary ;

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

The purpose of a join is to combine the data across tables.


A join is actually performed by the where clause which combines the specified
rows of tables.
If a join involves in more than two tables then Oracle joins first two tables
based on the joins condition and then compares the result with the next table
and so on.

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

Assume that we have the following tables.


drop table emp;
drop table dept;

create table dept(deptno number primary key,dname varchar2(15),location


varchar2(15));
insert into dept values(10,'INVENTORY',HYBDERABAD');
insert into dept values(20,'FINANCE','BANGLORE');
insert into dept values(30,'HR','MUMBAI');
insert into dept values(40,'SALES','DELHI');

create table emp(empno number, ename varchar2(15),job varchar2(15),salary


number,deptno number);
insert into emp values(111,'sunil','analyst',7448,10);
insert into emp values(222,'sudha','clerk',6953,20);
insert into emp values(333,'jagan','manager',6161,10);
insert into emp values(444,'madhu','engineer',7933,40);
insert into emp values(555,'sajid','analyst',4983,10);
insert into emp values(666,'akash','clerk',9594,20);
insert into emp values(777,'hamed','manager',5869,10);
insert into emp values(888,'chander','clerk',8877,20);
insert into emp values(999,'akhil','analyst',3956,10);

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.

DROP TABLE EMPLOYEE;

CREATE TABLE EMPLOYEE(ENAME VARCHAR2(12),


CITY VARCHAR2(14));

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');

SQL> SELECT * FROM EMPLOYEE;

SQL> SELECT EMPLOYEE.ENAME FROM EMPLOYEE WHERE EMPLOYEE.ENAME='SUNIL';

SQL> select emp2.ename from employee emp1,employee emp2 where emp1.city=emp2.city


and emp1.ename='SUNIL';

4. NATURAL JOIN
Natural join compares all the common columns.
Ex:
SQL> select empno,ename,job,dname,location from emp natural join dept;

drop table emp_company;

create table emp_company(ename varchar2(12),cname varchar2(12),


salary number(5),doj date);

insert into emp_company values('JUNAID','WIPRO',7482,'12-OCT-2009');


insert into emp_company values('ZAHEER','SATYAM',3874,'05-JUN-2008');
insert into emp_company values('MAZHAR','VIRTUSA',29439,'29-AUG-2004');
insert into emp_company values('KALEEM','INFOSYS',38484,'10-APR-2002');
insert into emp_company values('SALIM','WIPRO',6535,'18-MAR-2006');
insert into emp_company values('SAJID','INFOSYS',5000,'24-JAN-2005');
insert into emp_company values('LATEEF','SATYAM',8475,'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','INFOSYS',83894,'23-APR-2004');

DROP TABLE EMPLOYEE;

create table employee (ename varchar2(15),


city varchar2(15),salary number(6));

insert into employee values('SAJID','MADRAS',5000);


insert into employee values('SALIM','MUMBAI',6535);
insert into employee values('JUNAID','DELHI',7482);
insert into employee values('FARID','HAMED',7434);
insert into employee values('ASLAM','PUNE',3845);
insert into employee values('ZAHEER','HYDERABAD',3874);
insert into employee values('LATEEF','HYDERABAD',8475);
insert into employee values('HUSSAIN','DELHI',5000);

Example: Retrieving name, living city and salary of employee

SQL> select e.ename,e.city,c.salary from employee e,

PNo: 72
TECH IQ Technologies
emp_company c where e.ename=c.ename;

Using 'JOIN' clause:


-------------------------
SQL> select ename,city,salary from employee natural join emp_company;

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.

DROP TABLE MANAGER;

create table manager(ename varchar2(14),mname varchar2(12));

insert into manager VALUES('ASLAM','AFZAL');


insert into manager VALUES('SAJID','MALIK');
insert into manager VALUES('ZAHEER','');
insert into manager VALUES('FARID','KHAN');
insert into manager VALUES('HAMED','');
insert into manager VALUES('MAZHAR','SHAREEF');
insert into manager VALUES('JUNAID','');
insert into manager VALUES('NAVED','BASEER');
insert into manager VALUES('OSMAN','');
insert into manager VALUES('GAFOOR','ILYAS');
insert into manager VALUES('KAREEM','HASEEB');

SQL> SELECT * FROM MANAGER;

SQL> select * from emp_company;

Now example on 'USING' clause:


----------------------------------------
SQL> select ename,mname,salary from manager join emp_company using(ename) where
salary < 6000;

ON Clause:
-------------
It is like 'where' clause and you can put multiple conditions in the 'ON' clause.

SQL> select c.ename,m.mname,c.salary from manager m join emp_company c on


( c.ename=m.ename and salary > 7000);

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.

DROP TABLE EMP_SHIFT;

CREATE TABLE EMP_SHIFT(ENAME VARCHAR2(15),SHIFT VARCHAR2(2));

INSERT INTO EMP_SHIFT VALUES('ASLAM','B');


INSERT INTO EMP_SHIFT VALUES('SAJID','C');
INSERT INTO EMP_SHIFT VALUES('ZAHEER','A');
INSERT INTO EMP_SHIFT VALUES('FARID','B');
INSERT INTO EMP_SHIFT VALUES('HAMED','A');
INSERT INTO EMP_SHIFT VALUES('MAZHAR','B');
INSERT INTO EMP_SHIFT VALUES('JUNAID','C');
INSERT INTO EMP_SHIFT VALUES('TANVEER','B');
INSERT INTO EMP_SHIFT VALUES('WAHEED','C');
INSERT INTO EMP_SHIFT VALUES('KAMAL','A');
INSERT INTO EMP_SHIFT VALUES('PASHA','B');

SQL> select * from EMP_SHIFT;

SQL> select * from MANAGER;

Example: Performing NATURAL JOIN

SQL> select ename,mname,shift from manager natural join emp_shift;

SQL> select m.ename,mname,shift from manager m left outer join emp_shift s on


(m.ename=s.ename);

->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.

-> We can also write query as:

SQL> select m.ename,mname,shift from manager m,emp_shift s where


(m.ename=s.ename(+));

Displaying all rows of EMP_SHIFT table


-----------------------------------------------
SQL> select m.ename,mname,shift from manager m right outer join emp_shift s on
(m.ename=s.ename);

FULL OUTER JOIN: In case of full outer join, rows from both the tables rows are
produced.

Example for FULL OUTER JOIN

SQL> select m.ename,mname,shift from manager m full outer join emp_shift s on


(m.ename=s.ename);

PNo: 74
TECH IQ Technologies

SQL> select m.ename,mname,shift from manager m right outer join emp_shift s on


(m.ename=s.ename);

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.

LEFT OUTER JOIN


This will display the all matching records and the records which are in left hand
side table those that are not in right hand side table.

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(+);

RIGHT OUTER JOIN


This will display the all matching records and the records which are in right
hand side table those that are not in left hand side table.

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;

FULL OUTER JOIN


This will display the all matching records and the non-matching records from both
tables.
Ex:
SQL> select empno,ename,job,dname,loc from emp e full outer join dept d
on(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);

Basic Set Operations


The three basic set operations are:
1. UNION
2. INTERSECT
3. MINUS

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

SQL> select city from company where cname='ACC' UNION


2 select city from company where cname='TATA' ;
CITY
----------
BOMBAY
DELHI
HYDERABAD

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}

Then the minus operation will produce the following result:


S minus R = {b,c}
The elements {b,c} are present in set S but not in set R. The element 'a' is present in both sets, so
it will not appear in the output.
Example: Finding cities where ACC is located but not TATA.

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

drop table emp_company;

create table emp_company(ename varchar2(12),cname varchar2(12),


salary number(5),doj date);

insert into emp_company values('JUNAID','WIPRO',67953,'12-OCT-2009');


insert into emp_company values('ZAHEER','SATYAM',39489,'05-JUN-2008');
insert into emp_company values('MAZHAR','VIRTUSA',29439,'29-AUG-2004');
insert into emp_company values('KAREEM','INFOSYS',38484,'10-APR-2002');

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');

DROP TABLE EMPLOYEE;

create table employee (eno number(4),ename varchar2(15),


COMPANY VARCHAR2(15),city varchar2(15),pincode number(7));

insert into employee values(1,'SAJID','INFOSYS','MADRAS',500034);


insert into employee values(2,'SALIM','TATA','BOMBAY',650007);
insert into employee values(3,'JUNAID','WIPRO','DELHI',700006);
insert into employee values(4,'FARID','TATA','BOMBAY',700012);
insert into employee values(5,'ASLAM','TATA','PUNE',300045);
insert into employee values(6,'ZAHEER','SATYAM','HYDERABAD',200384);
insert into employee values(7,'LATEEF','SATYAM','HYDERABAD',500475);
insert into employee values(8,'HUSSAIN','TATA','BOMBAY',500018);
insert into employee values(9,'SURESH','ACC','BOMBAY',700012);
insert into employee values(10,'KALEEM','TATA','MADRAS',760000);
insert into employee values(11,'HAMED','INFOSYS','BOMBAY',765098);
Example: Displaying the names of employees living in BOMBAY and working with company TATA

SQL> SELECT * FROM EMPLOYEE;

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

ENAME CNAME SALARY DOJ


------------ ------------ ---------- ---------
AMOL ACC 2394 17-MAR-02

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));

insert into countries values('AFGHANISTAN');


insert into countries values('BANGLADESH');
insert into countries values('CAMBODIA');
insert into countries values('CHINA');
insert into countries values('DANISH');
insert into countries values('INDIA');
insert into countries values('NEPAL');
insert into countries values('PAKISTAN');
insert into countries values('SRI LANKA');

SQL> SELECT * FROM COUNTRIES;

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.

->An index is an ordered list of the cotents of a column, of table.


->Indexing involves forming a two dimensional matrix completely independent of the table on which the
index is being created.
->A column, which will hold sorted data, extracted from the table on which the index is being created.
->An address field that identies the location of the record in the Oracle database. This address field is
called Rowid.

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.

Address field in the Index:


The address field of an index is called ROWID. ROWID is an internal generated and maintained, binary
value, which identifies a record. The information in the ROWID columns provides Oracle engine the location
of the table and a specific record in the Oracle database.

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

Creating Simple Index:


An index created on a single column of a table it is called Simple Index. The syntax for creating simple
index that allows duplicate values is:

Syntax:
Create INDEX indexname ON tablename(column-name);

drop table emp13;

Create table emp13(empno number(3),ename varchar2(12),


job varchar2(12),city varchar2(12),hiredate date,salary number(5),
comm number(3),mgr number(3));

SQL> desc emp13


Name Null? Type
----------------------------------------- -------- ---------------------------
EMPNO NUMBER(3)

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)

insert into emp13 values(1,'SANDEEP','ENG','HYDERABAD','24-JUN-2009',6000,473,274);


insert into emp13 values(2,'PRAKASH','DOCTOR','BANGLORE','03-NOV-2005',5000,374,242);
insert into emp13 values(3,'SALIM','CLERK','NEW DELHI','02-MAY-2008',7384,384,884);
insert into emp13 Values(4,'JUNAID','PILOT','BOMBAY','18-APR-2009',3848,273,384);
insert into emp13 values(5,'SURESH','MANAGER','MADRAS','15-FEB-2005',3873,374,749);
insert into emp13 values(6,'SALMAN','MANAGER','NEW DELHI','15-AUG-2005',4555,374,653);
create INDEX idxemp on emp13 (ename);
Creating Composite Index:
An index created on more than one column it is called Composite Index. The syntax for creating a
composite index that allows duplicate value is:
Syntax:
Create INDEX indexname ON tablename (columname,columnname);

create INDEX idxemp on emp13 (empno,job,salary);

Creation of Unique Index:

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).

Syntax to create a 'CLUSTER':


---------------------------------------
create cluster cluster-name (column1 data-type,column2 data-type);

->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:

SQL> create table BOOKSHELF1(Title VARCHAR2(100) primary key,


Publisher VARCHAR2(20),CategoryName VARCHAR2(20),
Rating VARCHAR2(2)) cluster BookandAuthor(Title);

Note: Prior to inserting rows into BookShelf1 table, you must create a cluster index:

create index BookandAuthorndx on cluster BookandAuthor;

-->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.

Now a second table is added to the cluster:

create table BOOKSHELF_AUTHOR


(Title VARCHAR2(100),
AuthorName VARCHAR2(50),
constraint TitleFK Foreign key (Title) references BOOKSHELF(Title),
constraint AuthorNameFK Foreign key (AuthorName)
references AUTHOR(AuthorName))
cluster BookandAuthor(Title);

->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));

insert into Sales_order1(pno,pname,quantity,orderno,


orderdate,clientno) values(order_seq.nextval,'MOBILE',5,
'A01','02-APR-2012','C001');
insert into Sales_order1(pno,pname,quantity,orderno,
orderdate,clientno) values(order_seq.nextval,'CAP',15,'A02',
'02-APR-2012','C002');
insert into Sales_order1(pno,pname,quantity,orderno,

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

SQL> INSERT INTO sales_order1(orderno,orderdate,clientno) VALUES(order_seq.nextval,sysdate,'C007');


SQL> SELECT order_seq.currval FROM dual;
CURRVAL
----------
5
SQL> select * from sales_order;
PNO PNAME QUANTITY ORDERNO ORDERDATE CLIENTN
---------- ---------- ---------- ------- --------- -------
1 MOBILE 5 A01 12-APR-03 C004
2 PEN 3 C12 06-NOV-05 C006
5 CAP 4 E37 02-AUG-08 C001

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.

xii) Data Control Language:


Using the data control language (DCL), you can control access to the data.
Granting and Revoking Permissions:
-------------------------
Oracle provides extensive security features in order to safeguard information stored int its tables from
unauthorized viewing and damage. Depending on a user's status and responsibility, appropriate rights on
Oracle's resources can be assigned to the user. The rights that allow the use of some or all of Oracls'es
resources on the Server are Privileges.

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.

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);
insert into sales_order7 values(1,'CHAIR',14);
WITH GRANT OPTION:
---------------------------
The 'WITH GRANT OPTION' allows the grantee to 'in turn' grant object privileges to other users.
CREATING USER 'ORBIT'
------------------------------
CREATE USER ORBIT IDENTIFIED BY ADMIN;
Example 1:
Give the user 'orbit' all data manipulation permissions on the table emp.
GRANT SELECT ON SALES_ORDER7 TO orbit;
To see the data from 'SALES_ORDER7' table type the following command
select * from System.sales_order7;
Giving 'UPDATE' object privilege to Orbit user:
---------------------------------------------------------
GRANT UPDATE ON SALES_ORDER7 TO ORBIT;

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.

CREATING USER 'MITA'


------------------------------
CREATE USER MITA IDENTIFIED BY ADMIN;
GRANT SELECT,UPDATE ON SALES_ORDER7 TO mita;
Example 3:
Give the user 'Ivan' all data manipulation privileges on the table client_master along with an optino to
further permission on the client_master table to other users.
In user 'SYSTEM' environment
-----------------------------------
GRANT ALL ON sales_order7 TO ivan WITH GRANT OPTION;
In user 'IVAN' environment
-----------------------------------
GRANT ALL ON SYSTEM.sales_order7 TO ORBIT WITH GRANT OPTION;
Referencing a table belonging to another user:
---------------------------------------------------------
Once a user has privileges to access another user's object/s, the user can access the table by prefixing the
table with the name of the owner.
Example:
SELECT * FROM orbit.SALES_ORDER7;
Granting privileges when a grantee has been given the GRANT privilege:
->If the user wants to grant privileges to other users, the user must be the owner of the object or must be
given the GRANT option by the owner of the object.
Example: Give the user 'SURESH' permission to view records from the product_master table. The table
originally belongs to the user 'SYSTEM', who has granted you the privilege to GRANT privilege on
product_master.
syntax:
GRANT SELECT ON SYSTEM.SALES_ORDER7 TO SURESH;
REVOKING PRIVILEGES GIVEN
------------------------------------
Privileges once given can be denied to a user using the REVOKE command. The object owner can revoke
privileges granted to another user. A user of an object who is not the owner, but has been granted the
GRANT privilege, has the owner to REVOKE the privileges from a grantee.
Revoking permissions using the REVOKE statement:
The 'REVOKE' statement is used to deny the grant given on an object.
Note: The revoke command is used to revoke object privileges that the user previously granted directly to
the Revokee.
->The REVOKE command cannot be used to revoke the privileges granted through the operating system.
Example 1: All the privileges on the table product_master have been granted to ORBIT. Take back the
'Delete' privilege on the table.
Syntax:
REVOKE DELETE ON SALES_ORDER7 FROM MITA;

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.

An interesting fact about a View is that it is stored only as a definition in


Oracle's system catalogue. When a reference is made to a View, its definition is
scanned, the base table is opened and the View created on top of the base table.
Hence, a view holds no data at all, until a specific call to the view is made.
This reduces redundant data on the HDD to a very large extent. When a view is
used to manipulate table data, the underlying base table will be completely
invisible. This will give the level of data security required.

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.

Reason's why views are created are:


->When Data security is required
->When Data redundancy is to be kept to the minimum while maintaining data
security.

Creation of views:

Syntax:
CREATE VIEW viewname AS SELECT columnname,columnname FROM
tablename WHERE columnname=expression list;

1. Example: Creating a VIEW on employee table.

drop table emp;


Create table emp(eno number(3),ename varchar2(15),job varchar2(15), salary
number(7),exp number(3));

Insert into emp values(1,’SANDEEP’,’MANAGER’,9586,5);


Insert into emp values(2,’HAMED’,’ENGINEER’,8495,4);
Insert into emp values(3,’ANIL’,’DOCTOR’,6667,7);
Insert into emp values(4,’RAMESH’,’MANAGER’,9856,7);
Insert into emp values(5,’JUNAID’,’BUSINESS’,7941,6);

//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);

SELECT * FROM V1;


select * from emp;

2. Creating a VIEW on client_master1 table which has a primary key for


'client_no' column.

DROP TABLE CLIENT_MASTER;

create table client_master(client_no varchar2(6) PRIMARY KEY,


name varchar2(12),address1 varchar2(12), address2 varchar2(12),
city varchar2(15), state varchar2(12),pincode number,
bal_due number(6,2));

insert into client_master values('C0001','ahmed','dsnr',


'satoshngr','Hyderabad','AP',50003,300);

insert into client_master values('C0002','SAMI','LDRW','LB


SPACE','Hyderabad','AP',50003,300);

insert into client_master values('C0003','SALIM','HFRF','LB SPACE','Hyderabad',


'AP',50563,340);

insert into client_master values('C0004','MAHMOOD','ST COL','BHEL','Hyderabad',


'AP',59454,473);

insert into client_master values('C0005','GAFOOR','HFRF',


'KPHB','Hyderabad', 'AP',50563,533);

select * from client_master;

//Creating a view on ‘Client_master’table


Sql>drop view vc1;

Sql>CREATE VIEW vc1 AS SELECT client_no,name from client_master;


Sql>select * from vc1;

//Insertion is allowed
insert into vc1 values('C0006','SACHIN');

//Creating another view


Sql> drop view vc2;
Sql>CREATE VIEW vc2 AS SELECT name,address1 from client_master;
Sql>select * from vc2;

UPDATE VC2 SET NAME=' TENDULKAR' ;


SELECT * FROM VC2;
SELECT * FROM CLIENT_MASTER;

DELETE FROM VC2 WHERE ADDRESS1='HFRF';


SELECT * FROM VC2;

PNo: 90
TECH IQ Technologies

SELECT * FROM CLIENT_MASTER;

//Creating view
Sql>drop view vc3;
Sql>CREATE VIEW vc3 AS SELECT client_no,name,address1,
bal_due from client_master;

sql>select * from vc3;

sql>CREATE VIEW vw_client4 AS SELECT * from client_master;

Renaming the columns of a View:


The columns of the view can take on different names from the table of columns, if
required.

Example:

SQL> create view vw_client1 AS SELECT client_no cno,name cname,city place,pincode


zipcode from client_master;

DROP VIEW CLIENTADMIN;

CREATE VIEW clientadmin AS SELECT name,address1 add1,address2 add2,


city,pincode,state from client_master;

View created.

select * from clientadmin;

NAME ADD1 ADD2 CITY PINCODE STATE


---------- ------------ ---------- ---------- ---------- ----------
ASLAM 3-4,ABIDS SHANTNAGAR BANGLORE 57494 KARNATAKA

Selecting a data set from view:


Once a view has been created, it can be queried exactly like a base table.

Syntax:
SELECT columnname,columnname FROM viewname;

eg:

SQL> select name,add1,add2,city from clientadmin;

NAME ADD1 ADD2 CITY


---------- ------------ ---------- ----------
ASLAM 3-4,ABIDS SHANTNAGAR BANGLORE

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.

Syntax for creating Updateable View:

DROP VIEW CLIENT1;

create view client1 AS SELECT client_no,name,address1,


bal_due from client_master;

View created.

->When performing insertion using the VIEW.


SQL> insert into client1 values('C0006','JUNAID','4-5/23',4743);

SQL> insert into client1 values('C0007','ZAHEER','2-1/72',8437);

DROP VIEW CLIENT7;


create view client7 AS SELECT name,address1,
bal_due from client_master;

insert into client7 values('ZAHEER','2-1/72',8437);

->When performing MODIFICATION operation using the VIEW.


SQL> update client1 set bal_due=5094 where client_no='C0002';

->When a DELETE operation is performed using the view.


SQL> delete from client1 where client_no='C0002';

->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:

*Whether the tables were created using a 'Referencing clause'


*Whether the tables were created without any 'Referencing clause' and are
actually standalone tables not related in any way.

VIEW's Defined from Multiple tables (Which have no Referencing Clause):


-----------------------------------------------------------------
->If a 'VIEW' is created from multiple tables, which were 'NOT CREATED' using a
'Referencing clause' that is, no logical linkage exists between the tables, then
even though the PRIMARY KEY column as well as the NOT NULL columns are included
in the 'VIEW' definition the view's behaviour will be as follows:
*The INSERT,UPDATE or DELETE operation is not allowed.

DROP TABLE DEPT;

PNo: 92
TECH IQ Technologies

CREATE TABLE DEPT(DNO NUMBER(7),DNAME VARCHAR2(15));


INSERT INTO DEPT VALUES(101,'SALES');

DROP TABLE EMP;


CREATE TABLE EMP (ENO NUMBER,ENAME VARCHAR2(15),DNO NUMBER(4));

insert into EMP VALUES(1,'KALEEM',101);

CREATE VIEW VC3 AS SELECT ENO,ENAME,D.DNO,DNAME FROM EMP E,DEPT D WHERE E.DNO =
D.DNO;
SELECT * FROM VC3;

SELECT * FROM DEPT;


SELECT * FROM EMP;
SELECT * FROM VC3;

INSERT INTO VC3 VALUES(2,'NAGENDER',201,'PRODUCTION'); //NOT ALLOWED


UPDATE VC3 SET ENAME='NABEEL' WHERE DNO=101; //NOT ALLOWED
DELETE FROM VC3 WHERE ENO=1; //NOT ALLOWED

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));

insert into dept values(10,'ACCOUNTS','INDORE');


insert into dept values(20,'MARKETING','MUMBAI');
insert into dept values(30,'PHARMAY','BANGLORE');

SQL> SELECT * FROM DEPT;

//Foreign or child Table


DROP TABLE EMP;
CREATE TABLE EMP (ENO NUMBER,NAME VARCHAR2(15),JOB VARCHAR2(15),SALARY
NUMBER,DNO NUMBER,FOREIGN KEY (DNO) REFERENCES DEPT(DNO));

PNo: 93
TECH IQ Technologies

INSERT INTO EMP VALUES(1,'ANIL','SALESMAN',8978,20);


INSERT INTO EMP VALUES(2,'SUNIL','CLERK',45454,10);
INSERT INTO EMP VALUES(3,'PRADEEP','SALESMAN',9876,20);
INSERT INTO EMP VALUES(4,'SANDEEP','PHARMACIST',8375,30);
INSERT INTO EMP VALUES(5,'PRAKASH','SALESMAN',4345,20);

SQL> SELECT * FROM DEPT;

SQL> SELECT * FROM EMP;

//Creating view from 'Dept' and 'Emp' tables


SQL> CREATE VIEW V3 AS SELECT ENO,NAME,JOB,SALARY,DNAME,LOCATION,E.DNO FROM DEPT
D,EMP E WHERE D.DNO=E.DNO;

SQL> SELECT * FROM V3;

//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);

//Updation and deletion does not effect primary table


SQL> DELETE FROM V3 WHERE DNO=20;

SQL> SELECT * FROM DEPT;


SQL> SELECT * FROM EMP;
SQL> SELECT * FROM V3;

//Dropping a view
drop view v3;

ROLLUP and CUBE


Understanding ROLLUP
---------------------------
CUBE and ROLLUP grouping is used in data warehousing. Data warehousing is used for generating
business intelligence information, information that is required for decision-making by medium and high-
level managers.

->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.

Creating Table SALES


--------------------------
create table sales (year number, region varchar2(15), dept varchar2(15), profit number);

PNo: 94
TECH IQ Technologies

Inserting data into table SALES


-----------------------------------------
insert into sales values(2010, 'Central', 'pen_sales', 34000);
insert into sales values(2010, 'Central', 'pen_sales', 41000);
insert into sales values(2010, 'Central', 'book_sales', 74000);
insert into sales values(2010, 'east','pen_sales', 89000);
insert into sales values(2010, 'east','book_sales',100000);
insert into sales values(2010, 'east', 'book_sales', 15000);
insert into sales values(2010, 'west', 'pen_sales', 87000);
insert into sales values(2010, 'west', 'book_sales', 86000);
insert into sales values(2011, 'Central', 'pen_sales', 82000);
insert into sales values(2011, 'Central', 'book_sales', 85000);
insert into sales values(2011, 'east', 'pen_sales', 101000);
insert into sales values(2011, 'east', 'book_sales', 137000);
insert into sales values(2011, 'west', 'pen_sales', 96000);
insert into sales values(2011, 'west', 'book_sales', 97000);
insert into sales values(2010, 'south','appliances',85000);
insert into sales values(2010, 'north', 'bags', 64500);
insert into sales values(2010, 'north', 'book_sales', 64780);
insert into sales values(2010, 'north', 'pen_sales', 98400);
insert into sales values(2012, 'south', 'pen_sales', 64675);
insert into sales values(2011, 'north', 'appliances', 74660);
insert into sales values(2011, 'south', 'pen_sales', 74600);
insert into sales values(2012, 'north', 'book_sales', 47670);
insert into sales values(2012, 'west', 'pen_sales', 96000);
insert into sales values(2010, 'west', 'book_sales', 97000);

Displaying data from table SALES


------------------------------------------
SQL> SELECT * FROM SALES;

Using 'GROUP BY'


---------------------

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.

*A grand total row.

Using Partial ROLLUP:


---------------------------
Partial Rollup can be specified by using:

Group By Time, Rollup(Region, Department)

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);

TIME REGION DEPT PROFIT


---------- --------------- --------------- ----------
2010 east pen_sales 89000
2010 east book_sales 115000
2010 east 204000
2010 west pen_sales 87000
2010 west book_sales 86000
2010 west 173000
2010 Central pen_sales 75000
2010 Central book_sales 74000
2010 Central 149000
2010 526000
2011 east pen_sales 101000

TIME REGION DEPT PROFIT


---------- --------------- --------------- ----------
2011 east book_sales 137000
2011 east 238000
2011 west pen_sales 96000
2011 west book_sales 97000
2011 west 193000
2011 Central pen_sales 82000
2011 Central book_sales 85000
2011 Central 167000
2011 598000

20 rows selected.

Creating Group within Group


-----------------------------------
We already know that grouping is always done on certain combination. For example, supppose grouping is
done on TIME and REGION.

Listing: Grouping on TIME and REGION

SQL> Select year,REGION,DEPT,SUM(PROFIT) AS PROFIT FROM sales GROUP BY


ROLLUP((year,REGION),DEPT);

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.

Note: CUBE is specified in GROUP BY clause just like ROLLUP.

Listing: Using CUBE to product aggregations

SELECT year,nvl(region,0) Region, Dept, SUM(Profit) AS Profit FROM sales GROUP BY CUBE(year, Region,
Dept);

Using Partial Cube:


---------------------------
When you specify less number of dimensions in the CUBE clause, the combinations are generated only for
the dimensions that you have specified. Suppose you specify a group by time, cube (region,dept), then
combinations are generated only for region and dept along with time. So, in the output you will have rows
like 2010, central, pel_sales.2010, central, but not central, pen_sales.

Listing: Using group by time, cube (region,dept)

SELECT year, Region, Dept, SUM(Profit) AS Profit FROM sales


GROUP BY year, CUBE(Region, Dept);

PNo: 97
TECH IQ Technologies

PL/SQL (Procedural Language/Structured Query Language):


Disadvantages in SQL:
---------------------------
Though SQL is the natural language of the DBA, it suffers from various disadvantages, when used as a
conventional programming language.

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.

PL/SQL (Procedural Language/Structured Query Language):


PL/SQL is the procedural language extension to the Oracle's Structured Query Language, and is a block
structured language that enables developers to code procedures, functions, and unnamed blocks that
combine SQL with procedural statements.

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 (Procedural Language/Structured Query Language):


----------------------------------------------------------------
PL/SQL is the procedural language extension to the Oracle's Structured Query Language, and is a block
structured language that enables developers to code procedures, functions, and unnamed blocks that
combine SQL with procedural statements.

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.

A PL/SQL block has three parts to it:


• Declaration objects of the block are declared here
• Execution objects of the block are defined here to manipulate data
• Exception error handling logic is placed here

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.

Variables and Constants:


---------------------------
The program stores values in variables and constants. As the program executes, the values of variables
can change, but the values of constants cannot.

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.

PL/SQL (Procedural Language/Structured Query Language):


----------------------------------------------------------------
PL/SQL is the procedural language extension to the Oracle's Structured Query Language, and is a block
structured language that enables developers to code procedures, functions, and unnamed blocks that
combine SQL with procedural statements.

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.

• 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.

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 (Procedural Language/Structured Query Language):


----------------------------------------------------------------
PL/SQL is the procedural language extension to the Oracle's Structured Query Language, and is a block
structured language that enables developers to code procedures, functions, and unnamed blocks that
combine SQL with procedural statements.

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.

A PL/SQL block has three parts to it:


• Declaration objects of the block are declared here
• Execution objects of the block are defined here to manipulate data
• Exception error handling logic is placed here

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.

Variables and Constants:


---------------------------
The program stores values in variables and constants. As the program executes, the values of variables
can change, but the values of constants cannot.

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.

Displaying user Messages on the Screen:


Programming tools require a method through which messages can be displayed to the user on
the screen.

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]

ii)Steps for writing PL/SQL programs in SQL prompt

Step 1:

In SQL prompt type

ed aa [then press enter key] [or you can give any name]

In the new notepad file type the following program */

/*Program to perform addition of two numbers using PL/SQL */


declare

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

--In the SQL prompt then type the following command


*/

SQL> set serveroutput on


SQL> @ 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

PL/SQL procedure successfully completed.

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

PL/SQL procedure successfully completed.

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

PL/SQL procedure successfully completed.

/*Program to perform arithmetic operations*/


declare
a number(3):=&a;
b number(3):=&b;
c number(3):=&c;

add number(4);
product number(3);
average number(4,2);
begin
add:=a+b+c;
product:=a*b*c;
average:=add/3;

dbms_output.put_line('The addition of three number is' || add ||'The multiplication of


three no is' || product);

dbms_output.put_line('The multiplication of three no is' || product);

dbms_output.put_line('The average of three numbers is' || average);

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

/*Program to perform number raise to the power of second number*/

declare

a number(3);
b number(2);
c number(5);
begin
a:=&a;
b:=&b;
c:=power(a,b);

PNo: 104
TECH IQ Technologies

dbms_output.put_line('The result is' ||c);


end;
OUTPUT:
SQL> @ a2
Enter value for a: 2
old 7: a:=&a;
new 7: a:=2;
Enter value for b: 3
old 8: b:=&b;
new 8: b:=3;
The result is8

PL/SQL procedure successfully completed.

--program to calculate simple interest


declare
p number;
r number;
t number;
i number;
begin
p:=&p;
r:=&r;
t:=&t;
i:=(p*r*t)/100;
dbms_output.put_line('the simple interest'||i);
end;
/

--program to convert temp from centigrade to fahrenheit


declare
c number;
f number;
begin
c:=&c;
f:=((9/5)*c)+32;
dbms_output.put_line('the temperature in fahrenheit is' ||f);
end;
/

/*Program to perform number raise to the power of second number*/

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

PL/SQL procedure successfully completed.

/*Program to ALTER employees detail*/

drop table emp13;

Create table emp13(empno number(3),ename varchar2(12),job varchar2(12),city


varchar2(12),hiredate date,
salary number(5),comm number(3),mgr number(3));

SQL> desc emp13


Name Null? Type
----------------------------------------- -------- ----------------------------

EMPNO NUMBER(3)
ENAME VARCHAR2(12)
JOB VARCHAR2(12)
CITY VARCHAR2(12)
HIREDATE DATE
SALARY NUMBER(5)
COMM NUMBER(3)
MGR NUMBER(3)

insert into emp13 values(1,'SANDEEP','ENG','HYDERABAD','24-JUN-2009',6000,473,274);

insert into emp13 values(2,'PRAKASH','DOCTOR','BANGLORE',


'03-NOV-2005',5000,374,242);

insert into emp13 values(3,'SALIM','CLERK','NEW DELHI',


'02-MAY-2008',7384,384,884);

insert into emp13 Values(4,'JUNAID','PILOT','BOMBAY','18-APR-2009',3848,273,384);

insert into emp13 values(5,'SURESH','MANAGER','MADRAS',


'15-FEB-2005',3873,374,749);

insert into emp13 values(6,'SALMAN','MANAGER','NEW DELHI',


'15-AUG-2005',4555,374,653);

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;

insert into emp13 values(en,ena,jb,city,dt,sal,c,m);


del_eno:=&del_eno;
delete from emp13 where empno=del_eno;
up_eno:=&up_eno;
update emp13 set salary=salary*2.10 where empno=up_eno;
end;
/
OUTPUT:

ENO ENAME CITY JOB SALARY COMM


---- ---------- ---------- ---------- ---------- ----------
111 AHMED HYDERABAD MANAGER 6758 543
222 HAMED BANGLORE DOCTOR 8475 352
333 ASLAM BOMBAY CLERK 8574 643
444 JUNAID BANGLORE DOCTOR 4735 934

SQL> @ aa

Enter value for en: 555


old 11: en:=&en;
new 11: en:=555;
Enter value for ena: SAJID
old 12: ena:='&ena';
new 12: ena:='SAJID';
Enter value for city: NAGPUR
old 13: city:='&city';
new 13: city:='NAGPUR';
Enter value for jb: CLERK
old 14: jb:='&jb';
new 14: jb:='CLERK';
Enter value for sal: 8904
old 15: sal:=&sal;
new 15: sal:=8904;
Enter value for c: 364
old 16: c:=&c;
new 16: c:=364;
Enter value for del_eno: 222
old 18: del_eno:=&del_eno;
new 18: del_eno:=222;
Enter value for up_eno: 333

PNo: 107
TECH IQ Technologies
old 20: up_eno:=&up_eno;
new 20: up_eno:=333;

PL/SQL procedure successfully completed.

Values after program executed are:


SQL> select * from emp123;

ENO ENAME CITY JOB SALARY COMM


----- ---- ---------- ---------- ---------- ---------- ----------
111 AHMED HYDERABAD MANAGER 6758 543
333 ASLAM BOMBAY CLERK 9431.4 643
444 JUNAID BANGLORE 555 4735 934
555 SAJID NAGPUR CLERK 8904 364

iii) Condition Control Statements in PL/SQL:

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>

ELSIF <Condition> then


<action>

ELSIF <Condition> then


<action>
ELSE

<action>

END IF:

2. Iterative or Looping statements:


The statements under the looping will be executed repeatedly until the condition becomes false.
Looping means repeatedly executed the statements.

2.1 WHILE loop:


Syntax: WHILE<Condition>
Loop
<Action>
END LOOP;
2.2 The FOR Loop

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

/*Program to find biggest of three numbers*/

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;
/

PL/SQL procedure successfully completed.

/*Program to find whether number is even or odd*/

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*/

drop table emp13;

Create table emp13(empno number(3),ename varchar2(12),


job varchar2(12),city varchar2(12),hiredate date,
salary number(5),comm number(3));

insert into emp13 values(1,'SANDEEP','ENG','HYDERABAD','24-JUN-2009',6000,473);


insert into emp13 values(2,'PRAKASH','DOCTOR','BANGLORE','03-NOV-2005',5000,374);
insert into emp13 values(3,'SALIM','CLERK','NEW DELHI','02-MAY-2008',7384,384);
insert into emp13 Values(4,'JUNAID','PILOT','BOMBAY','18-APR-2009',3848,273);
insert into emp13 values(5,'SURESH','MANAGER','MADRAS','15-FEB-2005',3873,374);
insert into emp13 values(6,'SALMAN','MANAGER','NEW DELHI','15-AUG-2005',4555,374);

commit;

SQL> select * from emp13;

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);

elsif total>5000 and total<10000 then


rate:=0.5;
dbms_output.put_line('THe tax rate is ' || (rate*100)||'%');
tax:=(total*rate);
dbms_output.put_line('Employees original 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;
/

Program on Looping Statements

/*Program to print 1 to 10 numbers in series*/


declare
i number;
begin
i:=1;
while i<=10 loop
dbms_output.put_line(i);
i:=i+1;
end loop;
end;
/
OUTPUT:
SQL>@ a9
1
2
3
4
5
6
7
8
9
10

/*Program to find fibonacci series of given number*/


declare
a number;
b number;
c number;
i number;
x number;
begin
a:=&a;
b:=0;
c:=1;
i:=3;
dbms_output.put_line(b);
dbms_output.put_line(c);
while i<=a loop
x:=b+c;
dbms_output.put_line(x);
b:=c;
c:=x;
i:=i+1;
end loop;
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;

Create table emp(empno number(3),ename varchar2(12),


job varchar2(12),city varchar2(12),hiredate date,salary number(5),
comm number(3),mgr number(3));

insert into emp values(1,'SANDEEP','ENG','HYDERABAD','24-JUN-2009',6000,473,274);


insert into emp values(2,'PRAKASH','DOCTOR','BANGLORE','03-NOV-2005',5000,374,242);
insert into emp values(3,'SALIM','CLERK','NEW DELHI','02-MAY-2008',7384,384,884);
insert into emp Values(4,'JUNAID','PILOT','BOMBAY','18-APR-2009',3848,273,384);
insert into emp values(5,'SURESH','MANAGER','MADRAS','15-FEB-2005',3873,374,749);
insert into emp values(6,'SALMAN','MANAGER','NEW DELHI','15-AUG-2005',4555,374,653);
insert into emp values(7,'RASHED','BUSINESS','NAGPUR','13-APR-2002',4235,374,364);
insert into emp values(8,'AMJAD','SCIENTIST','PUNE','17-MAR-2009',6456,374,653);

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;

update emp set salary=salary+2000 where name='SALIM';


update emp set salary=salary+3000 where name='RASHED';

select sum(salary) into total_sal from emp;

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'.

General Cursor Attributes:


When the Oracle engine creates an Implicit or Explicit cursor, cursor control variables are also created to
control the execution of the cursor. Whenever any cursor is opened and used, the Oracle engine creates a
set of four system variables which keeps track of the 'Current' status of a cursor. These cursor variables
can be accessed and used in a PL/SQL code block. Both Implicit and Explicit cursor has four attributes.

They are described below:

---------------------------------------------------------------------------
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.

Implicit Cursor Attributes:


----------------------------------

Attribute Name Description


------------------ -----------------------------------------------------------
1. %ISOPEN The Oracle engine automatically opens and closes the SQL cursor after executing its
associated select, insert, update or delete SQL statement has been processed in cas of implicit cursors.
Thus the SQL%ISOPEN attribute of an implicit cursor cannot be referenced outside of its SQL statement. As
a result, SQL%ISOPEN always evaluates to FALSE.

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’ */

drop table emp33;

CREATE TABLE EMP33(ENO NUMBER(3) NOT NULL,


ENAME VARCHAR2(10),JOB VARCHAR2(10),SALARY NUMBER(5),
HIREDATE DATE,DEPTNO NUMBER(4),CITY VARCHAR2(12),
EXP NUMBER(2));

INSERT INTO EMP33 VALUES(1,'SURESH','CLERK',12394,'12-APR-2009',10,'DELHI',6);


INSERT INTO EMP33 VALUES(2,'SAMI','DOCTOR',1234,'23-MAY-2006',20,'HYDERABAD',3);
INSERT INTO EMP33 VALUES(3,'AMJAD','DRIVER',7465,'05-AUG-2006',10,'DELHI',2);
INSERT INTO EMP33 VALUES(4,'AHMED','MANAGER',2345,'06-JUN-2003',20,'BOMBAY',1);
INSERT INTO EMP33 VALUES(5,'ZAHEER','BUSINESS',4532,'18-JUL-2009',20,'HYDERABAD',7);
INSERT INTO EMP33 VALUES(7,'MAJEED','DOCTOR',8473,'18-SEP-2005',10,'BANGALORE',6);
INSERT INTO EMP33 VALUES(8,'JUNAID','TEACHER',3748,'29-NOV-2003',10,'MADRAS',3);

COMMIT;

select * from emp33;

ENO ENAME JOB SALARY HIREDATE DEPTNO CITY EXP


----- ------- ------- ---------- --------- ---------- ----- ----
1 SURESH CLERK 10000 15-SEP-06 10 DELHI 2

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

/*1. Example for SQL%FOUND:

The HRD manager decided to raise the salary of employees by 1.05.


Write a PL/SQL block to accept the employee number and update the salary of that employee.
*/

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

PL/SQL procedure successfully completed.

SQL>

/*2. Example for SQL%NOTFOUND:


The HRD manager decided to raise the salary of employees by 3000 whose city is either in
('SHIMLA','PUNE','INDORE') and their experience is greater than 5 years.
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

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

PL/SQL procedure successfully completed.

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

PL/SQL procedure successfully completed.

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.

Explicit Cursor Management:


The steps involved in using an explicit cursor and manipulating data in its active set are:

*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.

The functionality of OPEN, FETCH and CLOSE commands:


Initialization of a cursor takes place via the OPEN statement, this
*Defines a private SQL area named after the cursor name
*Executes a query associated with the cursor which retrieves the table data and populates the named
private SQL area in memory i.e. creates the ACTIVE Data Set.
*Sets the cursor row pointer in the Active Data Set to the first record.

->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;

Explicit Cursor Attributes:


--------------------------------
Similar to the cursor attributes in case of implicit cursors, four attributes are associated with explicit
cursors.

Attribute Name Description


------------------ -----------------------------------------------------------
1. %ISOPEN Evaluates to TRUE, if an explicit cursor is open; or to FALSE, if it is closed. The syntax for
accessing this attribute is cursorname%ISOPEN

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.

/*4.Example for ISOPEN Explicit Cursor*/


Table: 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

PNo: 120
TECH IQ Technologies

Table: EMP_RAISE

SQL> drop table emp_raise;


SQL> create table emp_raise(eno number(3),raise_date date,
salary number(5));

/*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

CURSOR C_EMP IS select eno,salary from emp33 where deptno=20;


emp_code number;
salary number;

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> create table emp_raise(eno number(3),raise_date date, salary number(5));

SQL> select * from emp_raise;


ENO RAISE_DAT SALARY
---------- --------- ----------
2 17-APR-16 1419
4 17-APR-16 6147
5 17-APR-16 5212

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);

set serveroutput on;

select * from emp;

//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;

IF NOT c_high_sal%ISOPEN THEN


DBMS_OUTPUT.PUT_LINE('Cursor is closed ');
END IF;
END;

/*7.Example for Explicit %ISOPEN and %NOT FOUND cursor*/

/*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.*/

->Data in the emp33 table before executing a %FOUND cursor


SQL> select eno,ename,salary,deptno from emp33;

ENO ENAME SALARY DEPTNO


---------- ---------- ---------- ----------
1 SURESH 12394 10
2 SAMI 2653 20

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;

insert into emp_raise values(str_eno,sysdate,num_sal*0.05);


end loop;
commit;
close c_emp;
else
dbms_output.put_line('Unable to open Cursor');
end if;
end;
/

OUTPUT:
select eno,ename,salary,deptno from emp33;

ENO ENAME SALARY DEPTNO


---------- ---------- ---------- ----------
1 SURESH 12394 10
2 SAMI 2786 20
3 AMJAD 7838 10
4 AHMED 12067 20
5 ZAHEER 10231 20
7 MAJEED 11473 10
8 JUNAID 6748 10

7 rows selected.

SQL> select * from emp_raise;

ENO RAISE_DAT SALARY


---------- --------- ----------
2 17-APR-12 133
4 17-APR-12 575
5 17-APR-12 487

PNo: 123
TECH IQ Technologies

/*Example for SQL%ROWCOUNT.


8. Write PL/SQL block to accept emplyeee number and update the salary of that employee who is working
as 'DOCTOR' by 1.15. Display appropriate message based on the existence of the record in the employee
table.*/

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

PL/SQL procedure successfully completed.

Cursor FOR Loop:


In most situations that require an explicit cursor, we can simplify coding by using a cursor FOR loop
instead of the OPEN, FETCH, and CLOSE statements.

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.

A cursor for loop automatically does the following:


---------------------------------------------------------------
*Implicity declares its loop index as a %rowtype record
*opens a cursor
*fetches a row from the cursor for each loop iteration
*closes the cursor when all rows have been processed.

->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.*/

->Data in the tables before executing the cursor program

SQL> select eno,ename,salary,deptno from emp33;

ENO ENAME SALARY DEPTNO


---------- ---------- ---------- ----------
1 SURESH 12394 10
2 SAMI 3685 20
3 AMJAD 7838 10
4 AHMED 12067 20
5 ZAHEER 10231 20
7 MAJEED 15173 10
8 JUNAID 6748 10

SQL> delete from emp_raise;


SQL>
declare
/*Declaration of a cursor which fetches the records having dept_no 30*/
CURSOR c_emp IS SELECT eno, salary from emp33;

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*/

update emp33 set salary=emp_rec.salary+(emp_rec.salary*0.05) where eno=emp_rec.eno;


dbms_output.put_line(' Updated salary sucessfully for employee no ' || emp_rec.eno || ' for table emp33');

insert into emp_raise values(emp_rec.eno,sysdate,emp_rec.salary*0.05);


dbms_output.put_line(' Added new record sucessfully for employee no ' || emp_rec.eno || ' in table
emp_raise');

end loop;
commit;
end;
/

OUTPUT:

PL/SQL procedure successfully completed.


SQL> select eno,ename,salary,deptno from emp33;
ENO ENAME SALARY DEPTNO
---------- ---------- ---------- ----------
1 SURESH 12394 10
2 SAMI 3869 20
3 AMJAD 7838 10
4 AHMED 12670 20
5 ZAHEER 10743 20
7 MAJEED 15173 10
8 JUNAID 6748 10

PNo: 125
TECH IQ Technologies

SQL> select * from emp_raise;

ENO RAISE_DAT SALARY


---------- --------- ----------
2 17-APR-16 184
4 17-APR-16 603
5 17-APR-16 512

/*
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.

Declaring a Parameterized Cursor:


------------------------------------------
Syntax:
CURSOR cursor_name (variable_name datatype) IS SELECT stmt.....;

Opening a Parameterized Cursor and passing values to the Cursor:


---------------------------------------------------------------------------------
Syntax:
OPEN cursor_name(value/variable/expression)

Example program on Parameterized Cursor:


----------------------------------------------------
10. 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
decreease 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.

1.Table Name : ITEM_TRANSACTION


------------------------------------------
SQL> create table ITEM_TRANSACTION(Itemid number(4),Description varchar2(20),Quantity number(3));

2.Table Name : ITEM_MASTER


-----------------------------------
SQL> create table ITEM_MASTER(Itemid number(4) PRIMARY KEY,Description varchar2(20),Bal_stock
number(5));

Inserting Values into ITEM_TRANSACTION Table


---------------------------------------------------------------
Insert into Item_Transaction values(1,'MOBILE',5);
Insert into Item_Transaction values(2,'CAP',15);
Insert into Item_Transaction values(3,'COMPUTER',4);

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;

SQL> SELECT * FROM ITEM_TRANSACTION;

ITEMID DESCRIPTION QUANTITY


---------- -------------------- ----------
1 MOBILE 5
2 CAP 15
3 COMPUTER 4
4 BOOK 10
5 WATCH 16
6 KEYBOARD 13
7 RAM 8

DECLARE

/*Cursor c_item_tran retrieves all the records of table Item_Transaction*/

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*/

CURSOR c_itemchk(mastitemid number) IS


SELECT itemid from ITEM_MASTER where itemid=mastitemid;

/* variable that hold data from the cursor c_item_tran */


itemidno number(4);
descrip varchar2(30);
quantity number(4);

/*Variable that hold data from the cursor c_itemchk*/

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;

/*Open the c_itemchk cursor


Note: The value of variable passed to the c_itemchk cursor is set to the value of item id in the current row of cursor
c_item_tran */

OPEN c_itemchk (itemidno);


FETCH c_itemchk INTO mast_ins_uptd;

/*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;

ITEMID DESCRIPTION QUANTITY


---------- -------------------- ----------
1 MOBILE 5
2 CAP 15
3 COMPUTER 4
4 BOOK 10
5 WATCH 16
6 KEYBOARD 13
7 RAM 8

SQL> select * from item_master;

ITEMID DESCRIPTION BAL_STOCK


---------- -------------------- ----------
1 MOBILE 20
2 CAP 60
3 COMPUTER 16
4 BOOK 40
5 WATCH 64
6 KEYBOARD 52
7 RAM 32

vi)CONCURRENCY CONTROL IN ORACLE


Users manipulate Oracle table data via SQL or PL/SQL sentences. An Oracle transaction can be made up of
a single SQL sentence or several sentences. This gives rise to Single Query Transaction(SQT) and Multiple
Query Transaction (MQT).

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'.

Oracle's Default Locking Strategy - Implicit Locking:


I. Type of Lock to be applied
II. Level of Lock to be applied

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.

The two types of locks supported by Oracle are:


---------------------------------------------------------
1. Shared Locks:
-------------------
a). Shared locks are placed on resources whenever a Read operation(SELECT) is performed.
b). Multiple shared locks can be simultanesouly set on a resource.

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.

II. LEVEL OF LOCKS:


------------------------
A table can by decomposed into rows and a row can be further decomposed into fields. Hence, if an
automatic locking system is designed to be able to lock the fileds of a record, it will be the most flexible
locking system available.

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".

Oracle provides the following three lovels of locking:


i. Row level
ii. Page level
iii. Table level

-> 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.

Consider the following SCENARIO:

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.

Who can explicitly lock?


-> Users can lock tables they own or any tables on which they have been granted table privileges ( such as
select, insert, update, delete).

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.

1. The SELECT.....FOR UPDATE statement:


---------------------------------------------------
It is used for acquiring exclusive row level locks in anticipation of performing updates on records. This
clause is generally used to signal the Oracle engine that data currently being used needs to be updated. It
is often followed by one or more update statements with a where clause.

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.

select * from client_master where cno=3 FOR UPDATE NOWAIT;

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:

SQL> 00054: resource and acquire with NOWAIT specified.

The SELECT ....FOR UPDATE cannot be used with the following:


*DISTINCT and the GROUP BY clause
*SET Operators and GROUP functions

2. Using Lock Table statement:


-------------------------------------
To manually override Oracle's default locking strategy by creating a data lock in a specific mode.
Syntax:
-----------
LOCK TABLE tablename IN {ROW SHARE\ROW EXCLUSIVE\SHARE UPDATE\SHARE\SHARE ROW
EXCLUSIVE\EXCLUSIVE} [NOWAIT]
where,
tablename: Indicates the name of table(s), view(s) to be locked. In case of VIEWS, the lock is placed on
underlying tables.

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.

Share RowExclusive: They are used to look at a whole table, to selective


updates and to allow other users to look at rows in the table but not lock the table in share mode or to
update rows.

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).

Table Name: EMP

drop table emp;

Create table emp(empno number(3),ename varchar2(12),


job varchar2(12),city varchar2(12),hiredate date,salary number(5),
comm number(3),mgr number(3));

SQL> desc emp


Name Null? Type
----------------------------------------- -------- ---------------------------
EMPNO NUMBER(3)
ENAME VARCHAR2(12)
JOB VARCHAR2(12)
CITY VARCHAR2(12)
HIREDATE DATE
SALARY NUMBER(5)
COMM NUMBER(3)
MGR NUMBER(3)
insert into emp values(1,'SANDEEP','ENG','HYDERABAD','24-JUN-2009',6000,473,274);
insert into emp values(2,'PRAKASH','DOCTOR','BANGLORE','03-NOV-2005',5000,374,242);
insert into emp values(3,'SALIM','CLERK','NEW DELHI','02-MAY-2008',7384,384,884);
insert into emp Values(4,'JUNAID','PILOT','BOMBAY','18-APR-2009',3848,273,384);
insert into emp values(5,'SURESH','MANAGER','MADRAS','15-FEB-2005',3873,374,749);
insert into emp values(6,'SALMAN','MANAGER','NEW DELHI','15-AUG-2005',4555,374,653);
insert into emp values(7,'RASHED','BUSINESS','NAGPUR','13-APR-2002',4235,374,364);
insert into emp values(8,'AMJAD','SCIENTIST','PUNE','17-MAR-2009',6456,374,653);

COMMIT;
SQL> select * from emp;

EMPNO ENAME JOB HIREDATE SAL COMM DEPTNO


------ --------- ---------- ------------ -------- ---------- ----------
1 SAMI DOCTOR 23-MAY-08 36700 383 10

2 SURESH CLERKS 02-JUN-06 37832 384 20

3 AMJAD SALESMAN 19-OCT-05 84724 394 30

4 SALIM SALESMAN 12-APR-04 38944 939 30

5 RASHEED MANAGERS 29-AUG-08 58348 834 40

6 PRADEEP ANALYSTS 16-NOV-01 47834 534 50

44 SURESH DOCTOR 12-OCT-05 5000 500 30


55 NARESH DOCTOR 03-AUG-02 7400 745 30
An INSERT Operation:
-----------------------------
Focus:To check the behavior of the Oracle Engine in multi-user environment when an INSERT operation is
performed.

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.

insert into emp values(10,'S. ZAHEER','DENTIST','AGRA',


'17-FEB-2004',2456,374,293);
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
7 ZAHEER ENGINEER 5000 02-APR-08
44 SURESH DOCTOR 5000 12-OCT-05
55 SURESH DOCTOR 5000 12-OCT-05
CLIENT B:
------------
-> Client B fires a SELECT statement on 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
->Client B performs an INSERT operation
Syntax:
---------
insert into emp values(11,'BASEER','SHOP','DELHI','17-JUN-2002',2456,374,293);
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.

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;

EMPNO ENAME JOB SAL HIREDATE


---------- ------------ -------------- ---------- ---------
1 SAMI DOCTOR 36700 23-MAY-08
2 SURESH CLERKS 37832 02-JUN-06
3 AMJAD SALESMAN 34724 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 with a FOR UPDATE clause on the EMP table.
Syntax:
---------
SQL> SELECT EMPNO,ENAME,JOB,SALary,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;

* Client A performs an update operation on the EMPNO=5 in the EMP table.


Syntax:
---------
SQL> update emp set salary=salary-700 where empno=5;

1 row updated.
SQL> select empno,ename,job,salary,hiredate from emp FOR UPDATE;

EMPNO ENAME JOB SAL HIREDATE


---------- ------------ -------------- ---------- ---------
1 SAMI DOCTOR 36700 23-MAY-08
2 SURESH CLERKS 37832 02-JUN-06
3 AMJAD SALESMAN 34724 19-OCT-05
4 SALIM SALESMAN 38944 12-APR-04
5 RASHEED MANAGERS 38348 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 with a FOR UPDATE clause and NOWAIT clause on the EMP table.

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;

SQL> create table ACCOUNTS(Acc_Id varchar2(8),


Name varchar2(10),Balance number(5));
Insert into Accounts values('AC001','ANUJ',5000);
Insert into Accounts values('AC002','ROBERT',10000);
Insert into Accounts values('AC003','MITA',5000);
Insert into Accounts values('AC004','SUNITA',15000);
Insert into Accounts values('AC005','MELBA',5000);
SQL> SELECT * FROM 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

vii)Working with Exceptions:


PL/SQL enables the user to anticipate and trap for certain runtime errors. These errors are known as exceptions and, if not handled in
the PL/SQL block, would cause the program to terminate under abnormal conditions. Exceptions can be internally defined by Oracle
or the user.

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.

Steps for trapping an error include:


• Declare the name for the user exception within the declaration section of the block
• Raise the exception explicitly within the executable portion of the block using the raise command
• Reference the declared exception with an error-handling routine

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;

Note: We can also raise a predefined exception explicitly.: RAISE INVALID_NUMBER;

Using SQLCODE and SQLERRM:


----------------------------------
In an exception handler, we can use the functions SQLCODE and SQLERRM to find out which error occurred and to get the error
message.

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

Creating Table COMMISSION_PAYABLE Table:


------------------------------------------------------------
SQL> create table commission_payable(salesman_no varchar2(8),
date_of_payment date,comm_amount number(5));

*/
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';

INSERT INTO commission_payable


VALUES(sales_no,sysdate,sales_amt*comm_rate/100);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('Salesman No' || sales_no|| ' is not
present in the sales_master table');

END;
/

OUTPUT:
SQL> SELECT * FROM SALES_MASTER;

SALESMAN_NO NAME COMM_RATE ACTUAL_SALES


----------- --------------- ---------- ------------
1 ASLAM 300 500
2 JUNAID 150 600
3 ZAHEER 250 1000
4 SALMAN 200 2000

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;

PL/SQL procedure successfully completed.

SQL> select * from comm_payable;

SALESMAN_NO SALESDATE COMM_AMT


----------- --------- ----------
3 30-OCT-09 2500

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

PL/SQL procedure successfully completed.

/*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

Creating Table Client_Master:


---------------------------------------
DROP TABLE CLIENT_MASTER1;

create table client_master1(client_no varchar2(6) PRIMARY KEY,


name varchar2(12),address1 varchar2(12), address2 varchar2(12),
city varchar2(15), state varchar2(12),pincode number,
bal_due number(6,2));

insert into client_master1 Values('C0001','ahmed','dsnr','satoshngr','Hyderabad','AP',50003,300);

insert into client_master1 values('C0002','SAMI','LDRW','LB SPACE','Hyderabad','AP',50003,300);


insert into client_master1 values('C0003','SALIM','HFRF','LB SPACE','Hyderabad', 'AP',50563,340);
insert into client_master1 values('C0004','MAHMOOD','ST COL','BHEL','Hyderabad', 'AP',59454,473);
insert into client_master1 Values('C0005','GAFOOR','HFRF','KPHB','Hyderabad', 'AP',50563,533);
insert into client_master1 Values('C0006','SAJID','BANK ST','VK COL','PUNE', 'MH',48389,483);

SELECT * FROM CLIENT_MASTER1;

CLIENT_NO NAME ADDRESS1 ADDRESS2 CITY STATE PINCODE BAL_DUE


---------- -------- ---------- --------- ------- ------- -------- -------
C0001 BAYROSS BANKSTREET RTC X ROAD BOMBAY MAHRASHTRA 400054 1500

C0002 VANDANA TV TOWER MALAKPET MADURAI TAMIL NADU 780001 2500

C0003 ABDUL SAMI WATER TANK DSNR BOMBAY MAHRASHTRA 400057 5000

C0004 SURESH DMRL LAB NADER GUL BOMBAY MAHRASHTRA 400056 0

C0005 MUJAHED MH SCHOOL MOGHALPURA SHIMLA DELHI 100001 2000

C0006 MUDASSIR FACTORY RD BALANAGAR BOMBAY MAHRASHTRA 400050 4939


*/
DECLARE
bal_amt number(10,2);
trans_amt number(10,2);
cl_no varchar2(7);
trans_type char(1);

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;
/

User Defined Exception Handling (For Business Rule Validation)


-------------------------------------------------------------------------------
In commercial application data being manipulated needs to be validated against business rules. If the data violates a
business rule, the entire record must be rejected.
Syntax:
------------
DECLARE
<Exceptionname> Exception;

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.

Creating Table SALESMAN_MASTER1


--------------------------------------------------
SQL>

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,300);

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.

Procedures and Functions are made up of:


------------------------------------------------------------------
1. A declarative part
2. An executable part
3. An optional exeception-handling part

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.

Exception Handling Part:


-------------------------------------
This part contains code that peforms required actions to deal with exceptions that may be raised during
the execution of code in the executable part. An Oracle exception handler can be redirected to the
exceptionhandling sectino of the procedure or function where the procedure or function determines the
actual action that must be carried out by Oracle's exception handler.

Advantages of Using a Procedure or Function:


-------------------------------------------------------------------------
1. Security:
Stored procedures and unctions can help enforce data security. For e.g. by giving permission to a
procedure or function that can query a table and granting the procedure or function to users, permissions
to manipulate the table itself need not be granted to users.

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.

Difference between Function /Procedure


*A function must return a value back to the caller. A function can return only one value to the calling
PL/SQL code block.

*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.

SYNTAX FOR CREATING STORED PROCEDURE and FUNCTIONS:


----------------------------------------------------------------------------

1.Syntax for Creating Procedure:


--------------------------------------------------
CREATE OR REPLACE PROCEDURE [schema.] procedurename (argument {IN,OUT,IN
OUT}data type,...) {IS,AS}
variable declarations;
constant declarations;

BEGIN
PL/SQL subprogram body;
EXCEPTION
exception PL/SQL block;
END;

Keywords and Parameters:


------------------------------------------

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.

procedure : It is the name of the procedure to be created.

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.

2.Syntax for Creating Function:

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;

Keywords and Parameters:

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.

function : It is the name of the function to be created.

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

//Example program on FUNCTIONS


-- Function to return the sum of 3 values.

SQL>ed fun_tot

create or replace function fun_tot(a number, b number, c number) return number is


total number;
begin
total:=a+b+c;
return (total);
end;
/

//Calling function using 'select' query


SQL> select fun_tot(10,20,30) from dual;

FUN_TOT(10,20,30)
-----------------
60

//Calling function using PL/SQL program

declare
a number(5);
begin
a:=fun_tot(5,10,15) ;
dbms_output.put_line('Calculted value : ' || a);
end;

-- Function to return the average of 3 values.

SQL> ed fun_avg

create function fun_avg(a in number, b in number, c in number) return number is


average number;

begin
average:=(a+b+c)/3;
return(average);
end;
/

SQL> @ fun_avg

Function created.

SQL> select fun_avg(5,10,15) from dual;

FUN_AVG(5,10,15)
----------------
10

PNo: 148
TECH IQ Technologies
-- Function to return the simple interest.

SQL> ed fun_si

create function fun_si(p number, r number, t number) return number is


interest number(8,2);

begin
interest:=(p*r*t)/100;
return(interest);
end;
/

SQL> @ fun_si

//Calling using 'SQL' queries


SQL>select fun_si(8674,3,5) from dual;

//Calling using 'PL/SQL' program

declare
result number(7);
begin
result:=fun_si(8674,3,5);
dbms_output.put_line('Simple interest is ' || result);
end;

--Function to convert 'DOLLAR' into equivalent rupees.


CREATE OR REPLACE FUNCTION F3(D NUMBER) RETURN NUMBER IS
DOLLAR NUMBER;
BEGIN

DOLLAR:=(48*D);
RETURN (DOLLAR);
END;
/

//Calling function using 'SQL'queries


sql>select f3(500) from dual;

//calling function using 'PL/SQL' program


declare
currency_conversion number(10);
begin
currency_conversion:=f3(700);
dbms_output.put_line('Equivalen Indian rupees = ' || currency_conversion);
end;

-- Function to return the grade on result.

SQL>ed fun_gra

create function fun_gra(a number, b number, c number) return varchar is


grade char;
ave number(4,1);
begin

PNo: 149
TECH IQ Technologies
ave:=(a+b+c)/3;

if (a>=35 and b>=35 and c>=35) then


if (ave>=75 and ave<=100) then
grade:='A';
elsif (ave>=60 and ave<75) then
grade:='B';
elsif (ave>=50 and ave<60) then
grade:='C';
elsif (ave>=35 and ave<50) then
grade:='D';
end if;
else
grade:='F';
end if;
return(grade);
end;
/

SQL> @ fun_gra
Function Created

SQL> select fun_gra(70,65,78) from dual;

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);

dbms_output.put_line('Grade is ' || a);


end;

//Retrieve data
select * from student;

/*
Recursion: It refers to calling the same function within the subprogram again and again repeatedly.

Example program on Recursion

*/
SQL> ed fact

Create Function fact (n number) return number is


begin
if n=0 then
return (1);
else
return(n*(n-1));
end if;

PNo: 151
TECH IQ Technologies
end;
/

SQL> @ fact

Function created.

SQL> select fact(5) from dual;

FACT(5)
----------
20

/*Example for using a Function:


-----------------------------------------------
Focus:
----------
Consider the tables 'ITEM_MASTER' and 'ITEM_TRANSACTION'. Both the tables belong to an inventory
system. The 'Item_Transaction' table is used to register the inward movement stock, as it happens. At
regular intervals, as a batch process the stock value must be written to the 'Item_Master' table.

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.

1.Table Name : ITEM_TRANSACTION


------------------------------------------
SQL> drop table item_transaction;
create table ITEM_TRANSACTION(Itemid number(4),Description varchar2(20),Quantity number(3));

Inserting Values into ITEM_TRANSACTION Table


---------------------------------------------------------------

Insert into Item_Transaction values(1,'MOBILE',5);


Insert into Item_Transaction values(2,'CAP',15);
Insert into Item_Transaction values(3,'COMPUTER',4);
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;
SQL> select * from item_transaction;

ITEMID DESCRIPTION QUANTITY


---------- -------------------- ----------
1 MOBILE 10
2 WATCH 20
3 COMPUER 5

2.Table Name : ITEM_MASTER

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.

*/

CREATE OR REPLACE FUNCTION f_itemidchk(vitemidno IN number) RETURN number is

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

/*PL/SQL program to call function ‘f_itemidchk ‘ */


DECLARE
CURSOR scantable IS SELECT itemid,description,quantity FROM
item_transaction;

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);

ELSIF valexists=1 THEN

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;
/

//After program executed then


Sql>select * from item_master;

Stored Procedures: It is a set of statements written using PL/SQL (Procedural Language/Structured


Query Language). To perform some calculations on the tables of a database, we can use stored
procedures. Stored procedures are written and stored at database server. When a client contacts the
server, the stored procedure is executed, and the results are sent to the client.

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.

Example for creating 'PROCEDURE':


Step 1:
--------
SQL> ed myproc [then press EMTER KEY] then it will ask you to save file press on 'YES' button.

Step 2:
------- -
Write the following coding in the file

create or replace procedure myproc(no in int, isal out float) as


salary float;
begin
select sal into salary from emp where eno=no;
isal:=salary+500;
end;

Step 3:
-------
Click on Save and Exit button

Step 4:
--------
In SQL> prompt type

SQL>set serveroutput on [To activate Server for PL/SQL programs]

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

-- drop table stud_info;

-- create table stud_info (rno number(2),name varchar2(10),


s1 number(2), s2 number(2),s3 number(2));

//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:

//calling procedure using 'SQL' queries


exec proc_insert(1,'RAMESH',50,60,70)

select * from stud_info;

//calling procedure using 'PL/SQL' program


DECLARE

begin
proc_insert(2,'SAJID',89,93,45);
END;

select * from stud_info;

-- Procedure to update the salary of an employee.


create or replace procedure proc_update(eno number, amt number) is
begin
update emp set salARY=salARY+amt where empno=eno;
commit;
end;
/

//calling procedure using ‘SQL’ query


EXEC PROC_UPDATE(1,2000)
select * from emp;

//calling procedure using ‘PLS/SQL’ Program


DECLARE
N NUMBER;
s number;
BEGIN
N:=&N;
S:=&S;
PROC_UPDATE(n,s);
end;

PNo: 156
TECH IQ Technologies
select * from emp;

-- Procedure to select the data of table emp on deptno

create or replace procedure proc_select(dno number) is


cursor c1 is select * from emp where deptno=dno;
emprec c1%rowtype;
begin
dbms_output.put_line('Employeed Information');
dbms_output.put_line('--------------------------');
for emprec in c1
loop
dbms_output.put_line(emprec.empno || ' ' || rpad(emprec.ename,10,' ') || ' ' ||
rpad(emprec.job,10,' ') || ' ' || emprec.salary);
end loop;

end;
/

//calling using 'SQL'


exec proc_select(20)

//calling using 'PL/SQL'


DECLARE
BEGIN
proc_select(10);
end;

-- Procedure to insert the values into the table employees

create or replace procedure proc_ins3 (a number, b varchar, c varchar, d date, e number) is


begin
insert into emp (empno, ename, job, hiredate, salary) values (a, b, c, d, e);
commit;
exception
when program_error then
dbms_output.put_line('Data mismatch');
end;
/

-- Procedure to update the values in a table

create procedure proc_upd (eno number, amt number) is


begin
update emp set sal=sal+amt where empno=eno;
commit;
end;
/

PNo: 157
TECH IQ Technologies

/*PROGRAM TO INCREMENT THE HIGHEST SALARY AND DECREMENT THE LOWEST


SALARY USING PROCEDURES*/

create or replace procedure proc is


e number;
l number;
begin
select eno,salary into e,l from emp77 where salary=(select max(salary) from emp77);
update emp77 set salary=salary*1.1 where eno=e;
select eno,salary into e,l from emp77 where salary=(select min(salary) from emp77);
update emp77 set salary=salary*0.85 where eno=e;
end;
/

OUTPUT:

SQL> select * from emp77;

ENO ENAME CITY JOB SALARY HIREDATE STATE COUNTRY

1 ASIF HYD MANAGER 8795 23-AUG-06 AP INDIA

2 HAMED BANGLORE CLERK 5748 12-MAY-08 KAR INDIA

SQL> @ a

Procedure created.

SQL> execute proc;

PL/SQL procedure successfully completed.

SQL> select * from emp77;

ENO ENAME CITY JOB SALARY HIREDATE STATE COUNTRY


--- -------- ------ ------ -------- ----------- -------- ----------
1 ASIF HYD MANAGER 9675 23-AUG-06 AP INDIA

2 HAMED BANGLORE CLERK 4886 12-MAY-08 KAR INDIA

--create a procedure which gets the name and salary of the employee when the employee id is
passed.

DROP TABLE EMPLOYEE;

create table employee (eno number(4),ename varchar2(15),


COMPANY VARCHAR2(15),city varchar2(15),salary number(6));

insert into employee values(1,'SAJID','INFOSYS','MADRAS',5000);

insert into employee values(2,'SALIM','TATA','BOMBAY',6535);

PNo: 158
TECH IQ Technologies
insert into employee values(3,'JUNAID','WIPRO','DELHI',7482);

insert into employee values(4,'FARID','ACC','BOMBAY',7434);

insert into employee values(5,'ASLAM','TATA','PUNE',3845);

insert into employee values(6,'ZAHEER','SATYAM','HYDERABAD',3874);

insert into employee values(7,'LATEEF','SATYAM','HYDERABAD',8475);

insert into employee values(8,'HUSSAIN','TATA','BOMBAY',5000);


insert into employee values(9,'SURESH','ACC','BOMBAY',7000);
insert into employee values(10,'KALEEM','TATA','MADRAS',7650);
insert into employee values(11,'HAMED','INFOSYS','BOMBAY',7650);

commit;

//Creating Procedure

CREATE OR REPLACE PROCEDURE p1(id IN NUMBER, X OUT varchar,Y OUT number)


IS
BEGIN
SELECT ename,salary INTO X,Y FROM employee WHERE eno = id;
END;
/

--PL/SQL Program to call 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;

--Using IN OUT parameter in procedures:


--Procedure to increase salary of an employee by passing employee number

CREATE OR REPLACE PROCEDURE emp_salary_increase


(eid IN employee.eno%type, salary_inout IN OUT employee.salary%type) IS

tmp_sal number;

BEGIN

PNo: 159
TECH IQ Technologies
SELECT salary INTO tmp_sal FROM employee WHERE eno = eid;

IF tmp_sal between 2000 and 3000 THEN


salary_inout := tmp_sal * 1.2;

ELSIF tmp_sal between 3001 and 5000 THEN


salary_inout := tmp_sal * 1.3;

ELSIF tmp_sal > 5001 THEN


salary_inout := tmp_sal * 1.4;
END IF;
END;

--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);

dbms_output.put_line('The salary of ' || emp_rec.eno ||

' increased from '|| pre_sal || ' to '||emp_rec.salary);


END LOOP;

END;

PNo: 160
TECH IQ Technologies

ix) ORACLE PACKAGES:

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.

Invoking a Package & the Oracle Engine:


--------------------------------------------------------------
When a package is invoked, the Oracle engine performs three steps to execute it.
1. Verify user access:
Confirms that the user has 'EXECUTE' system privilege granted for the subprogram.

2. Verify procedure validity:


Checks with the data dictionary to determine whether the subprogram is valid or not. If the subprogram is
invalid, it is automatically recompiled before being executed.

3. Execute:
The package subprogram is executed.

To reference a package's subprograms and objects, you must use 'DOT Notation'.

Syntax for Dot Notation:

->Package_name.type_name
->Package_name.object_name
->Package_name.subprogram_name

In the above syntax:


------------------------------
*Package_name is the name of the declared package
*Type_name is the name of the type that is user defined, such as record
*Object_name is the name of the constant or variable that is declare by the user.
*Sub_program is the name of the procedure or function contained in the package body.

PNo: 162
TECH IQ Technologies

PACKAGE SPECIFICATION

CREATE OR REPLACE PACKAGE check_data AS


FUNCTION f_itemidchk(itemidno IN number) RETURN number;
PROCEDURE proc_insert(itemidno IN number,descrip IN varchar2,quantity IN number);
PROCEDURE proc_update(itemidno IN number,quantity IN number);
END check_data;
/

drop table item_transaction;

CREATE TABLE ITEM_TRANSACTION(ITEMID NUMBER(5),


DESCRIPTION VARCHAR2(15),QUANTITY NUMBER(5),
bal_stock number(8));

INSERT INTO ITEM_TRANSACTION VALUES(1,'BOOK',10,50);


INSERT INTO ITEM_TRANSACTION VALUES(2,'PEN',20,49);
INSERT INTO ITEM_TRANSACTION VALUES(3,'CAP',12,60);

COMMIT;

drop table item_master;

CREATE TABLE ITEM_MASTER(ITEMID NUMBER(5),


DESCRIPTION VARCHAR2(15),QUANTITY NUMBER(5),
BAL_STOCK NUMBER(6));

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;

PROCEDURE proc_insert(itemidno IN number,descrip IN varchar2,quantity IN number) IS

BEGIN
INSERT INTO item_master (id,description,quantity)

PNo: 163
TECH IQ Technologies
values(itemidno,descrip,quantity);
END;

PROCEDURE proc_update(itemidno IN number,quantity IN number) IS


BEGIN
UPDATE item_master set bal_stock=bal_stock+quantity where id=itemidno;
END;
END check_data;

-- Calling the PACKAGE in the PL/SQL CODE

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

x)OVERLOADING PROCEDURES and FUNCTIONS:


A package is an Oracle object that can hold a number of other objects like procedures and functions. More
than one procedure or function with the same name but different parameters can be defined within a
package or within a PL/SQL declaration block.

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.

CREATE OR REPLACE PACKAGE BODY check_data IS


FUNCTION value_ok(date_in IN date) RETURN BOOLEAN IS
BEGIN
RETURN date_in<=sysdate;
END;

FUNCTION value_ok(number_in IN number) RETURN BOOLEAN IS


BEGIN
RETURN number_in>0;
END;

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.

Overloading Built-in PL/SQL Functions and Procedures:


-------------------------------------------------------------------------------
PL/SQL itself makes extensive use of overloading. An example of an overloaded function in PL/SQL is the
TO_CHAR function. Function overloading allows develoers to use a single function to convert both numbers
and dates to character format.

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.

Where to Overload Functions and Procedures:


-----------------------------------------------------------------------
There are only two places in PL/SQL programs where the procedures and functions can be overloaded.

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;

ORA-0955: name is already used by an existing object.

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;

CREATE PROCEDURE trim_and_center(string_in IN varchar2, string_out OUT varchar2) IS


BEGIN

PNo: 166
TECH IQ Technologies
----------
----------
END;

Such procedure overloading is not allowed


------------------------------------------------------------------

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

CREATE OR REPLACE PACKAGE BODY check_data IS


FUNCTION value_ok(date_in IN date) RETURN BOOLEAN IS
BEGIN
RETURN date_in<=sysdate;
END;

FUNCTION value_ok(number_in IN number) RETURN BOOLEAN IS


BEGIN
RETURN number_in>0;
END;

END;

The call to the function will either be :


Is_date_ok:=check_data.value_ok('12-Dec-97')
Or
Is_number_ok:=check_data.value_ok(23)

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.

The overloading attempts will result in the following error messages:


PLS-00307: too many declarations of 'value_check' match this 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:
---------------

PROCEDURE develop_analysis (quarter_end_in IN date, sales_in IN number) IS


PROCEDURE revise_estimate(date_in IN date ) IS
BEGIN
DECLARE
PROCEDURE revise_estimates(dollars_in IN number) IS
BEGIN
----------
----------
END;
BEGIN
revise_estimate(quarter_end_in);
revise_estimate(dollar_in);
END;
END;

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.

Function or Procedure Overloading Example:


Focus:

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

create table emp33(eno number(4),ename varchar2(12),


job varchar2(12),salary number(6),hiredate date,deptno number(4),
city varchar2(12),exp number(2),dname varchar2(12));

insert into emp33 Values(1,'SURESH','DOCTOR',4500,


'12-MAR-2008',10,'BOMBAY',2,'HEALTH');

insert into emp33 Values(2,'NARESH','CLERK',3500,'21-APR-2005',


20,'HYDERABAD',3,'ACCOUNTS');

SQL> SELECT * FROM EMP33;

ENO ENAME JOB SALARY HIREDATE DEPTNO CITY EXP DNAME


1 SURESH CLERK 2123.08425 15-SEP-06 10 DELHI 2 ACCOUNTS

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

DROP TABLE EMP_RAISE;

create table emp_raise(eno number(3),raise_date date,


salary number(5));

Table : DEPT1

DROP TABLE DEPT1;

create table dept1 (ename varchar2(10),eno number(2),


dname varchar2(10),deptno number(2));

INSERTING VALUES INTO DEPT1:


----------------------------------------------------
insert into dept1 values('SURESH',1,'ACCOUNTS',10);
insert into dept1 values('SAMI',10,'HEART',30);
insert into dept1 values('FARID',2,'ACCOUNTS',20);
insert into dept1 values('AMJAD',3,'SALES',30);
insert into dept1 values('SALIM',4,'SALES',30);
insert into dept1 values('RASHEED',5,'PRODUCTION',40);
insert into dept1 values('PRADEEP',6,'COMPUTERS',50);
insert into dept1 values('ZAHEER',7,'CEO',60);
insert into dept1 values('SAMI',8,'COMPUTERS',20);
insert into dept1 values('PRADEEP',9,'PRODUCTION',30);

SQL> SELECT * FROM DEPT1;

ENAME ENO DNAME DEPTNO


---------- ---------- ---------- ----------
SURESH 1 ACCOUNTS 10
SAMI 10 HEART 30
FARID 2 ACCOUNTS 20
AMJAD 3 SALES 30
SALIM 4 SALES 30
RASHEED 5 PRODUCTION 40
PRADEEP 6 COMPUTERS 50
ZAHEER 7 CEO 60
SAMI 8 COMPUTERS 20
PRADEEP 8 PRODUCTION 30

* ENO and raise_date together form a composite primary key.

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
*/

Syntax: Package Specification:


-----------------------------------------------
CREATE OR REPLACE PACKAGE employee_incentives IS
PROCEDURE give_emp_raise(dept_no IN number);
PROCEDURE give_emp_raise(dept_name IN varchar2);
END;
/
Syntax: Package Body:
------------------------------------
CREATE OR REPLACE PACKAGE BODY employee_incentives IS
PROCEDURE give_emp_raise(dept_no IN number) IS
CURSOR c_emp(c_dept_no number) IS
SELECT eno,salary from emp33 where deptno=c_dept_no;
str_emp_code emp33.eno%type;
num_salary emp33.salary%type;

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;

PROCEDURE give_emp_raise(dept_name IN varchar2) IS


CURSOR c_emp(c_dept_name varchar2) IS
SELECT e.eno,salary from emp33 e,dept1 where e.deptno=dept1.deptno AND e.dname=c_dept_name;

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
/

PL/SQL Block Code For Overload Procedure:


--------------------------------------------------------------------
DECLARE

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');

ELSIF dept_type='NAME' THEN


DBMS_output.put_line('Record is updated with name as its parameter');
employee_incentives.give_emp_raise(dept_name);

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.

Database Triggers vs Procedures:


->Triggers do not accept parameters whereas procedures accepts parameters.
->A trigger is executed implicitly by the Oracle engine itself upon modification of an associated table or its
data.
->To execute a procedure, it has to be explicitly called by the user.

Database Triggers Vs Declarative Integrity Constraints:


Triggers as well as declarative integrity constraints can be used to constrain data input.
The differences are:
->A declarative integrity constraint is a statement about a database that is always true. A constraint
applies to existing data in the table and any statement that manipulates the table.
->Triggers constrain what a transaction can do. A trigger does not apply to data loaded before the grigger
was creaetd, so it does not guarantee all data in table conforms to the rules established by an associated
trigger.
->A trigger enforces a transitional constraint, which cannot be enforced by a declarative integrity
constraint.

How to Apply Database Triggers:


A trigger has basically three parts:
1. A trigger event or statement
2. A trigger restriction
3.A trigger action

1. Trigger Event or Statement


---------------------------------------------
It is a SQL statement that causes a trigger to be fired. It can be INSERT, UPDATE or DELETE statement for a
specific table.

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 vs After Triggers:


-----------------------------------
When defining a trigger it is necessary to specify the trigger timing, i.e. specifying when the triggering
action is to be executed in relation to the triggering statement. BEFORE and AFTER apply to both row and
the statement triggers.

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:

1. BEFORE statement trigger:


------------------------------------------
Before executing the triggering statement, the trigger action is executed.

2. BEFORE row trigger:


--------------------------------
Before modifying each row affected by the triggering statement and beore appropriate integrity
constraints, the trigger is executed if the trigger restriction either evaluated to TRUE or was not included.

3. AFTER statement trigger:


---------------------------------------
After executing the triggering statement and applying any deffered integrity constraints, the trigger action
is executed.

4. AFTER row trigger:


-------------------------------
After modifying each row affected by the triggering statement and possibly applying appropriate integrity
constraints, the trigger action is executed for the current row if the trigger restriction either evaluates to
TRUE or was not included. Unlike BEFORE row triggers, AFTER row triggers have rows locked.

Syntax for Creating a Trigger:


-------------------------------------------
CREATE OR REPLACE TRIGGER [schema] triggername
{BEFORE,AFTER}
{DELETE,INSERT, UPDATE [OF column,...]}
ON [schema.] tablename
[REFERENCING {OLD AS old, NEW AS new} ]
[FOR EACH ROW [WHEN condition]]
DECLARE
variable declarations;
constant declarations;
BEGIN
PL/SQL subprogram body;
EXCEPTION
exception PL/SQL body;
END;

Keywords and Parameters:


---------------------------------------

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.

triggername : It is the name of the trigger to be created

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

Restriction on Trigger Code:


-----------------------------------------
[] You cannot write any transaction control statement, like 'Commit','Rollback', and 'Savepoint'. Inside the
trigger code, no DDL statement can be executed directly or indirectly (via procedures). This is done to
support the statement level atomicity. Suppose the 'Commit' statement is allowed inside the trigger body.
In that case it may record partial effect of the statement. For example, a statement intends to update 10
rows and after updating each row, a 'Commit' statement is issued. Now, if after two rows, there occurs a
problem in the third row, then the user gets a partial effect of the statement.

[] 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.

Example program on ‘TRIGGER’

--Create a TRIGGER which does not allow any DML operations over the --EMP table, if the user is SYSTEM.

create or replace trigger enquirytrg1


before insert or update on emp
declare
uname varchar(30);
begin
select user into uname
from dual;
If uname='SYSTEM' --caps
then
Raise_application_error(-20110,'Invalid insertion or updation');
end if;
end;

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

Raise_application_error(-20111,'Insertion is not allowed on


other days');

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’

SQL> desc client_master;


Name Null? Type
----------------------------------------- -------- -------------------

CLIENT_NO NOT NULL VARCHAR2(6)


NAME VARCHAR2(10)
ADDRESS VARCHAR2(10)
CITY VARCHAR2(10)
STATE VARCHAR2(10)
PINCODE NUMBER(6)
BAL_DUE NUMBER

drop table client_master;

CREATE TABLE CLIENT_MASTER(Client_NO number(4) primary key,


NAME VARCHAR2(10),ADDRESS VARCHAR2(10),
CITY vARCHAR2(10),state varchar2(12),pincode number(6),
bal_due number(5));

drop table audit_client;

create table audit_client(client_no varchar2(7),name varchar2(12),


bal_due number(5),operation varchar2(10),userid varchar2(10),
odate date);

//Insert these rows before executing trigger


Insert into client_MASTER values(1,'ZAHEER','HN1','BANGALORE',
'KARNATAK',56000,2300);
insert into client_MASTER values(2,'PRAKASH','DG1',
'BANGALORE','KARNATAK',56000,2300);

SQL> desc auditclient


Name Null? Type
----------------------------------------- -------- -------------------

CLIENT_NO VARCHAR2(6)
NAME VARCHAR2(10)
BAL_DUE NUMBER(5)
OPERATION VARCHAR2(7)
USERID VARCHAR2(10)
ODATE DATE

CREATE OR REPLACE TRIGGER t4 after INSERT ON client_master FOR EACH ROW


declare
oper varchar2(10);
client_no varchar2(10);
name varchar2(10);
bal_due number(5);
begin
IF inserting then
oper:='insert';
end if;
client_no:=:new.client_no;
name:=:new.name;

PNo: 177
TECH IQ Technologies
bal_due:=:new.bal_due;
insert into audit_client values(client_no,name,bal_due,oper,user,sysdate);
end;
/

SQL> desc client_master;


Name Null? Type
----------------------------------------- -------- -------------------

CLIENT_NO NOT NULL VARCHAR2(6)


NAME VARCHAR2(10)
ADDRESS VARCHAR2(10)
CITY VARCHAR2(10)
STATE VARCHAR2(10)
PINCODE NUMBER(6)
BAL_DUE NUMBER

SQL> desc auditclient


Name Null? Type
----------------------------------------- -------- -------------------

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;
/

GENERATION OF A PRIMARY KEY USING A DATABASE TRIGGER:


---------------------------------------------------------------------------

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.

Automatic Primary Key Generation:


-------------------------------------------
If the data entry operator is not allowed to enter the primary key value and the primary key value is
generated by the system, it would be possible to conserve on time and resources.

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.

2. Use MAX function.

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.

1. Generating Primary Key using Sequences:


------------------------------------------------------
The Oracle engine provides an object called a sequence that generates numeric values starting with a
given value and with an increment as specified by the user. Thus a sequence must first be created using
SQL*Plus. Once the sequence is created a database trigger can be written such that it retrieves the next
number from the sequence and uses the same as the primary key value.

Syntax for Sequence Creation:


-------------------------------------

drop table client_master;

PNo: 179
TECH IQ Technologies

CREATE TABLE CLIENT_MASTER(Client_NO VARCHAR2(15) primary key,


NAME VARCHAR2(10),ADDRESS VARCHAR2(10),
CITY vARCHAR2(10),state varchar2(12),pincode number(6),
bal_due number(5));

Syntax for Sequence Creation:


-------------------------------------
DROP SEQUENCE CLIENT_SEQ;
CREATE SEQUENCE client_seq
INCREMENT BY 1 START WITH 1;

Syntax for Database Trigger creation:


----------------------------------------------
CREATE OR REPLACE TRIGGER client_no_generation
BEFORE INSERT ON client_master
FOR EACH ROW

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;
/

//Try to insert these rows


insert into client_master (name,address,city,state,pincode,bal_due)
values('RAMESH','HH1','BANGLORE','KARNATAK',56003,3000);

insert into client_master (name,address,city,state,pincode,bal_due) values('ASLAM','A-


BLOCK','CHENNAI','TAMIL NADU',54001,4500);

insert into client_master (name,address,city,state,pincode,bal_due) values('PRAKASH','B-


BLOCK','COIMBATORE',
'TAMIL NADU',54001,4500);

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.

SQL> desc client_master1;


Name Null? Type
----------------------------------------- -------- ------------
CLIENT_NO VARCHAR2(6)
NAME VARCHAR2(10)
ADDRESS VARCHAR2(10)
CITY VARCHAR2(10)
STATE VARCHAR2(12)
PINCODE NUMBER(6)
BAL_DUE NUMBER(7)

insert into client_master1(name,address1,address2,city,state,


pincode,bal_dUe) values('BAYROSS','A/5APRT','MG ROAD',
'HYDERABAD','AP',500001,4000);

1. Generating Primary Key using Sequences:


------------------------------------------------------
The Oracle engine provides an object called a sequence that generates numeric values starting with a
given value and with an increment as specified by the user. Thus a sequence must first be created using
SQL*Plus. Once the sequence is created a database trigger can be written such that it retrieves the next
number from the sequence and uses the same as the primary key value.

Syntax for Sequence Creation:


-------------------------------------
CREATE SEQUENCE client_seq
INCREMENT BY 1 START WITH 1;

Syntax for Database Trigger creation:


----------------------------------------------
CREATE OR REPLACE TRIGGER client_no_generation
BEFORE INSERT ON client_master
FOR EACH ROW

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.

SQL> desc client_master1;


Name Null? Type
----------------------------------------- -------- ------------
CLIENT_NO VARCHAR2(6)
NAME VARCHAR2(10)
ADDRESS1 VARCHAR2(10)
ADDRESS2 VARCHAR2(10)
CITY VARCHAR2(10)
STATE VARCHAR2(12)
PINCODE NUMBER(6)
BAL_DUE NUMBER(7)

SQL> insert into client_master1(name,address1,address2,city,state,


pincode,bal_dUe) values('BAYROSS','A/5APRT','MG ROAD',
'HYDERABAD','AP',500001,4000);

insert into client_master1(name,address1,address2,city,state,


pincode,bal_dUe) values('SMITH','2/5APRT','SG ROAD',
'BANGLORE','KA',505401,8000);

2. Generating Primary Key using MAX Function:


----------------------------------------------------------
The Oracle engine provides a built-in function that returns the maximum value in a data set. Thus the
maximum value retrived from the table is incremented by 1 to generate a new primary key value.

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;
/

//Try to insert these rows


insert into client_master (name,address,city,state,pincode,bal_due) values('RAKESH',
'C-BLOCK','HYDERABAD','TS',54001,4500);

insert into client_master (name,address,city,state,pincode,bal_due) values('SACHIN',


'D-BLOCK','VIJAYWADA','AP',500001,4751);

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 whole collection


-------------------------------------
CREATE TYPE tab_course AS
OBJECT (coursecode number(2), coursename varchar2(30));
/

Declaring a table
---------------------
CREATE TYPE tab_courselist AS
TABLE OF tab_course
/

Declaring a Nested table


------------------------------
CREATE TABLE tab_STUDENT (sname varchar2(12),
courses tab_courselist)
NESTED TABLE courses STORE AS c_tab
/

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:

INSERT INTO tab_student VALUES( 'Anil',


tab_courselist( tab_course (10,'Oracle'),
tab_course (20, 'Pascal')));
INSERT INTO tab_student VALUES( 'Sunil’,
tab_courselist (tab_course (10,'Oracle'),
tab_course (25,'C'), tab_course (30,'FORTRAN')));

UPDATE Statement
--------------------------
We can update collections using the update clause. We can use the constructor method to set new values.

Assigning new course values to ANIL

Update tab_student
Set courses = tab_courselist(tab_course (10, 'Oracle'),
tab_course (25,'C')) where sname = 'Anil'
/

Using variables to assign values


--------------------------------------
declare
X tab_courselist;

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

Manipulating the nested table of 'Anil'.

Update THE ( select courses from tab_student where sname = 'Sunil')


SET coursename = 'oracle 8.0' WHERE coursecode= 10
/

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.

Deleting a row from nested table of 'Anil'

DELETE THE (Select courses from tab_student where sname = 'Anil')


Where coursecode = 20
/

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

You might also like