Sei sulla pagina 1di 154

By Chanchal Wankhade

I would like to dedicate this book to my grandmother late shrimati Gayabai


Maruti Wankhade for her blessings and admiring me to learn new things.

Acknowledgements
First of all I would like to thanks Mr. Balaji Iyengar, Mr. Prashant Pandit and Mr. Sheldon Dsouza for their
unbelievable help and support. Ive never met a group of people who are so generous with their time and knowledge.
Its a privilege to be associated with them.
In particular, I would like to thank Mr. Girish Wankhede, who inspired me to explore Oracle more deeply. I would also
like to thank the companies Ive worked with that uses Oracle.
Most important, I would like to thanks to my family for their tolerance. I kept myself busy exploring oracle and the
support and appreciation (which is really important for all of us) my mom Mrs. Vanamala Wankhade and dad Mr.
Manohar Wankhade gives me while exploring my knowledge. I really thanks to them.
Last but not the least; I would like to thanks to Mr. Ashish Dabral, who is there to support me in my personal and
professional life. His guidance and support always boost me to do things in a better way.

What is oracle server?


Just for our understanding and who are brand new for oracle server concept, below is the graphical
example of oracle server which will help beginners to understand it easily. Its a part of database
architecture and not full database architecture. We will see the actual database architecture while we will
proceed further. For now, lets understand what oracle server is:-

In the above graph, I have shown you a human being and notebooks. While showing you above graph, my
aim is to show you that, as we all are having pair of hands, pair of legs, brain (memory),pair of eyes, mouth
etc. by which we can perform various activities like walking, reading, writing, eating etc. Oracle also has its
component to perform its activities. But when it comes to remember anything we cant remember all the
things which were happened in the past. For remembering all the important things we can write it in a
notebook, so whenever we required anything we can go and read it from notebook. Likewise, oracle
database works. Oracle has its own component which helps it to perform its activities. Unlike, we can write
in a notebook by using hands, same way oracle can write in a data files by using database writer (DBWR)
background process and likewise. If we talk about memory then we have memory to remember something
which is happened, same like us, oracle has memory to remember or store something but its not
permanent. If you want to store some data permanently then oracle DBWR background process to write it
in the data files and therefore data files are the actual database which contains all the permanent data.
Every oracle database must have at least one data file to store data.
Therefore we can conclude that oracle works same as we perform our activities. We can read from
textbook/notebooks or can write in notebooks, oracle also can do the same. It can read data or write data
from the data files which is the actual database.

Internal process while connecting to oracle database:Again we will see graphical example to understand what internally happens when we try to connect to
oracle database server:-

What you can see in above graph is, if C wants to go to Ds house then what are the things he must know,
first is name of the D, other thing is address of the D. Address can include Gate No., Room No. etc. C can
go by Walking, by Bike, by Bus, by Train or by any other Vehicle. After reaching to Ds home he meet to Ds
gatekeeper and gatekeeper assist C where he wish to go. Similarly, if we want to connect to the oracle
database, we must know the IP address of the database server, Name of the Database, Port No. on which
database is operating, and off course password. When any client try to connect to the database (I am
talking in both the cases, when both client and database resides on different machines or same machine)
by using COMMAND PROMPT , TOAD, SQL DEVELOPER or any other tool (Similar to Bus, Bike Train
etc) it goes first to listener. Now question is, what is listener? Listener is a kind of gatekeeper for oracle who
assists the entire connection requests to connect to the database. For example, when I want to connect to
the database I will go to command prompt and type database name, password, it will go to the listener to
verify that the database name and password is correct, IP address is correct, Port is opened etc. if yes,
then it will allow me to connect to the database otherwise it will throw erro r like if we specify wrong name of
the database then it will show you ORA-12154: TNS:could not resolve the connect identifier specified or if
you specify wrong user id or password it will show user id or password is wrong error. Once I connect to
the database it will allow me to directly connect to the database next time . For example, after connecting to
the database, I want to fetch (retrieve/select) data from employee table, I will counter the command and this
command will not go to listener, it will directly go the shared server (oracle assistant, to handle multiple
users at a time) and fetch the data. So the listener will just show you the way and next time you can go
directly to the database.
So whenever we try to connect to the database we must ensure that there is a entry in the listener.ora file
for that database and must specify the correct user name and password.

Now lets see what the actual oracle architecture is:-

What is oracle instance?


Oracle instance is a collection of memory structure and background processes. Oracle allocates a memory area
called the System Global Area (SGA) and starts one or more Oracle processes.
What is SGA?
The SGA is a shared memory area that contains data and control information for the particular instance. Multiple
users can share data within this memory area and information stored in the SGA can avoid repeated access from
physical disk, a time consuming operation.
SGA consist of:Shared pool
Large pool
database buffer cache
Redo log buffer cache
Java pool
Streams pool

What is shared pool?


The shared pool caches information that can be shared among users. Some examples:
SQL statements are cached so that they can be reused.
Information from the data dictionary such as user account data, table and index descriptions, and privileges
is cached for quick access and reusability.
Stored procedures, which are executable code that is stored in the database, can be cached for faster
access.
What is large pool?
This is an optional area that is used for buffering large I/O requests for various server processes.
What is database buffer cache?
Before any data stored in the database can be queried or modified, it must be read from disk and stored in memory.
The buffer cache is the component of the SGA that acts as the buffer to store any data being queried or modified. All
user processes connected to the database share access to the buffer cache.
What is redo log buffer cache?
This buffer improves performance by caching redo information (used for instance recovery) until it can be written at
once and at a more opportune time to the physical redo log files that are stored on disk.
What is java pool?
The Java pool memory is used for all session-specific Java code and data within the Java Virtual Machine (JVM).
What is streams pool?
The Streams pool is used by the Oracle Streams product.

What are the Background processes?


Oracle creates a set of background processes for an instance that interact with each other and with the operating
system to manage memory structure, asynchronously perform I/O to write data to disk. They asynchronously perform
I/O and monitor other Oracle processes to provide increased parallelism for better performance and reliability. There
are many background processes but we will look into the major ones only:SMON
PMON
DBWn
LGWR
CKPT
What is SMON?
SMON stands for system monitor. The system monitor performs crash recovery when a failed instance starts up
again.
For example, I you are updating a table and all of us sudden power gets down you dont have backup and your
server is shutdown. When you again startup the oracle database that time system monitor (SMON) will make sure
that your database is in the state on which it was when power shutdown occurs.
What is PMON?
PMON stands for Process monitor. PMON monitors the other background processes and performs process recovery
when a server or dispatcher process terminates abnormally.
For example, PMON resets the status of the active transaction table, releases locks that are no longer required,
and removes the process ID from the list of active processes.
What is DBWn?
DBWn stands for database writer. It is use to write contents of database buffer to database files. It also writes
modified buffers to data files. DBWn background process writes data on data file periodically.
For example, if you have updated records and commit that update statement, it means you are ready to permanently
save the changes. Periodically check point process runs on the database which tells DBWn process to write data on
the data file.
What is CKPT?
CKPT stands for checkpoint .The checkpoint background process, updates the control file and data file headers
with checkpoint information and signals DBWn to write blocks to disk.
What is LGWR?
LGWR stands for log writer. The log writer process (LGWR) manages the redo log buffer. LGWR writes one
contiguous portion of the buffer to the online redo log. By separating the tasks of modifying database buffers,
performing scattered writes of dirty buffers to disk, and performing fast sequential writes of redo to disk, the database
improves performance.

What are the different types of files?


Data file

Redo Log Files


Control Files
Parameter File
Archive File
Trace File
Alert log file

What is data file?


Data files are physical files of the operating system that store the data of all logical structures in the database. In
simple words data file holds the actual data of the database.
What is redo log file?
The most crucial structure for recovery operations is the redo log, which consists of two or more pre-allocated files
that store all changes made to the database as they occur. Every instance of an Oracle Database has an associated
redo log to protect the database in case of an instance failure.
What is control file?
Every Oracle Database has a control file, which is a small binary file that records the physical structure of the
database. The control file includes:
The database name
Names and locations of associated data files and redo log files
The timestamp of the database creation
The current log sequence number
Checkpoint information
What is parameter file?
A parameter file is a file that contains a list of initialization parameters and a value for each parameter. You specify
initialization parameters in a parameter file that reflect your particular installation. Oracle supports the following two
types of parameter files:
Server Parameter Files
Initialization Parameter Files
Server Parameter Files
A server parameter file is a binary file that acts as a repository for initialization parameters. The server parameter
file can reside on the machine where the Oracle database server executes. Initialization parameters stored in a
server parameter file are persistent, in that any changes made to the parameters while an instance is running can
persist across instance shutdown and startup.

Initialization Parameter Files:An initialization parameter file is a text file that contains a list of initialization parameters. The file should be written
in the client's default character set.

What is archive file?


When your database is in Archive log mode, archive log file starts or stops automatic archiving of online redo log
files, manually archives specified redo log files, or displays information about redo log files.

What is trace file?


Trace files are stored in the Automatic Diagnostic Repository, in the trace directory under each ADR home. To help
you locate individual trace files within this directory, you can use data dictionary views. For example, you can find the
path to your current session's trace file or to the trace file for each Oracle Database process.

What is alert log file?


The alert log file is a chronological log of messages and errors written out by an Oracle Database. You can find
messages in this file like: database startup, shutdown, log switches, space errors, etc. A good database administrator
constantly monitors this file to detect unexpected errors and corruption.

What is storage structure?


While storing data, it gets store logically in tablespace and physically in datafiles.

Storage structure:LOGICAL STORAGE STRUCTURE

PHYSICAL STORAGE STRUCTURE

TABLESPACE

DATAFILES

TABLES

SEGMENTS

ROWS

EXTENDS

COLUMNS

BLOCKS

Logical storage structure:1) Tablespace:A tablespace is a logical storage unit within an Oracle database. The tablespace is made up of one or more datafiles
which are stored in the server's file system. A datafile belongs to one and only one tablespace but one tablespace
can belongs to one or many datafiles.
2) Tables:Tables are the basic unit of storage. Again it stores data logically in the format rows and columns.
3) Rows:Rows are combination of all the fields is called rows.
4) Column:Column is a list of values in fields.

Physical storage structure:1) Datafiles:Database datafiles are physical files stored on disk. These files are used to store data on disk. Database datafiles are
only written to by the DBWR processes.
2) Segments:A segment is a set of extents that contains all the data for a specific logical storage structure within a tablespace. For
example, for each table, Oracle allocates one or more extents to form that table's data segment, and for each index,
Oracle allocates one or more extents to form its index segment.
3) Extend:An extent is a logical unit of database storage space allocation made up of a number of contiguous data blocks. One
or more extents in turn make up a segment. When the existing space in a segment is completely used, Oracle
allocates a new extent for the segment.
4) Block:Oracle manages the storage space in the datafiles of a database in units called data blocks. A data block is the
smallest unit of data used by a database. In contrast, at the physical, operating system level, all data is stored in
bytes. Each operating system has a block size. Oracle requests data in multiples of Oracle data blocks, not operating
system blocks.

What is pl/sql?
PL/SQL stands for Procedural Language extensions to the Structured Query Language or SQL. SQL is
the powerful tool for both querying and update data in relational databases. Oracle introduced PL/SQL to
extend some limitations of SQL to provide a more comprehensive solution for building mission-critical
applications running on Oracle database.
PL/SQL is a combination of SQL along with the procedural features of programming languages. It was
developed by Oracle Corporation in the early 90s to enhance the capabilities of SQL.
Below is the example of pl/sql:EMPLOYEE TABLE
EMP_NO
X
X
X
X

EMP_NAME
XXXX
XXXX
XXXX
XXXX

PHONE
XXXX
XXXX
XXXX
XXXX

SALARY
XXXX
XXXX
XXXX
XXXX

DEPT_NO
XXXX
XXXX
XXXX
XXXX

ADDRESS
XXXX
XXXX
XXXX
XXXX

Suppose if, you want to perform the below tasks:1)


2)
3)
4)
5)

Increase the salary of employees by 10 percent whose designation is Manager.


Increase the salary of employees by 20 percent whose salary is below 10,000.
Increase the salary of employees by 10 percent who is under department 10.
Increase the salary of employees by 5 percent whose salary is more than 10,000.
Increase the salary of employees by 30 percent whose salary is less than 5,000.

You can perform this update by using sql queries but you would need to fire 5 queries. But if you will use pl/sql then
you can perform this in one query by using various construct like loop, if else statements. Thats the beauty of the
pl/sql.
When you use pl/sql anonymous block or other named program, you write part of the code in pl/sql and part of the
code in sql. Pl/sql part will go to the pl/sql compiler and sql part will go to the sql compiler. Lets have an example:-

How pl/sql works?


Pl/sql program consists of sql and pl/sql statement which firms pl/sql block.
Pl/sql has 4 blocks:Declare
Begin
Exception
End
When you write a code using block its called Anonymous block.
Pl/sql has three sections:1) Declare (optional)
2) Begin (Mandatory)
3) Exception (optional)
From the above three sections, there is only one section which is mandatory i.e. Begin. Begin is just not a
begin block. In pl/sql each begin has its end at the end of block or section, hence when I am saying begin is
mandatory that means I have started a block by using begin (reserve keyword) and that begin will always
have end (reserve keyword) at the end of anonymous block or pl/sql section. Like below example:Begin
Sql statements;
End;
Understanding different sections in detail:Declare Section:These sections of pl/sql block start with reserve keyword DECLARE which can be use for declaring
placeholders like variables, records, cursors and constants.
Begin Section:This section of Pl/sql block start with reserve keyword BEGIN and ends with reserve keyword END. This is
a mandatory section of pl/sql block which is use to writing program logic for performing tasks. In this section
we can use conditional operator and cursors also.
Exception Section:This section in pl/sql block starts with reserve keyword EXCEPTION. This is an optional section in pl/sql
block. However we can handle any errors in this section.

Below is the Sample pl/sql block:Declare

(Declarative Section)
Begin
(Execution Section)
Exception
(Handling any error)
End;
(End of the Block)

Pl/sql blocks are also called ANONYMOUS BLOCKS.


ANONYMOUS BLOCK is pl/sql program unit which consist of declare, begin exception and end sections.

INDEX
SR No. Particulars
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

DBMS / RDBMS concept


Language statements in oracle
Pl/sql data types
Connecting to oracle database
Pl/sql tables
Pl/sql constraints
Pl/sql index
What is Field, Record and Column
Altering, modifying, updating table
Fetching data from table
Joins in pl/sql
Where, Group by, having and order by clause
Oracle supplied functions
Pl/sql Inline view and sub query
Pl/sql variables and constant
Sample anonymous block
Pl/sql loops
Pl/sql cursors
Pl/sql view and types of view
Pl/sql sequence
Pl/sql stored procedure
Pl/sql stored function
Pl/sql package
Pl/sql triggers
Exception handling in pl/sql
Operators in pl/sql
Conditional statements
Job scheduler
Sql * loader
External tables
Merge in pl/sql
Composite datatype
Dbms_output.put_line package
Pseudo columns
Transaction in pl/sql

Page No.
19
19
21
23
28
36
41
43
44
47
49
56
59
62
65
68
69
72
75
81
87
91
94
98
102
107
123
126
129
134
137
141
149
150
151

DBMS and RDBMS CONCEPTS:-

Database management system (DBMS):Database management system is a program which uses standard method of cataloging, retrieving and modifying
data. In DBMS, DML operation affects whole database.

Relational database management system (RDBMS):Relational database management system holds data in a table format. Structure of the RDBMS is table, fields and
records. Tables further consist of rows and rows consist of table fields. You can perform DML operation to a
particular table only which means unlike DBMS, DML operation affects to whole database but in RDBMS DML
operations affects only to a particular table.
RDBMS stores data in tables which might be related to each other by common fields. Relation constitutes of primary
key and foreign key constraint.

Language statements in oracle:There are mainly three types of languages statements in oracle as stated below:-

1) Data definition language statement (DDL)


2) Data manipulation language statement (DML)
3) Transactional control statement (TCS)

What data definition language is?


Data definition language lets you perform below tasks:1)
2)
3)
4)
5)

Create
Alter
Drop
Grant
Revoke

DDL statements will allow you to create, alter or drop schema objects. It will also allow you to grant or role back any
privileges or role from users.

What data manipulation language is?


Data manipulation language lets you perform below tasks:1) Insert
2) Update
3) Delete
DML statements will allow you do insert, update or delete data from existing schema objects.

What transactional control statement is?


Transaction control statement lets you perform below tasks:1) Rollback
2) Commit
Transaction control statement allows you to commit or rollback the transaction.

What are the different types of data types in oracle?

Above, I have classified the oracle data type in two different parts,
1)
2)

Scalar data types and


Composite data types.

Scalar data type includes number, char, varchar, varchar2, date, pls_integer etc. composite data type includes
records and collections. Collection again divided into three parts, index by tables this also called as associative array,
varray and nested tables.

What scalar data type is?


Scalar data type can hold single value at a time with no internal component.

Lets look at the category and description of the various scalar data types:Category Data Description
Numeric

Numeric values, on which you can perform arithmetic operations.

Character Alphanumeric values that represent single characters or strings of characters, which you can manipulate.
BOOLEAN Logical values, on which you can perform logical operations.
Datetime

Dates and times, which you can manipulate.

Interval

Time intervals, which you can manipulate.

Lets look at the data type family and data type name of scalar data type:Data type family

Data type name

NUMERIC

NUMBER
PLS_INTEGER
BINARY_FLOAT
BINARY_DOUBLE

CHARACTER

CHAR
VARCHAR2
NCHAR
NVARCHAR2

BOOLEAN

BOOLEAN

DATETIME

DATE
TIMESTAMP

INTERVAL

INTERVAL YEAR TO MONTH


INTERVAL DAY TO SECONDS

What is difference between CHAR, VARCHAR2 and VARCHAR2 scalar data types?
Char and varchar are similar but differ in the way that they store and retrieve. The char and varchar type are declared
with the length that indicates maximum number of characters you want to store. Like char (10) or varchar2 (10).
CHAR: - CHAR should be used for storing fix length character strings. String values will be space/blank
padded before stored on disk. If this type is used to store variable length strings, it will waste a lot of disk space.
VARCHAR: - VARCHAR behaves exactly the same as VARCHAR2.
VARCHAR2:- VARCHAR2 is used to store variable length character strings. The string value's length will be
stored on disk with the value itself.

What is difference between INTEGER, PLS_INTEGER and BINARY_INTEGER?


-

Pls_integer is a subtype with base type binary integer


Binary integer is a subtype with base type integer with a range of '-2147483647'...2147483647
Integer is a subtype with base type number (38, 0)

Note: - We will discuss composite data types letter in this book.

Connecting to oracle database:We can connect to oracle database by using multiple tools such as command prompt, toad, oracle sql developer,
sql*plus and many other third party tools. We will try to connect to oracle database by using these 4 tools:COMMAND PROMPT: - Type CMD (shortcut for command prompt) in RUN dialog box (windows key + R):-

Click ENTER or click OK. It will open command prompt like shown below:-

Type SQLPLUS and hit ENTER. Now it will ask you for username and password. Provide username and password
with database name or service name. I have also written a query to find to which database I am currently logged in
and by which user:-

TOAD: - TOAD is another tool which can talk to oracle database. We can install it on our machine or can directly
open it by double clicking on TOAD.EXE file.
TOAD will ask you three credentials, first is database name second is username and third is password. In database
name textbox you must specify the database name, in my case its ORCL. Then I will have to type user name, i.e.
SCOTT. And finally you will have to enter the password in password textbox.
Below is the process with the screen shots. Double click on the toad icon. It will land you on below screen:-

Type required info like database name, scheme name (username) and password:-

Select connect as Normal. Since we are programmer we can connect only with normally (without sys privileges):-

Click OK.

Sql*plus:Its another oracle supplied tool which gets install when you install oracle. It is similar to toad.
Lets see how to connect to oracle by using sql*plus:Click on the START > ALL PROGRAMS > ORACLE > APPLICATION DEVELOPMENT > SQL PLUS.

Once you click on sql plus it will open sql * plus window:-

Type username (schema name), password and host string:-

Click OK.

Oracle sql developer:Install oracle sql developer or click on sql developer.exe file. it will show you initialization process:-

Click on

Once you click on


you will land onto the below screen. Type name of the connection as you want, type
username, password, click on save password checkbox, type host name or ip_address of the machine, specify the
port number and database SID or Service name. after putting all the information click on test or you can directly click
on connect button:-

Once you click on save button, the connection will be saved in the connection tab so you can use it again and again.
You can see below the name CONNECTION_TO_SCOTT is present in the connection tab.

If you want to add more connection then just click on


will be listed in connection tab.

and put all the required information. After you saved it, it

Table:Table is a basic data storage unit of oracle. Data gets stored in a table logically. When we insert a row in table that
time each row gets a rowid assign to it. Suppose I have a table called EMP_TEST below and if I want to see the
rowid for a particuler row I can see that by using below mention queries.
CREATE TABLE EMP_TEST
(EMPNO NUMBER,
EMPTYPE VARCHAR2(10),
SALARY NUMBER,
JDATE DATE,
DEPTNO NUMBER
);
INSERT INTO EMP_TEST VALUES (1,'HR',99999,TO_DATE('04-NOV-2013','DD-MON-YYYY'),10);
INSERT INTO EMP_TEST VALUES (2,'ADMIN',1234,TO_DATE('02-MAY-2013','DD-MON-YYYY'),20);
INSERT INTO EMP_TEST VALUES (3,'IT',4321,TO_DATE('02-MAY-2013','DD-MON-YYYY'),30);
INSERT INTO EMP_TEST VALUES (4,'OPERATION',2314,TO_DATE('02-MAY-2013','DD-MON-YYYY'),40);
INSERT INTO EMP_TEST VALUES (10,'FINANCE',9876,TO_DATE(''02-MAY-2013','DD-MON-YYYY'),50);
INSERT INTO EMP_TEST VALUES (10,' FINANCE ',99999,TO_DATE(''02-MAY-2013','DD-MON-YYYY'),50);
COMMIT;

Rowid gets assign in the following format:Lets talk about the rowid of EMPLOYEE whose EMPLOYEE NUMBER is 1.
AAAu61
Data object number

AAJ
Relative file number

AAB8Ce
Block number

AAA
Row number

What are these four blocks for rowid AAAu61AAJAAB8CeAAA:AAAu61


The data object number identifies the segment AAAu61. A data object number is assigned to every
database segment.
AAJ
The tablespace - relative data file number identifies the data file that contains the row AAJ.
AAB8Ce
The data block number identifies the block that contains the row AAB8Ce.Block numbers are relative to their
data file, not their tablespace. Thus, two rows with identical block numbers could reside in different data files
of the same tablespace. I.e. empno=10.
AAA
The row number identifies the row in the block.

There are different types of tables which are listed below:NO.


1

TABLE NAME
Heaped Organized Tables

Index Organized Tables

3
4

Clustered Tables
Partitioned tables

Global temporary tables

6
7

Dual table
External tables

Lets discuss different types of table in detail:-

Ordinary or Heap organized tables:Its a default type of table. When we create table ordinary/ heap organized table gets created.
Syntax for creating heap organized table is:CREATE TABLE EMPLOYEE (EMPNO NUMBER, EMPNAME VARCHAR2 (10));
You can create and drop the table like shown below:-

Index organized tables (IOT):The data of this table is stored in an index like structure. Unlike head organized table whose data is stored
as an unordered collection, data for index organized table is stored in B-Tree index structure in a primary
key sorted manner.
This table is use to have direct access to the row. In short this can be use to increase the performance of
the fetching query.
Syntax to create index organized table is:CREATE TABLE EMPLOYEE (EMPNO NUMBER, EMPNAME VARCHAR2 (10),
CONSTRAINT PK_EMPNO PRIMARY KEY (EMPNO));

OR
CREATE INDEX IND_EMPNO ON EMPLOYEE (EMPNO);

When you create primary key constraint or unique key constraint on a table, that time index with the same constraint
name gets created. When you drop the constraint, index also gets drop. Lets have an example below:-

When you create index on a table specifically and you need to drop that index, you need to drop it
specifically like shown below:-

Clustered tables:In simple words, A cluster is a schema object that contains data from one or more tables, all of which have
one or more columns in common. Syntax to create cluster table is:CREATE CLUSTER EMPLOYEE (DEPTNO NUMBER (3);
CREATE TABLE DEPARTMENT (DEPTNO NUMBER (3) PRIMARY KEY) CLUSTER EMP_DEPT
(DEPTNO);
CREATE TABLE EMPLOYEE (EMPNO NUMBER (5) PRIMARY KEY, ENAME VARCHAR2 (15), DEPTNO
NUMBER (3) REFERENCES DEPT) CLUSTER EMP_DEPT (DEPTNO);

When you need to drop the cluster, that time you would need to drop it including its tables or you will have to first
drop all the tables which are in the cluster and then drop the cluster like shown below:-

OR, drop all the tables first then drop cluster:-

Partitioned tables:Partitioning allows a table, index, or index-organized table to be subdivided into smaller pieces, where each
piece of such a database object is called a partition. Each partition has its own name.We can divide a large
amount of data into sub tables called partitions, according various criteria. We can partition tables
when there are millions of records in a table. Partition tables are mostly used in data warehousing.
Most commonly use partition types are:Range
Hash
List
Composite
We will be having example of Range partition only. Syntax to create partition table is:CREATE TABLE TABLE_NAME (COLUMN_LIST)
PARTITION BY RANGE
(
PARTITION PARTITION_NAME VALUES LESS THAN (VALUE),
PARTITION PARTITION_NAME VALUES LESS THAN (VALUE),
PARTITION PARTITION_NAME VALUES LESS THAN (VALUE),
PARTITION PARTITION_NAME VALUES LESS THAN (MAXVALUE),
);
Lets look at the actual example:-

Above I have created an EMPLOYEE table with EMPNO, EMPNAME, SALARY AND J_DATE (joining date)
columns. I have partitioned that table on J_DATE column. While inserting or fetching values in the table it
will insert or fetch the data from respective partition. For example, if I want to insert a record which is having
J_DATE as 15 Feb 2013 then this record will be saved in PART_EMP_2013 sub table.
You can drop this table by simple drop command.

Global temporary table:The data in a global temporary table is private, such that data inserted by a session can only be accessed
by that session. The session-specific rows in a global temporary table can be preserved for the whole
session, or just for the current transaction. The ON COMMIT DELETE ROWS clause indicates that the data
should be deleted at the end of the transaction.
Syntax to create global temporary table is:We can create transaction level temporary table and session level temporary table.
Lets see what transaction level temporary table is:CREATE GLOBAL TEMPORARY TABLE TABLE_NAME
(
COLUMN_LIST WITH_DATA_TYPE
)
ON COMMIT DELETE ROWS;

Lets see what session level temporary table is:CREATE GLOBAL TEMPORARY TABLE TABLE_NAME
(
COLUMN_LIST WITH_DATA_TYPE
)
ON COMMIT PRESERVE ROWS;

Dual table:The DUAL table is a special one-column table present by default in all Oracle database installations. It is
suitable for use in selecting a pseudo column such as SYSDATE or USER. The table has a single
VARCHAR2 (1) column called DUMMY that has a value of 'X'.

External tables:External tables are used to fetch data from files like text file or excel file.

Constraints:There are 5 types of constraint in oracle which helps us to define certain quality of requirement that the data in the
database needs to meet. In other words it can be called as rules which need to be meeting while manipulating
database data.
Scenario:-

In above EMPLOYEE table there are 6 columns named as EMP_NO, EMP_NAME, PHONE, SALARY, DEPT_NO
and ADDRESS. My requirement is EMP_NO column should not be NULL and it should be UNIQUE. EMP_NAME
column must have a name and hence it should not be null. I have table called PHONE_MASTER and
PHONE_MASTER also contains PHONE column and I want to insert value in PHONE column of a
PHONE_MASTER table if same phone number is present in the EMPLOYEE table in the PHONE column. DEPT_NO
column should not contain duplicate values. I need to check that while inserting data in the EMPLOYEE table,
ADDRESS of the employee should not be null.
Considering above requirement I will have to create various constraint on the table and these are discuss in detail
below:There are 5 types of constraints and are listed below:-

1)
2)
3)
4)
5)

Primary key
Foreign key
Unique key
Not null
Check

Lets look at the example of each constraint type.

Primary key:The primary key of a table uniquely identifies each row and ensures that no duplicate rows exist. Therefore, a primary
key value cannot be NULL.A table can have at most one primary key, but that key can have multiple columns (that is,
it can be a composite key). To designate a primary key, use the PRIMARY KEY constraint.
You can create primary key constraint while creating a table or you can alter table to add primary key:Primary key constraint while creating table:CRAETE TABLE TABLE_NAME (COLUMN_NAME DATA_TYPE PRIMARY KEY, COLUMN_NAME DATA_TYPE);

Primary key constraint after creating table (composite primary key):ALTER TABLE TABLE_NAME ADD CONSTRAINT CONSTRAINT_NAME PRIMARY KEY (COLUMN NAME /
COLUMN_LIST);

If you required to drop constraint then you can drop it like:-

Foreign key:When two tables share one or more common columns, you can use a FOREIGN KEY constraint to enforce referential
integrity that is, to ensure that the shared columns always have the same values in both tables. It is also called as
referential integrity constraint.

Syntax to create foreign key is:You can create foreign key while creating a table or you can add it by altering the table.
CREATE TABLE TABLE_NAME (COLUMN_NAME DATA_TYPE, CONSTRAINT CONSTRAINT_NAME
FOREIGN KEY (COLUMN_NAME) REFERENCES REFERENCE_TABLE_NAME (COLUMN(S)) ;
Foreign key while creating table:CREATE TABLE EMPLOYEE (EMPNO NUMBER, DEPT_NO NUMBER PRIMARY KEY);
CREATE TABLE DEPT (DEPT_NO NUMBER, DEPT_NAME VARCHAR2 (10), CONSTRAINT FOR_DEPT_NO
FOREIGN KEY (DEPT_NO) REFERENCES EMPLOYEE (DEPT_NO));

Note: - if you would try to create foreign key without having related primary key, will throw error.
Foreign key constraint after creating a table (composite foreign key):ALTER TABLE DEPT ADD CONSTRAINT FOR_DEPTNO_CON FOREIGN KEY(DEPT_NO)
REFERENCES EMPLOYEE (DEPT_NO);

You can drop foreign key constraint like:-

Unique key:Unique key constraint ensures that the column does not have duplicate values in the column. We can create unique
constraint on one or multiple columns. The difference between unique key and primary key is that unique key
constraint allows NULL values and primary key does not. In regards to create composite unique key constraints you
must create it out of line (by altering a table).

Syntax to create unique constraint is:You can create unique constraint while creating a table or you can add it by altering table (out of line).
CREATE TABLE TABLE_NAME (COLUMN_NAME DATA_TYPE, COLUMN_NAME DATA_TYPE UNIQUE,);
Unique key while creating a table:CREATE TABLE EMPLOYEE (EMPNO NUMBER UNIQUE, EMPNAME VARCHAR2 (10));

Unique key after creating a table (composite unique key):ALTER TABLE EMPLOYEE ADD CONSTRAINT CON_UNIQUE (EMPNO, EMPNAME);

You can drop unique key constrain like:-

Not null:Not null constraint will create a rule on a table column which will not allow NULL values to be inserted.
Syntax to create not null constraint is:You can create not null constraint while creating table or by altering table:CREATE TABLE TABLE_NAME (COLUMN_LIST DATA_TYPE NOT NULL);
Not null constraint while creating a table:CREATE TABLE EMPLOYEE (EMPNO NUMBER NOT NULL, EMPNAME VARCHAR2 (10));

Not null constraint after creating a table:ALTER TABLE EMPLOYEE MODIFY EMPNO NOT NULL;

Note: - You can combine unique key and not null key to firm a primary key like constraint.
Check:Check constraint enforce a rule on a table column to check for the required value. If you required to check a value
before inserting into the column you should create check constraint.
Syntax to create check constraint is:You can create check constraint while creating a table or by alter the table:CREATE TABLE TABLE_NAME (COLUMN_LIST, CONSTRAINT CONSTRAINT_NAME CHECK (SALARY >10000));

Check constraint while creating a table:CREATE TABLE EMPLOYEE (EMPNO NUMBER, EMPNAME VARCHAR2 (10), SALARY NUMBER, CONSTRAINT
CON_CHECK CHECK SALARY>10000());

Check constraint after creating table:ALTER TABLE EMPLOYEE ADD CONSTRAINT CONSTRAINT_CHECK CHECK (SALARY <15000);

You can drop check constraint like:

Index:Index is an optional structure associate with table to have direct access to the row which can be use to improve the
performance.

Scenario:Consider above scenario, you have a book of suppose history and the book consist of 1000 pages. On the 999 page
there is information about AURANGAZEB and that you want to read but you dont know where this information
resides in this book. To read information about AURANGAZEB you will scan the book page by page (full book scan).
Since the information resides on 999 pages it will take much more time to find the page. But when you have an index
on in the book you will go to the index page and find the appropriate topic with page number and direct jump onto
that page. If the book does not have index then also it is the book but if the book does have an index it will work fast.
Similarly, there is an index in oracle say, you have a table called EMPLOYEE (see above table) and you dont have
index on the table. You want to fetch information about the employee whose employee number is 7. In this case
oracle will search the result row by row (full table scan) and once it finds the employee number 7 it will show the
information (consider if your table have millions of records). But if you have index on that table then it will directly go
to the index and fetch the information quickly. Table without index is still a table but it will make difference if you have
an index on it.

Syntax to create an index is:CREATE INDEX INDEX_NAME ON TABLE_NAME (COLUMN_NAME(S));


CREATE INDEX IN_EMPNO ON EMP (EMPNO);

You can create index on multiple columns:CREATE INDEX INDEX_NAME ON TABLE_NAME (COLUMN_LIST);
CREATE INDEX MUL_INDX ON EMPLOYEE (EMPNO, SALARY);

What are field, record and column in oracle?


To understand this we would required to create and insert values in a table. So lets create an employee table.
You know the syntax:CREATE TABLE EMPLOYEE (EMPNO NUMBER, EMPNAME VARCHAR2 (10), SALARY NUMBER (6, 2));
INSERT INTO EMPLOYEE VALUES (1, CHANCHAL, 5000);
SELECT * FROM EMPLOYEE;

What is field?
In above case fields are the name of the all the columns so list of empno, empname and salary is collectively called
field.

What is record?
Record is a collection of all the values in one row. In above case records consist of 1, CHANCHAL and 5000.

What is column?
Column is a list of values in one field. In above case column can be empno, empname, or salary.

How to alter, update or modify table?


Lets create a table to understand alter table concept, update table concept and modify table concept.
CREATE TABLE EMPLOYEE (EMPNO NUMBER, EMPNAME VARCHAR2 (10), SALARY NUMBER (5, 2));
INSERT INTO EMPLOYEE (EMPNO, EMPNAME) VALUES (1,CHANCHAL);
INSERT INTO EMPLOYEE (EMPNO, EMPNAME) VALUES (2,WANKHADE);
SELECT * FROM EMPLOYEE;

What is altering table and why it is used?


Alter table allows you to add one or more columns or add any constraint if you have missed out while creating a
table. For example, if I have missed the column ADDRESS in the EMPLOYEE table and I want to add it in a table .
Look at the syntax while adding two columns:-

If I want to add constraint in EMPLOYEE table then I can add this by following syntax:-

What is updating a table?


Update statement will allow you to update any existing value. In EMPLOYEE table there are SALARY, PHONE_NO,
DEPT_NO and ADDRESS columns empty. Lets try to update them to fill some value.

Make sure you have committed the data to save it permanently otherwise it will not be saved in your table.
What is modifying a table?
Modify can be use when you want to modify data type of the existing tables column. Suppose if you required
modifying DEPT_NO column to VARCHAR2 data type of EMPLOYEE table.

Remember while modifying data type of the column; you need to make sure that the column is empty in case you are
trying to switch from number to char or varchar2. In case you have to increase the length of the varchar2 data type
then you can do it easily but you cant modify data type from bigger length to smaller length. See the example above.
I have created table called DEPARTMENT which is having DEPT_NO and DEPT_TYPE columns. Initially I have
given DEPT_NO column number data type. After creating table I have modified that to varchar2 data type with the
length 10 and inserted some values into the DEPARTMENT table. After that I have changed the length of the
DEPT_NO column to varchar2 with length 15 and inserted 15 length values. Now I want to again modify the
DEPT_NO column and make the length 14. I tried to perform that but it does not allow me to decrease the length of
the column data type while there is a value already present which is having more than length I want to modify.
In short you cannot directly switch to another data type without empting column first and you cannot modify less
length of data type while there is a value having more length than you want to modify.

Fetching data from a table:To understand this we will create EMPLOYEE table and will try to retrieve some data from employee table.
CREATE TABLE EMPLOYEE (EMPNO NUMBER, EMPNAME VARCHAR2 (10), SALARY NUMBER);
INSERT INTO EMPLOYEE VALUES (1,CHANCHAL, 5000);
INSERT INTO EMPLOYEE VALUES (2, JACK, 6000);
INSERT INTO EMPLOYEE VALUES (3,JOHN, 7000);
INSERT INTO EMPLOYEE VALUES (4,MIKE, 8000);
INSERT INTO EMPLOYEE VALUES (5,SCOTT, 9000);

Above we have inserted some values in EMPLOYEE table. Now suppose I want to retrieve all the records from
EMPLOYEE table then will fire query like:SELECT * FROM EMPLOYEE;

If I want to fetch only the rows which are having salary more than 7000 then I can retrieve it by specifying where
condition:-

If I want to retrieve row only for 1 EMPNO then I will use = sign.

Joins:-

Scenario:Suppose, there is a shop owner and he maintain his data in a table format. He has an order table and quantity table.
His order table contains fields like order number, order date and quantity table contains order number, quantity. Now
suppose that shop keeper want to see, against which order number how much quantity have been purchased. Shop
keeper doesnt have all the information in one table. If he wants to find the information he must fetch data from two
tables e.i. Order table and quantity table. In order to fetch this data, shop keeper can join that tables and get the
desired result. Join can be said as helper to the shop keeper which will help shop keeper to fetch data from two
tables as per his requirement.
What join is?
Join is a query which allows to fetch data from two or more tables, views and materialized views. It combines data
from two tables. Join can be used in a FROM clause or WHERE clause of the query. There are different types of
joins available in oracle. And they are listed below:1) Equijoin
2) Self join
3) Outer join
A. Left outer join
B. Right outer join
C. Full outer join
4) Cross join
Lets discuss all the joins in detail:-

Equijoin
In simple words, equijoin is a join statement that uses (=) sign in the where condition. It will fetch data which is
matched with the condition specified in where clause, like (a.deptno=b.deptno).

Syntax of equijoin is:SELECT A.COLUMN_NAME, B.COLUMN_NAME FROM TABLE_NAME A, TABLE_NAME B


WHERE A.COLUMN_NAME=B.COLUMN_NAME;
Lets have an example of an equijoin:SELECT A.EMPNO, A.EMPNAME, B.DEPTNO, B.DEPTTYPE FROM EMPLOYEE A, DEPARTMENT B
WHERE A.DEPTNO=B.DEPTNO;

In above screen shot, I have selected two columns from employee table and two columns from department table on
the condition that where both the tables have same department table.

Self join:As you can understand by its name, self join is a join which joins a table to itself.
Syntax of self join is:SELECT A.COLUMN_NAME B.COLUMN_NAME FROM A.TABLE_1 A, TABLE_1 B WHERE
A.COLUMN_NAME=B._COLUMN_NAME;
Example is:-

Outer join:Outer join is a kind of equijoin but we can fetch non-match data from the tables. There are three outer join. Right
outer join, left outer join and full outer join.
A) Right outer join:-

Right outer join retrieves all the records from right side of the table in a select query and only matching records from
the left site of the table in a select query.
Syntax of the right outer join is:SELECT A.COLUMN_LIST, B.COLUMN_LIST FROM TABLE A, TABLE B WHERE
A.COLUMN_NAME (+) =B.COLUNN_NAME;
(+) Sign can be use instate of specifying RIGHT OUTER JOIN keyword left side of the (=) sign.

Lets have an example of right outer join:SELECT A.EMPNO, A.EMPNAME, B.DEPTNO


FROM EMPLOYEE A, DEPARTMENT B
WHERE A.DEPTNO (+) =B.DEPTNO;

We can specify (+) sign instate of specifying RIGHT OUTER JOIN keyword in the left side of the (=) sign.
Above query can be written as:SELECT A.EMPNO, A.EMPNAME, B.DEPTNO
FROM EMPLOYEE A RIGHT OUTER JOIN DEPARTMENT B
ON A.DEPTNO=B.DEPTNO;

B) Left outer join

Left outer join retrieves all the records from left side of the table in a select query and only matching records from the
right hand side of the table.
Syntax of the left outer join is:SELECT A.COLUMN_LIST, B.COLUMN_LIST FROM TABLE A, TABLE B
WHERE A.COLUMN_NAME=B.COLUMN_NAME (+);
Specify the (+) sign in the right side of the condition.
Lets have an example:-

The above example can be written as


SELECT A.EMPNO, A.EMPNAME, B.DEPTNO
FROM EMPLOYEE A LEFT OUTER JOIN DEPARTMENT B ON A.DEPTNO=B.DEPTNO;

C) Full outer join:-

Full outer join retrieves all the records from both tables. Whenever there are no values, it will show NULL.
Syntax of full outer join is:SELECT A.COLUMN_LIST, B.COLUMN_LIST FROM TABLE A FULL OUTER JOIN TABLE B ON
A.COLUMN_NAME =B.COLUMN_NAME;
Lets have an example:SELECT * FROM EMPLOYEE;
SELECT * FROM DEPARTMENT;
SELECT A.EMPNO, A.EMPNAME, A.MGRID, B.DEPTTYPE
FROM EMPLOYEE A FULL OUTER JOIN DEPARTMENT B
ON A.DEPTNO=B.DEPTNO;

Cross join
Cross join is the join which fetch data multiplied times. Suppose you have 10 records in one table and 10 records in
other table in select query then output would be 100 records.
Syntax of the cross join is:SELECT A.COLUMN_NAME_LIST, B.COLUMN_NAME_LIST FROM TABLE A, TABLE B;
Lets have an example:SELECT A.EMPNO, A.EMPNAME, B.DEPTTYPE FROM EMPLOYEE A, DEPARTMENT B;

Above statement can be use as:SELECT A.EMPNO, A.EMPNAME, B.DEPTTYPE FROM EMPLOYEE CROSS JOIN DEPARTMENT;

Conditions in select queries:When we required fetching data according to our requirement, that time we can use many oracle supplied conditions
to get desired output. We can use where clause, group by clause, having clause and order by clause and many more
clauses.
What where clause is?
We can fetch only desired records by putting where condition in select statement. After specifying table name we can
specify where condition.
Syntax for where condition is:SELECT COLUMN_LIST FROM TABLE_NAME WHERE CONDITION;
Suppose we have a table called EMPLOYEE and we require to fetch employee whose employee number is 10:SELECT * FROM EMPLOYEE WHERE EMPNO=10;

What group by clause is?


When we use aggregate functions in a select query we need to specify group by clause when we use other columns
in select query.
Syntax for group by clause is:SELECT COLUMN_NAME1, COLUMN_NAME2, MIN/MAX/SUM/COUNT/AVG (COLUMN_NAME) FROM
TABLE_NAME WHERE CONDITION GROUP BY COLUMN_NAME1, COLUMN_NAME2;
Suppose, we need to find out employee number with maximum salary we can do this like:-

What having clause is?


Having clause is use after group by clause to specify another condition in after the group by clause.
Syntax for the having clause is:SELECT COLUMN_NAME_LIST, MIN/ MAX/ SUM/ AVG/ COUNT (COLUMN_NAME) FROM TABLE_NAME
WHERE CONDITION GROPU BY COLUMN_NAME1, COLUMN_NAME2 HAVING COLUMN_NAME CONDITION;
We can use having condition like:-

What order by clause is?


Order by clause will help us to order the output in ascending or descending orders. By default its ascending order.
Syntax for using order by clause is:SELECT COLUMN_LIST FROM TABLE_NAME ORDER BY ASCENDING / DESCENDING;
We can use order by condition like:Order by descending:-

Order by ascending:-

Order by ascending (by default):-

Oracle supplied function:There are many functions which are supplied by oracle. These are listed below:Function to convert values in the upper case:SELECT UPPER ('chanchal wankhade') CONV_UPPER FROM DUAL;
Function to convert values to lower case:SELECT LOWER ('CHANCHAL WANKHADE') CONV_UPPER FROM DUAL;
Function to replace any value:SELECT REPLACE ('CHANCHAL WANKHADE','CHANCHAL','WANKHADE') REPLACE_FUNC FROM DUAL;
Function to trim a value or blank space (note there is a space between single code and chanchal and single code
and wankhade):SELECT TRIM (' CHANCHAL WANKHADE ') TRIM_FUNC FROM DUAL;
Function to trunc values:SELECT TRUNC (123456789.1234) TRIM_FUNC FROM DUAL;
Function to make every words first later in capital:SELECT INITCAP ('CHANCHAL WANKHADE') INITCAP_FUNC FROM DUAL;
Function to find out a number by providing two dates:SELECT MONTHS_BETWEEN ('01-DEC-2013','01-JAN-2013') MONTHS_BET FROM DUAL;
SELECT MONTHS_BETWEEN ('01-JAN-2013','01-DEC-2013') MONTHS_BET FROM DUAL;
Function to round the values to till required numbers:SELECT ROUND (12345.123,7) ROUND_FUNC FROM DUAL;
SELECT ROUND (12345.123) ROUND_FUNC FROM DUAL;
Function to find characters which are starting from specific character to specific character:SELECT SUBSTR ('CHANCHAL WANKHADE',5,5) FROM DUAL;
Function to find the positions of the specified character:SELECT INSTR ('CHANCHAL WANKHADE','A',1,1) INSTR_FUNC FROM DUAL;
SELECT INSTR ('CHANCHAL WANKHADE','A',1,2) INSTR_FUNC FROM DUAL;
SELECT INSTR ('CHANCHAL WANKHADE','A',1,3) INSTR_FUNC FROM DUAL;

Above functions which screen shots:-

Inline views:Oracle allows us to use subset in FROM clause of a select query which is known as INLINE VIEW. It treats the inline
view as predefine view even though its not predefined. It is called inline view because it functions like a view in a sub
query.
Lets have an example of inline view:Create employee table and insert some values in that:-

Create dept table and insert some values in that:-

Above we have created two table called employee and dept with some data in it.

Inline view query:If you want to fetch count of records from one table and all the related records from other table then you can achieve
this by below query:-

If you want to select max salary in each department then you can achieve this by below query:-

Sub query in oracle:In oracle, we can define query in WHERE clause of the select statement. It is called sub query because it is a query
in another query.
The difference between inline view and sub query is, inline view is used in FROM clause and sub query is use d in
WHERE clause.

Another example is:-

Variables and Constants:What are variables?


Variables in oracle are used by programmers in the declare block to store data temporarily during execution of the
code. The name of a PL/SQL variable consists of a letter optionally followed by dollar signs, underscores, and
number signs or other characters and should not exceed 30 characters. Syntax of declaring variable is:Variable_name datatype [NOT NULL: = value];
Variable_name is the name of the variable.
Datatype is a valid PL/SQL datatype.
NOT NULL is an optional specification on the variable. If you declare a variable as NOT NULL then best
practice would be to initialize the variable while declaring it.
Value or DEFAULT value is also an optional specification where you can initialize a variable.
If you are declaring variable then you must terminate it by using semicolon at the end.
Suppose you want to declare a variable called V_EMPNO with NUMBER data type which will store number values:DECLARE
V_EMPNO NUMBER;
If you want to declare a variable called V_EMPNAME with VARCHAR2 data type which will store character values:DECLARE
V_EMPNAME VARCHAR2 (10);
Default value:You can declare a variable and provide default value in it:DECLARE
V_EMPNO NUMBER:=123456789;
The (:-) sign is to provide default value.
Suppose you want to declare a variable called V_DEPTNO with NUMBER datatype which will store NUMBER values
and your requirement is this variable should not be NULL then you can do this by below method:DECLARE
V_DEPTNO NUMBER NOT NULL: =10;
Here you have initialized the V_DEPTNO variable with 10. So whenever you execute this variable and will not
provide any value then oracle will consider value for this variable as 10.
Above is hard coded declaration of variable. If there is any type mismatch, variable assignments and comparisons
may not work as expected. Hence, instead of hard coding the type of a variable, we should use the %TYPE operator.

Suppose, above we have declared V_EMPNO as NUMBER and we have to store data from EMPLOYEE table to the
variable V_EMPNO, we can also declare it as:DECLARE
V_EMPNO EMPLOYEE.EMPNO%TYPE;
If you want to store whole row of any table lets say EMPLOYEE table. You can do it by %ROWTYPE operator.
Suppose, you need to store whole row of EMPLOYEE table then you can do this by below method:DECLARE
V_EMPNO EMPLOYEE.EMPNO%ROWTYPE;

How these variables can be used in pl/sql block?


Suppose you want to store a value in variable, you can declare and use this variable like shown below:-

Like shown above, you can use this variable for various manipulations.

What are bind variables?


Bind variables are variables you create in pl/sql and then reference in pl/sql or sql. If you create a bind variable in
pl/sql, you can use the variable as you would a declared variable in your pl/sql subprogram and then access the
variable from pl/sql.
How to create BIND VARIABLES?
You can create bind variable by using VARIABLE keyword like below:VARIABLE VARIABLE_NAME DATATYPE;
For example if you want to declare a bind variable you can do this like:-

How to reference bind variable?


You can reference bind variables in PL/SQL by typing a colon (:) followed immediately by the name of the variable.
For example, to change this bind variable in pl/sql, you must enter a PL/SQL block. For example:

You can print the bind variable by using PRINT keyword:-

What is constant?
Constant is a value of a pl/sql variable which is declared once, and cannot change its value at run time.
If you provide a default value for variable and specify keyword CONSTANT before datatype, it will be treated as
constant and this value will not be changed throughout the program. If you are declaring variable as a constant, you
must provide value to the variable.
Syntax to create a constant is:CONSTANT_NAME CONSTANT DATATYPE: = VALUE;
DECLARE
V_EMPNO CONSTANT NUMBER: =1234567890;
Lets have an example:-

Anonymous block:Anonymous block is unnamed pl/sql program. Unlike other pl/sql named pre-compile object, Anonymous blocks are
not gets stored in a database. There are pre-compile object like store procedure, function package.
Syntax of the anonymous block is:DECLARE
- - - Declaration of variable, constant, cursor etc.
BEGIN
- - - executable part.
EXCEPTION
- - - we can catch any exception/ error here.
END;
Lets try to create anonymous block with Hello World output:DECLARE
V_OUT VARCHAR2 (15);
BEGIN
V_OUT:= HELLO WORLD;
DBMS_OUTPUT.PUT_LINE (V_OUT);
END;

Many new programmer complaints that they have written a pl/sql block correctly and they can see oracle saying
PL/SQL procedure successfully completed. but they are not able to see the output. While writing program you make
habit of making server output on so you would be able to see the result.
Lets have another example:-

What is Iterative Statements in PL/SQL?


An iterative control Statements are used when we want to repeat the execution of one or more statements for
specified number of times.

Scenario:You want to execute some statement multiple times, sometimes you know how many times, sometimes you dont
know how many times your statement should get executed or you want to execute statement at least one time. To do
this kind of work, you would need to use loops. Loop will help you to execute your statement depending upon your
requirement. There are different types of loops. You need to choose which one is best suitable for your requirement.
There are three types of loops in PL/SQL:Simple loop
For loop
While loop
Lets discuss, loops in detail:-

Simple Loop
A Simple Loop is used when a set of statements is to be executed at least once before the loop terminates. An EXIT
condition must be specified in the loop, otherwise the loop will get into an infinite number of iterations. When the EXIT
condition is satisfied the process exits from the loop.
The General Syntax to write a simple loop is:
LOOP
STATEMENTS;
EXIT;
{OR EXIT WHEN CONDITION ;}
END LOOP;

Example of Simple Loop:

While Loop
A WHILE LOOP is used when a set of statements has to be executed as long as a condition is true. The condition is
evaluated at the beginning of each iteration. The iteration continues until the condition becomes false. If while
condition is not true, loop will not execute even once.
The General Syntax to write a WHILE LOOPS is:WHILE <CONDITION>
LOOP STATEMENTS;
END LOOP;
Example of While loop:-

For loop
A FOR LOOP is used to execute a set of statements for a predetermined number of times. Iteration occurs between
the start and end integer values given. The counter is always incremented by 1. The loop exits when the counter
reaches the value of the end integer.

The General Syntax to write a FOR LOOP is:


FOR COUNTER IN VAL1 (MIN_VALUE)..VAL2 (MAX_VALUE)
LOOP STATEMENTS;
END LOOP;
Example of for loop:

Another example is:-

Cursors in pl/sql:-

Scenario:If you want to select data from a table or tables, and based on some condition you need to manipulate that data. You
can achieve this by using cursors. It will store data fetch by sql queries in a private area and that data can then
manipulate accordingly. For this, you must declare the cursor, open that cursor, fetch the records and finally you
should close the cursor.

What is pl/sql Cursors?


A cursor is a temporary work area, created in the system memory when a SQL statement is executed. A cursor
contains information on a select statement and the rows of data accessed by it. This temporary work area is used to
store the data retrieved from the database, and manipulate this data in executable part of the block. A cursor can
hold more than one row, but can process only one row at a time. The set of records cursors currently holds is called
as active set.
There are two types of Cursors:
1) Implicit Cursor
2) Explicit Cursor

Implicit Cursors:
These are created by default when DML statements like, INSERT, UPDATE, and DELETE statements are executed.
They are also created when a SELECT statement that returns just one row is executed.
Attributes of Implicit Cursors:
1) SQL%FOUND
2) SQL%NOTFOUND
3) SQL%ROWCOUNT

Explicit Cursors:
They must be created when you are executing a SELECT statement that returns more than one row. Even though
the cursor stores multiple records, only one record can be processed at a time, which is called as current row. When
you fetch a row the current row position moves to next row.
1)
2)
3)
4)

CURSOR_NAME%FOUND
CURSOR_NAME %NOTFOUND
CURSOR_NAME %ROWCOUNT
CURSOR_NAME %ISOPEN

Steps while accessing cursors:


1)
2)
3)
4)

DECLARE
OPEN
FETCH
CLOSE

Lets have an implicit cursor Example:When you query data on the table implicitly cursor are declare implicitly.

Lets have an explicit cursor example:-

What is cursor with parameter?


We can pass parameter in the cursor and can use them in the query. We need to pass only datatype and not length
of the parameter.
Syntax of the cursor with parameter is:CURSOR CURSOR_NAME (PARAMETER_LIST)
IS
SELECT_STATEMENT;
Lets have an example:DECLARE
CURSOR CUR_1 (C_EMPNO NUMBER)
IS
SELECT EMPNO
FROM EMPLOYEE
WHERE EMPNO=10;
V_EMPNO NUMBER;
V_EMPNO_1 NUMBER;
BEGIN
OPEN CUR_1(V_EMPNO);
FETCH CUR_1 INTO V_EMPNO_1;
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NUMBER '||V_EMPNO_1);
END;

Views in pl/sql:-

Scenario:Above is EMPLOYEE table and EMP_VIEW. View showing only EMPNO, EMPNAME and SALARY columns and not
DEPTNO column from EMPLOYEE table. So, whenever you required to show some column from any table you can
create view and provide view name to the user so they cannot see the actual table name and owner of the table.

There are two types of views:1) View


2) Materialized view
What is view?
View is a virtual table which does not have its owned data, its derived its data from other table called underline or
based tables at a run time. In other words, A view is a representation of a SQL statement that is stored in m emory
so that it can be re-used.
Views are useful for security and information hiding. Some of the advantages of using views:
Reduce the complexity of SQL statements
Share only specific rows in a table with other users
Hide the NAME and OWNER of the base table
To create a view you need to have CREATE VIEW privileges. The syntax of the view is:CREATE VIEW VIEW_NAME AS SELECT STATEMENT;
Suppose, you have EMPLOYEE table with 4 columns, EMPNO, EMPNAME, SALARY and DEPTNO and you also
have DEPT table with DEPTNO and DEPTTYPE column. You are frequently using select query on EMPLOYEE table
and selecting only 3 columns, EMPNO, EMPNAME and SALARY from EMPLOYEE table and DEPTTYPE from
DEPT table, then better you should create view and fetch data from that view only. Lets see how we can do this:-

If you want to create a view on EMPLOYEE table and you want to show DEPTTYPE column from DEPT table, you
can achieve this by creating a view on the EMPLOYEE and DEPT tables:-

You can create view on multiple tables as well like shown below:-

Now lets select the view:-

If you query EMP_VIEW, it will show only 3 columns named as EMPNO, EMPNAME and SALARY from. It does not
show DEPTNO column.
Whenever you will query EMP_VIEW, every time it will go to the EMPLOYEE table and fetch the latest data present
in the table.
If you want to drop the view, you can drop the same by using drop keyword like shown below:-

Materialized view in pl/sql:-

Scenario:Suppose you have one or two database and you need replicate of one of your table, but this replica should retrieve
the result very fast and therefore view is not the best option for that because view takes too much time. So, you
would be need to create a materialized view on the table, which will be refresh on a particular time so the data of the
base table should get reflect in the materialized view. Materialized view are helpful to increase the performance of the
retrieval.
When you create view on the table, every time you query on the view it goes to the base table(s) and retrieve the
fresh data. But materialized view does not show fresh data. It will show you fresh data once it gets refreshed.

What is materialized view?


A materialized view or snapshot as they were previously known is a table segment whose contents are periodically
refreshed based on a query, either against a local or remote table. We can use materialized view to replicate table
situated on another database or remote database.
How to create materialized view?
As shown above, you can create materialized view in same database where your base table is present or in other
database by help of database link (DB Link).
Lets have an example, how to create materialized view in same database where base table resides:Since in oracle, we have facility to set time by when materialized view should get refreshed so we will be adding that
option in create script of the materialized view itself.
Without refresh time option:CREATE MATERIALIZED VIEW MVIEW_NAME AS SELECT QUERY;

Materialized view on employee table without refresh time option:CREATE MATERIALIZED VIEW EMP_MVIEW AS SELECT EMPNO, EMPNAME, SALARY FROM EMP;

We have created above mview on employee table which we would need to refresh at our own. Oracle itself will not
refresh it. It is also called as on demand refresh. We can refresh it like:EXECUTE DBMS_MVIEW.REFRESH ('EMP_MVIEW');

We have done complete refresh and it truncate the materialized segment and rebuild it by using related queries.
Since it truncate and reload data, it can be time consuming process. For faster refresh or to reduce consumption of
time, you can create materialized view LON on base table. LOG will hold all the information about the DML
operations performed on the base table from last refresh and while refreshing it will refresh only the records present
in the LOG because LOG holds only the changes made to the base table since last refresh.
Materialized view log will always be on the base table site.
How to create materialized view log?
Syntax:CREATE MATERIALIZED VIEW LOG ON TABLE_NAME
WITH PRIMARY KEY/ ROWID
INCLUDING NEW VALUES;
In our case, on employee table we can create LOG, if we dont have primary key constraint then we need to use
ROWID clause:CREATE MATERIALIZED VIEW LOG ON EMPLOYEE
WITH ROWID
INCLUDING NEW VALUES;

If we have primary key then we can use that in the log creation script:CREATE MATERIALIZED VIEW LOG ON EMPLOYEE
WITH PRIMARY KEY
INCLUDING NEW VALUES;

With refresh time option:We can create materialized view with refresh time specified in the mview creation script itself like:CREATE MATERIALIZED VIEW MVW_NAME
BUILD IMMEDIATE
REFRESH FAST/FORCE / COMPLETE
ON DEMAND
START WITH (STARTING_DATE) NEXT (NEXT_REFRESH_TIME)
DISABLE / ENABLE QUERY REWRITE
AS (SELECT QUERY);
Example:For fast refresh we would need to create materialized view log first and then we should create materialized view. So
first lets create materialized view log on the EMPLOYEE table.
CREATE MATERIALIZED VIEW LOG ON EMPLOYEE
WITH PRIMARY KEY
INCLUDING NEW VALUES;

Now create a materialized view:-

Above m view get refresh every time on which it was created suppose while creating it was 11 AM, then next day it
will get refresh on same time i.e. 11 AM. If you need to refresh mview on a particular time then you can specify start
with clause by converting your time in TO_DATE.

What is the difference between view and materialized view?


Sr. No

VIEW
The results are fetched from the views base tables
1 when the view is queried.
2 A view occupies no space on a disk
3 It shows real-time data from the base tables

How to drop materialized view and materialized view log?


We can drop materialized view and materialized view log like:-

MATERIALIZED VIEW
The query is executed when the materialized
view is refreshed
A materialized view occupies space on a disk
A materialized view does not reflect real-time
data

Sequence:-

Scenario:Suppose, you required to generate unique number, which you need to use as a primary key or generate sequential
number for your report. In such a case you can use sequence which generates unique number.

What is sequence?
Sequence is an object in oracle which generates unique auto generated number.
Syntax of the sequence:CREATE SEQUENCE SEQUENCE_NAME
MINVALUE VALUE
START WITH VALUE
[MAXVALUE VALUE]
INCREMENT BY VALUE
CACHE VALUE / NO CACHE
CYCLE / NOCYCLE;
Here:MINVALUE: - Is the value min value of the sequence. This values must be less than or equal to start with value.
START WITH VALUE: - Is the value from which sequence will start generating values.
MAXVALUE: - Is the value after which you dont require to generate value.
INCREMENT BY VALUE: - Is a value by which you need to increment your number.
CACHE VALUE: - Specify how many values of the sequence the database reallocates and keeps in memory for
faster access.
CYCLE VALUE: - Specify CYCLE to indicate that the sequence continues to generate values after reaching either its
maximum or minimum value.

Lets try to create a sequence:CREATE SEQUENCE TEST_SEQ


MINVALUE 1
START WITH 1
INCREMENT BY 1
NOCACHE;

You have created sequence now you need to retrieve its next value. To achieve this, there are pseudo columns in
oracle by which you can access sequence.
1) Nextval
2) Currval
NEXTVAL:Next value (nextval) is the pseudo column which will help you to retrieve sequence next value. When you want to use
the sequence with its next value you can use nextval pseudo column. Like shown below:Syntax to retrieve next value is:SEQUENCE_NAME.NEXTVAL;
In our case we have created TEST_SEQ, so we can retrieve its next value like:SELECT TEST_SEQ.NEXTVAL FROM DUAL;

Whenever you will fire this query you will get new number or say unique number and hence this can be used as
primary key since it generates 100 percent unique number.

Currval
Current value (currval) is the pseudo column which will help you to retrieve sequence current value. When you want
to use the sequence and you dont know the current value of the sequence then you can query that sequence with
curval pseudo column to find out what it the current number that sequence it holding. You can do this like below:Syntax is:SEQUENCE_NAME.CURVAL;
In our case we have created TEST_SEQ, lets see what current number this sequence is holding is:SELECT TEST_SEQ.CURRVAL FROM DUAL;

Above its showing 3 since after 3 we have not retrieved any value.
Using sequence in oracle is totally depends on version in which you are using sequence. In 10G, there are less
options, in 11G oracle have come up with enhancement and in 12C its very easy to work with sequence. Below we
have example with each version.

Use of Sequence in oracle 11G:You can create an auto number field by using sequences. A sequence is an object in Oracle that is used to generate
a number sequence. This can be useful when you need to create a unique number to act as a primary key.
Starting with Oracle 11g, we can use sequences with straight variable assignment. Before 11g, we always have to
use SELECT INTO clause to get sequence value in the variable. It is not a major change but just makes it easier to
use. Let us see it with an example. We will first create a sequence.

Here:sequence_name:- The name you want the sequence to have. This may include the user name if created from an
account with DBA privilege. n. An integer, positive or negative.
INCREMENT BY: - Tells the system how to increment the sequence. If it is positive, the values are ascending; if it is
negative, the values are descending.
START WITH: - Tells the system which integer to start with.
MINVALUE: - Tells the system how low the sequence can go. For ascending sequences, it defaults to 1; for
descending sequences, the default value is 10e27-1.
MAXVALUE:-Tells the system the highest value that will be allowed. For descending sequences, the default is 1; for
ascending sequences, the default is 10e27-1.
CYCLE:- Causes the sequences to automatically recycle to minvalue when maxvalue is reached for ascending
sequences; for descending sequences, it causes a recycle from minvalue back to maxvalue.
CACHE: - Caches the specified number of sequence values into the buffers in the SGA. This speeds access, but all
cached numbers are lost when the database is shut down. The default value is 20; maximum value is maxvalueminvalue.

We have created a sequence successfully.


Now we will try to use this sequence in Oracle 10 G.

For assigning the value to declared variable we required to use SELECT INTO clause.
Lets try to assign a value to variable without using SELECT INTO clause:-

Its throwing Error. That means its not supported In Oracle 10 G.


Lets try it in Oracle 11 G:-

Yes, In Oracle 11 G its working fine.

Use of Sequence in oracle 12G:Same like IDENTITY clause, oracle has come up with same functionality with DEFAULT clause. We can specify
default numeric value for the numeric data type column.
By using sequence, we can specify NEXTVAL and CURVAL (pseudo columns) as a default value for a column.
Few things to remember about using sequence pseudo columns as defaults include:
During table creation, the sequence must exist and you must have select privilege on it for it to be used as a
column default.
The users performing inserts against the table must have select privilege on the sequence, as well as insert
privilege on the table.
If the sequence is dropped after table creation, subsequent inserts will error.
Sequences used as default values are always stored in the data dictionary with fully qualified names.
Normal name resolution rules are used to determine the sequence owner, including expansion of private
and public synonyms.
As with any use of a sequence, gaps in the sequence of numbers can occur for a number of reasons. For
example, if a sequence number is requested and not used, a statement including a sequence is rolled back,
or the databases are turned off and cached sequence values are lost.
Below is an example of DEFAULT clause:To perform this activity, user has to have CREATE SEQUENCE and CREATE TABLE privileges.

Procedure in pl/sq:-

Scenario:Suppose in an organization, you have a database and that database is access by many users. All the users are
required to find out the average salary of all employees. For that everyone has created anonymous block and they
are executing it. But think a second; it will downgrade the performance of the database if the table is having millions
of records. Other major thing is when they exit connection to the database and they want to again calculate average
salary then they will have to again create an anonymous block and execute it. But, if you have a named pl/sql block
and it is stored in database and no need to recreate it again and again, that would minimized youre your headache
and at the same time everyone can use it. You can achieve this by creating store procedure.

What is store procedure?


Pl/sql procedure is a precompiled object store as an object in a database which may or may not return any value.
A stored procedure or in simple a proc is a named PL/SQL block which performs one or more specific task. This is
similar to a procedure in other programming languages. A procedure has a header and a body. The header consists
of the name of the procedure and the parameters or variables passed to the procedure. The body consists or
declaration section, execution section and exception section similar to a general PL/SQL Block. A procedure is
similar to an anonymous PL/SQL Block but it is named for repeated usage.
We can pass parameters to procedures in three ways.
1) IN-parameters
2) OUT-parameters
3) IN OUT -parameters
A procedure outside the Package is called Stand alone procedure.
To create procedure you must have create procedure privileges.

Syntax of the Procedure:


CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters]
IS
Declaration section
BEGIN
Execution section
EXCEPTION
Exception section
END;
When you create a procedure or function, you may define parameters. There are three types of parameters that can
be declared:
1. IN - The parameter can be referenced by the procedure. The value of the parameter cannot be overwritten
by the procedure.
2. OUT - The parameter cannot be referenced by the procedure, but the value of the parameter can be
overwritten by the procedure.
3. IN OUT - The parameter can be referenced by the procedure and the value of the parameter can be
overwritten by the procedure.
Lets try to create simple HelloWorld procedure:CREATE PROCEDURE HELLOWORLD AS
AS
BEGIN
DBMS_OUTPUT.PUT_LINE (HELLO WORLD);
END;

Now lets try to execute the procedure HelloWorld:-

Now, lets try to create parameterized procedure and execute it:CREATE OR REPLACE PROCEDURE ADD_TWO_NUMBERS (NUM_1 NUMBER, NUM_2 NUMBER)
AS
V_TOTAL NUMBER;
BEGIN
V_TOTAL:= NUM_1+NUM_2;
DBMS_OUTPUT.PUT_LINE('THE TOTAL OF '||NUM_1 ||' AND '|| NUM_2 ||' IS ' ||V_TOTAL||'.');
END;

Suppose you have a EMPLOYEE table and you want to insert values in it by using procedure. You can do it like:Query EMPLOYEE table first:-

Currently we dont have any records in EMPLOYEE table. Now create a procedure which will insert a record in the
EMPLOYEE table.
CREATE OR REPLACE PROCEDURE EMP_INSERT
(P_EMPNO EMPLOYEE.EMPNO%TYPE, P_EMPNAME EMPLOYEE.EMPNAME%TYPE, P_SALARY
EMPLOYEE.SALARY%TYPE)
AS
BEGIN
INSERT INTO EMPLOYEE (EMPNO,EMPNAME,SALARY)
VALUES (P_EMPNO,P_EMPNAME,P_SALARY);
COMMIT;
END;

Above there are 2 records inserted.


We have seen above how to create simple procedure and parameterized procedure. Lets see how to drop
procedure:Syntax is:DROP PROCEDURE PROCEDURE_NAME;

Pl/sql functions:-

Scenario:When you required to write a block which will always return you some value depending your logic written. For this
you can use stored function which always returns a value.
What is pl/sql function?
A function is a named PL/SQL Block which is similar to a procedure. The major difference between a procedure and
a function is, a function must always return a value, but a procedure may or may not return a value. Second thing is,
we can use functions in select statement, update statement or in anonymous block whereas we cannot use
procedure in select statement, update statement.
Syntax of Function:
CREATE [OR REPLACE] FUNCTION FUNCTION_NAME
[ (PARAMETER [,PARAMETER]) ]
RETURN RETURN_DATATYPE
IS | AS
[DECLARATION_SECTION]
BEGIN
EXECUTABLE_SECTION
[EXCEPTION
EXCEPTION_SECTION]
END [FUNCTION_NAME];
Here:RETURN clause specifies that data type you are going to return from the function.

As said above when you create a procedure or function, you may define parameters. There are three types of
parameters that can be declared:
1. IN - The parameter can be referenced by the procedure or function. The value of the parameter cannot be
overwritten by the procedure or function.
2. OUT - The parameter cannot be referenced by the procedure or function, but the value of the parameter can
be overwritten by the procedure or function.
3. IN OUT - The parameter can be referenced by the procedure or function and the value of the parameter can
be overwritten by the procedure or function.
Lets have an example of a function:-

Above you have created function successfully.

How to execute function:You cannot execute function same like a procedure. Hence it would be wrong if you execute it like:EXEC FUNCTION_NAME [(PARAMETER_NAME, PARAMETER_NAME)]; ------- WILL THROW AN ERROR.
You can execute function by many different ways like:
Using select statement
Using block
Using bind variable
Using dbms_output .put_lines package
Using select statement:SELECT FUNC_EMP_DETAIL FROM DUAL;

Using block:DECLARE
V_VARIABLE VARCHAR2(10);
BEGIN
V_VARIABLE:=FUNC_EMP_DETAIL;
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NAME IS '||V_VARIABLE||'.');
END;

Using bind variable:VARIABLE V_VARIABLE VARCHAR2 (10);


BEGIN
: V_VARIABLE:=FUNC_EMP_DETAIL;
END;
PRINT V_VARIABLE;

using dbms_output.put_line package


EXEC DBMS_OUTPUT.PUT_LINE (FUNC_EMP_DETAIL);
You can drop function like shown below:DROP FUNCTION FUNC_EMP_DETAIL;

Packages in oracle:-

Scenario:When you want to relate some procedures and function with each others or you want to declare global variables you
can use packages. It will hold variables, procedures and functions in one body.

What are packages in oracle?


A package is a schema object that groups logically related PL/SQL types, items, and subprograms. Packages
usually have two parts, a specification and a body, although sometimes the body is unnecessary. The specification
(spec for short) is the interface to your applications; it declares the types, variables, constants, exceptions, cursors,
and subprograms available for use. The body fully defines cursors and subprograms, and so implements the spec.
The concept of global, public and private object in package:As discuss above, to create package we need to create two parts, part 1 is package specification and part 2 is
package body. Objects declared in package specification are called global object. Objects declared in the package
body and not inside any procedures or functions in the package body are called public objects. Objects in the
package body inside the procedures or functions are called private objects. For example:-

How to create a packge?


Syntax of the package is :Syntax for package specification:CREATE [OR REPLACE] PACKAGE PACKAGE_NAME
[AUTHID {CURRENT_USER | DEFINER}]
{IS | AS}
[GLOBAL VARIABLE DECLARATION]
[CURSOR_SPEC ...]
[FUNCTION_SPEC ...]
[PROCEDURE_SPEC ...]
[CALL_SPEC ...]
[PRAGMA RESTRICT_REFERENCES (ASSERTIONS) ...]
END [PACKAGE_NAME];
You do not required to mention package SPECIFICATION keyword while create package specification. Oracle by
default will consider it as a specification.
Syntax for the package body:[CREATE [OR REPLACE] PACKAGE BODY PACKAGE_NAME {IS | AS}
[PUBLIC VARIABLE DECLARATION]
[CURSOR_BODY ...]
[FUNCTION_SPEC ...]
[PROCEDURE_SPEC ...]
[CALL_SPEC ...]
[BEGIN
SEQUENCE_OF_STATEMENTS]
PROCEDURE/ FUNCTION BODY [PRIVATE VARIABLE DECLARATION]
END [PACKAGE_NAME];]
While creating package body you need to specify BODY keyword.
You cannot use public and private variables outside the package body. However you can use global variable even
outside the body.
There can be a package specification without package body but there can not be package body without package
specification.

Lets look at the example of package:Below is the simple package specification:-

Below is the package body of packaged SAMPLE created above:-

We have created SAMPLE package. Now lets see how it can be executed.
Since there are two subprograms inside the package one is procedure and other is function. Both procedure and
function have to be executed in a different way. Like if you want to call procedure from package you would need to
execute it in a different way and procedure in a different way.
Lets try to execute procedure from the package SAMPEL :-

Lets try to execute function from package SAMPLE :-

You can execute function from a packge in a many different ways. like in a plsql block or by using execute
dbms_output.put_line.

If you want to drop package, you can drop by using drop command:Package has two part package specification and package body. If you no longer required package body, you can
drop it or you can drop whole package with body.
Droping package body only:DROP PACKAGE BODY PACKAGE_NAME;
In our case if we want to drop package body then we can drop it like:DROP PACKAGE BODY SAMPLE;
If I dont want whole package then I can drop whole package like:DROP PACKAGE PACKAGE_NAME
In our case we can drop package like:DROP PACKAGE SAMPEL;

Triggers in pl/sql:-

Scenario:You have an EMPLOYEE table and you want to keep track of the DML operations performed on the EMPLOYEE
table. In above case suppose, user A has changed the employee salary which were not required and now you want
to find out what was the last salary (actual salary) and who has change it. You can achieve this by implementing
triggers on the EMPLYOYEE table.

What is trigger?
Trigger is a block of code which gets executed against certain action such as insert, update and delete (DML).
Trigger triggers automatically when associate DML operation is executed.
There are generally 6 types of triggers:Row level trigger
Statement level trigger
Before trigger
After trigger
Instate of trigger
Schema level trigger
Lets discuss each type of trigger in detail:Row level Trigger:
The triggers are fired for each and every record which is inserted or updated or deleted from a table.
Statement level Trigger:
The Triggers are fired for each row of DML operation being performed on a table. We cannot access the column
values for records being inserted, updated, and deleted on the table and not individual records.

Before Triggers:
These triggers are fired before the triggering SQL statement (INSERT, UPDATE, DELETE) is executed. The
execution of triggering SQL statement is stopped depending on the various conditions to be fulfilled in BEFORE
trigger.
After Triggers:
These triggers are fired after the triggering SQL statement (INSERT, UPDATE, DELETE) is executed. The triggering
SQL statement is executed first followed by the code of trigger.
Instate of trigger:
INSTEAD OF triggers provide a transparent way of modifying views that cannot be modified directly through DML
statements (INSERT , UPDATE, and DELETE). These triggers are called INSTEAD OF triggers because, unlike other

types of triggers, Oracle fires the trigger instead of executing the triggering statement.
Schema level trigger:
Schema level triggers are fired when any schema level operation are performed. I.e. if you are creating a table in a
particular schema that have schema level triggers. It will also get triggered when you login or logout to the schema.
Its triggers when DDL statements are performed.
Syntax for creating a trigger:CREATE [OR REPLACE] TRIGGER TRIGGER_NAME
{BEFORE | AFTER | INSTEAD OF} {INSERT [OR] | UPDATE [OR] | DELETE}
[OF COL_NAME] ON TABLE_NAME
[FOR EACH ROW]
WHEN (CONDITION)
BEGIN --- SQL STATEMENTS
END;
Below is a simple example of trigger which will get executed when any update or delete statement is fired on
DEPARTMENT table. it will allow user to update or delete from the DEPARTMENT table and will log that changes to
the DEPT table which we can say its a audit table for DEPARTMENT table. We have also defined a exception below
as if any exception occurs then it will show message that you cannot make any changes.

Dept table is not having any data until now:

Now update department table:

Now query the dept table:

Since we are getting output in dept table so we can say that trigger is working properly.

What is difference between statement level trigger and row level trigger?
Statement level trigger will fire once for one DML statement. For example, suppose you have fire a update statement
and that update statement will affect 1000 rows, irrespective of updating 1000 rows, trigger will fire once only. but if
you have created row level trigger then it will fire 1000 times.

Schema level trigger example:If you dont want to allow drop action on Scott schema then you can create trigger so it will fire and show message to
user that they cannot drop the objects in this schema:CREATE OR REPLACE TRIGGER DROP_TRIGGER
BEFORE DROP ON SCOTT.SCHEMA
BEGIN
RAISE_APPLICATION_ERROR (
NUM => -20000,
MSG => 'CANNOT DROP OBJECT');
END;

Lets try to drop any object from the scott schema:-

Its showing the programmer defined error while dropping the object and hence we can say that the trigger is working
fine.

Exception handling:-

Scenario:While writing pl/sql code, you think there is a possibility that some error would be occurred and you need to track that
error and guide the user, what can be done to tackle with the error occurred. To achieve this, you can handle the
expected error in a exception block. It also called exception handling in oracle.

What exception handling is?


Run-time errors arise from design faults, coding mistakes, hardware failures, and many other sources, it is called
exception. Although you cannot anticipate all possible errors, you can plan to handle certain kinds of errors
meaningful to your PL/SQL program.
Exception handling can be categorized into the following parts:
1) Name system exception
2) Name programmer define exception
3) When others exception
Name system exception
Named system exceptions are exceptions that have been given names by PL/SQL and do not need to be defined by
the programmer.

Oracle has a standard set of exceptions already named as follows:Oracle Exception Name

Oracle Error

Explanation

DUP_VAL_ON_INDEX

ORA-00001

You tried to execute an INSERT or UPDATE statement that has created a


duplicate value in a field restricted by a unique index.

TIMEOUT_ON_RESOURCE

ORA-00051

You were waiting for a resource and you timed out.

T RANSACT ION_BACKED_OUT

ORA-00061

The remote portion of a transaction has rolled back.

INVALID_CURSOR

ORA-01001

You tried to reference a cursor that does not yet exist. This may have
happened because you'v e executed a FET CH cursor or CLOSE cursor
before Opening the cursor.

NOT_LOGGED_ON

ORA-01012

You tried to execute a call to Oracle before logging in.

LOGIN_DENIED

ORA-01017

You tried to log into Oracle with an invalid username/password


combination.

You tried one of the following:


1.
NO_DATA_FOUND

ORA-01403
2.
3.

You executed a SELECT INTO statement and no rows were


returned.
You referenced an uninitialized row in a table.
You read past the end of file with the UTL_FILE package.

TOO_MANY_ROWS

ORA-01422

You tried to execute a SELECT INTO statement and more than one row
was returned.

ZERO_DIVIDE

ORA-01476

You tried to divide a number by zero.

INVALID_NUMBER

ORA-01722

You tried to execute an SQL statement that tried to convert a string to a


number, but it was unsuccessful.

ST ORAGE_ERROR

ORA-06500

You ran out of memory or memory was corrupted.

PROGRAM_ERROR

ORA-06501

This is a generic "Contact Oracle support" message because an internal


problem was encountered.

VALUE_ERROR

ORA-06502

You tried to perform an operation and there was a error on a conversion,


truncation, or invalid constraining of numeric or character data.

CURSOR_ALREADY_OPEN

ORA-06511

You tried to open a cursor that is already open.

Syntax for using named exception handling is:The syntax for the Named System Exception in a procedure is:EXCEPTION
WHEN DUP_VAL_ON_INDEX
THEN
[DO SOMETHING]
WHEN INVALID_CURSOR
THEN
[DO SOMETHING]
WHEN NO_DATA_FOUND
Below is the sample example of named system exception:1) Create a table called Tran.

2) Create a procedure for insert records:

3) Insert records in the Tran table like below:

Above, while inserting duplicate record in the table it showing You have entered a duplicate value which we
have handle in the exception block of the procedure.

Programmer define exception


Sometimes, it is necessary for programmers to name and trap their own exceptions - ones that aren't defined already
by PL/SQL. These are called Named Programmer-Defined Exceptions.
Syntax of the programmer defined exception is:DECLARE
EXCEPTION_NAME EXCEPTION;
BEGIN
EXECUTABLE_SECTION
RAISE EXCEPTION_NAME;
EXCEPTION
WHEN EXCEPTION_NAME THEN
[STATEMENTS]
WHEN OTHERS THEN
[STATEMENTS]
END [PROCEDURE_NAME];

Lets have a sample example of programmer define exception:


Create a table

Create a procedure

Execute a procedure

By inserting duplicate record into the Tran table the no_tran Exception is raised and it is said programmer
defined exception.

Operators in oracle:-

There are different types of operators available in oracle:Set operator


Arithmetic operator
Character operator
Comparison operator
Logical operator
Other operator

1) Set operator:Set operators combine the results of two queries into a single result.
There are mainly 4 types of Set Operators listed as below:Operator
UNION

What it does
This combines the results of two queries and returns the set of distinct rows
returned by either query

UNION ALL

This combines the results of two queries and returns all rows returned by either
query, including duplicates

MINUS

This combines the results of two queries and returns the distinct rows that were
in the first query, but not in the second

INTERSECT

This combines the results of two queries and returns the set of distinct rows
returned by both queries

1) UNION:Union operator retrieves records from both queries by eliminating duplicate records. Query should have common
numbers of columns in each query OR if required, will have to specify dummy column and convert the data type of
the column to null which is/are not present in one table and exist in other table. We will see the examples how to
archive this.
For verifying the result of Set operator we will create two tables called TEST and TEST_1.
TEST table having 7 records :-

TEST_1 table having 10 records:-

Above we have created TEST and TEST_1 table which are having 7 and 10 records respectively. All the records are
unique from both the tables so it should retrieve all the records:-

Now lets try to use UNION Operator:-

17 records are retrieved from the above query. Now insert a duplicate record in one of table and again execute a
select query. We will inset the record in TEST table which is duplicate record:-

Now again execute select query and see the result.

After inserting duplicate record its showing 17 records only. I.e. duplicate records are not showing.

2) UNION ALL:UNION ALL operator retrieves all the records from both the queries. It does not worry about duplicate records and
hence is faster than UNION operator.
For the example we will again use the TEST and TEST_1 tables.

TEST table is having 8 records and TEST_1 table is having 10 records.


Execute the select query to use UNION ALL operator:-

UNION ALL operator showing total 18 records and that is correct.

Question: - I need to select 4 columns from one table and 3 columns from second table, how can I use UNION or
UNION ALL operator to retrieve the desired output?
Answer: - To achieve the desire output you need to specify the dummy column and convert the data type of the
dummy column to the data type of the second tables column. Lets try the example.
Data in the tables are as follows. TEST_1 table does not have deptno column:-

Now by adding dummy deptno column, try to retrieve the records as shown below:-

It shows blank/null records for the rows from the TEST_1 table.
Note:You need to convert both the column in char data type otherwise it will through error
ORA-01790: expression must have same data type as corresponding expression

3) MINUS:MINUS operator returns only distinct rows return by the first query and not by the second query.
In other words MINUS operator retrieves all the records which are present in the first query and not in second query.
We will see the simple example like, we have 1 to 10 empno in the TEST_1 and 1,2,3,4,6,8,9 and 10(excluding 5 and
7) in TEST table. So we can find it out by the query using MINUS operator.

If we do it by reveres then we will not get any row since all the empno in the TEST table present in the TEST_1 table.

4) INTERSECT :The SQL INTERSECT query allows you to return the results of 2 or more select queries. Intersect operator return
only those records which are return by both the queries. It finds out matching records from both the queries (tables).
It the record is available in one query and not in other, it will omit the record.
We will see the example:First query both the tables. Now try to find out which are the records are matching in both the tables.

If you try to find out on empno only, result will be changed since there are many employee numbers which are same
in both the tables. So if we query on employee number only then the result would be like-:

2) ARITHMETIC OPERATOR:Arithmetic operators manipulate numeric operands.


Below is the list of arithmetic operators.
Arithmetic Operation
+

Arithmetic Operation Explanation


Used for addition in SQL

Used for Multiplication in SQL

Used for division in SQL

Used for Subtraction in SQL

We will see the example of arithmetic operator with the help of DUAL table of oracle which is virtual table having 1
column and 1 row.

We will see the example of these operators in respect to table. We can use these operators to show increase in the
salary like:-

3) Character operator:Character operators are used in expressions to manipulate character strings.


|| (Concatenate) is a character operator.
We can use concatenate operator to combine two character string.
Below are the various types of example to use character operator:-

4) Comparison operator:Comparison operators are used in conditions that compare one expression with another. The result of a comparison
can be TRUE, FALSE, or NULL.
Comparison operators are used to compare one value or expression to another.
All comparison operators return a Boolean result.
Operator
=
<>,!=,~=
<
>
<=
>=
LIKE
BETWEEN
IN
IS NULL
ALL

Usage
Equality operator.
Inequality operator.
Less than operator.
Greater than operator.
Less than or equal to operator.
Greater than or equal to operator.
Pattern-matching operator.
Checks to see if a value lies within a specified range of values.
Checks to see if a value lies within a specified list of values.
Checks to see if a value is null.
Compares a value with every value in a list or returned by a query.

We would be using TEST and TEST_1 table to see the examples of the above operators:-

Below are the some examples of the comparison operators:-

5) Logical operator:There are three Logical Operators namely, AND, OR and NOT. These operators compare two conditions at a time to
determine whether a row can be selected for the output. When we retrieve data using a SELECT statement, we can
use logical operators in the WHERE clause, which allows you to combine more than one condition.
Operator

What it does

NOT

Reverses the meaning of another logical expression's result

OR

Logical ORTrue if any are true, false else

AND

Logical ANDTrue if all are true, else false

Below are some examples of the Logical operators:-

6) Other operator :We have (+) operator in the category of other operator.
(+) indicates that the preceding column is the outer join column in a join.
(+) sign in the where condition in join indicates that, query should retrieve all the records from the table which column
name does not contain (+) sign after the column name and only matching rows from the other table.
Structure and data of the TEST and TEST_1 TABLE.

Output for (+) operator:-

Above we have tried to cover all the operators which are available in oracle. There are more operators we will see
them in a next book.

Conditional Statements:-

Scenario:When you required to perform conditional operations and you need to specify if a student got 6o above marks then
he has secured first class or if he got below 60 percent marks but above 45 percent marks then he has secured
second class and vice versa. If you want to performed this kind of condition operation then you can use IF THEN
ALSE condition.

What is conditional statement?


As the name implies, PL/SQL supports programming language features like conditional statements, iterative
statements.
Conditional operator is:
IF THEN ELSE STATEMENT or IF THEN ELSIF ELSE.
Syntax for conditional statement is:CONDITION 1 (IF THEN ELSE)
IF CONDITION
THEN
STATEMENT 1;
ELSE
STATEMENT 2;
END IF;
NOTE:
When you are writing IF it means you have started condition hence you must close it and for that we have specified
END IF.

CONDITION 2 (IF THEN ELSIF ELSE)


IF CONDITION 1
THEN
STATEMENT 1;
STATEMENT 2;
ELSIF CONDTION2 THEN
STATEMENT 3;
ELSE
STATEMENT 4;
END IF
Below is the example with conditional statement which show which is the maximum number in the given
numbers:-

Lets see another example which will calculate your net salary:-

Job scheduler:-

Scenario:When you need to execute any procedure or any job on a particular time or repeated times, you can do it by using
various windows commands tasks in windows or any other third party softwares. While using windows command and
other tools we required to specify all the information like database user name, password and database name. This
will cause a problem, if you have a password change policy. Say you have a policy to change password in every 1
month. Every month you have to go the windows command and change the password manually. but in oracle, oracle
have its own job scheduler which runs on the given time and the beauty of it is, it doesnt require database name,
database user name and password since we create it in the schema where our procedure resides.
What oracle dbms_scheduler is?
Dbms_scheduler.create_job package will allow you to create a job which will fire on a given time. Suppose you need
to execute a procedure on 3 oclock, you can schedule a job and specify the name of the procedure which needs to
be executed; oracle job scheduler will execute it automatically. Its very simple and flexible solution to schedule jobs.
Syntax for creating a job scheduler is:BEGIN
DBMS_SCHEDULER.CREATE_JOB (
JOB_NAME
=> 'NAME_OF_THE_JOB,
JOB_TYPE
=> 'PLSQL_BLOCK/ PROCEDURE',
JOB_ACTION
=> 'BLOCK_NAME; END;,
START_DATE
=> SYSTIMESTAMP,
END_DATE
=> NULL / IF_YOU_WANT_TO_PUT_ANY_DATE,
COMMENTS
=> 'ANY_COMMENT_YOU_WANT_TO_SPECIFY.
ENABLED
=> TRUE / FALSE,
REPEAT_INTERVAL => 'FREQ=MONTHLY / DAILY; BYDAY=; BYHOUR=; BYMINUTE=; BYSECOND=;);
END;

Lets try to create a job which will trigger on 1 ST day of every month at 10 am:Suppose my procedure name is PROC_TEST:BEGIN
DBMS_SCHEDULER.CREATE_JOB (
JOB_NAME
=> 'MONTHLY_TESTING_JOBS',
JOB_TYPE
=> 'PLSQL_BLOCK',
JOB_ACTION => 'BEGIN PROC_TEST; END;',
START_DATE => SYSTIMESTAMP,
END_DATE
=> NULL,
COMMENTS => 'JOB IS CREATED FOR TESTING PURPOSE.,
ENABLED
=> TRUE,
REPEAT_INTERVAL => 'FREQ=MONTHLY; BYMONTHDAY=1; BYHOUR=10');
END;
Now, try to create a job which will fire daily basis:BEGIN
DBMS_SCHEDULER.CREATE_JOB (
JOB_NAME
=> 'NAME_OF_THE_JOB',
JOB_TYPE
=> 'PLSQL_BLOCK / PROCEDURE',
JOB_ACTION => 'BEGIN BLOCK_NAME; END;',
START_DATE => SYSTIMESTAMP,
END_DATE
=> NULL,
COMMENTS
=> 'COMMENT THAT YOU WANT TO SPECIFY.',
ENABLED
=> TRUE,
REPEAT_INTERVAL => 'FREQ=DAILY; BYDAY=MON, TUE, WED, THU, FRI, SAT, SUN; BYHOUR=TIME;
BYMINUTE=MINUTES; BYSECOND=SECOND ;');
END;
Lets try to create a job which will trigger daily at 11 am:Suppose my procedure name is PROC_TEST:BEGIN
DBMS_SCHEDULER.CREATE_JOB (
JOB_NAME
=> 'DAILY_TESTING_JOB',
JOB_TYPE
=> 'PLSQL_BLOCK',
JOB_ACTION
=> 'BEGIN PROC_TEST; END;',
START_DATE
=> SYSTIMESTAMP,
END_DATE
=> NULL,
COMMENTS
=> 'JOB IS CREATED FOR TESTING PURPOSE.',
ENABLED
=> TRUE,
REPEAT_INTERVAL => 'FREQ=DAILY; BYDAY=MON, TUE, WED, THU, FRI, SAT, SUN; BYHOUR=11;
BYMINUTE=00; BYSECOND=0 ;');
END;

If everything is correct then the above created jobs will execute on given time. But in case you need to execute them
manually, you can execute it by using dbms_scheduler_run_job oracle supplied package.
Syntax to run job manually:EXEC DBMS_SCHEDULER.RUN_JOB (JOB_NAME => 'NAME_OF_THE_JOB');
Suppose, we want to execute DAILY_TESTING_JOB, we can execute it like:EXEC DBMS_SCHEDULER.RUN_JOB (JOB_NAME => 'DAILY_TESTING_JOB');
Dropping jobs:If we dont required job anymore then we can drop it by using dbms_scheduler.drop_job oracle supplied package.
Syntax for dropping job is:BEGIN
DBMS_SCHEDULER.DROP_JOB(JOB_NAME =>'JOB_NAME');
END;
In our case, if we want to drop the job then we can drop it like:BEGIN
DBMS_SCHEDULER.DROP_JOB(JOB_NAME =>'DAILY_TESTING_JOB');
END;

Sql loader:-

Scenario:You have a text files or excel files or dat files or any other flat files which you need to upload in the database and do
some manipulations. Like you need to upload data in a table and use it for future. You will create index and primary
key on it to enhance the performance of the query. To achieve this you can use sql loader oracle supplied tool to
lead data from external files to oracle table.
What sql loader is?
Sql loader is oracle supplied tool to load data from external files to oracle tables. To use sql loader you would need to
create a directory (since oracle does not directly to windows files) which will work like a middle man to oracle and
external files.
Directory in oracle:Oracle directory is an object pointing to an operating systems directory from the oracle server to read or write the
data.
For example, If you need to read data from oracle which is located on windows directory c: \test\exaple folder, while
programming you cannot directly assign this path. Instate, you can make oracle directory which will represent that
path by a specific name of the directory.
Only created directory will not make your job over. To use that directory you must grant privileges to require user.
General syntax for creating directory is:
CREATE OR REPLACE DIRECTORY DIRECTORY_NAME AS WINDOWS_PATH.
Example can be:CREATE OR REPLACE DIRECTORY TEST AS F: \CHANCHAL;

After creating directory successfully, grant the privileges to require user(s):GRANT READ, WRITE ON DIRECTORY TEST TO USER_NAME;
Now we have created a directory and granted required privileges. So we are ready to use the directory.
Lets see an example how to upload data from excel to oracle using sql * loader:A simple way to upload data from Excel to Oracle is to use SQL* LOADER which is Oracle supplied tool. It is highly
preferred tool by programmers and DBAs. It uploads data very quick and fast.
As you know, you cannot upload data directly from Excel to Oracle. For that you have to save the excel sheet as
.csv file. .csv stands for comma separated value.
While uploading data from excel to oracle scenario would be like Excel -> Csv -> Oracle.
Suppose you have a excel file called Test and you need to upload it in oracle. So you will first convert it into the .csv
file. So lets rename Test excel file as Test.csv file like shown below:-

And save the file in F:\CHANCHAL Folder.

So we are ready with whatever we required to upload data from excel to oracle:Now, In order to upload data from excel to oracle the data which is coming from a file needs to be resides in a table.
So lets create a table:-

Structure of the table must be same in a sequence like it is in excel file(s).


Now, in order to load data from excel to oracle, we would required to create control file.
What is control file?
To load data from .csv file to oracle we would require control file. Control file holds all the information about execution
of the sql*loader, Like Name of the csv file, Name of the directory on which file is present, Column list, Name of the
target table etc. The SQL*Loader control file is a repository that contains the DDL instructions that you have created
to control where SQL*Loader will find the data to load, how SQL*Loader expects that data to be formatted, how
SQL*Loader will be configured.

How to create control file?


Creating control file is very easy. Open a notepad and save it as TEST.CTL (In Double quotes). Like above we
have save .csv file as csv (comma delimited)(*.csv). The path where you need to save control file is very important.
You must know where you have to save the control file. In our case we are saving it on F: \chanchal windows
directory which is also directory for oracle.

What control file will contain?


Generally syntax for control file would be:LOAD DATA
INFILE WINDOWS_PATH
TRUNCATE / REPLACE / APPEND
INTO TABLE TABLE_NAME
FIELDS TERMINATED BY ,
OPTIONALLY ENCLOSED BY
TRAILING NULLCOLS
(COLUMN_NAME, COLUMN_NAME)
Here:
Infile: - is a file from which, data will be imported in the oracle table.
Truncate: - Is use for truncating the table before inserting the records.
Replace: - All rows in the table are deleted and the new data is loaded. This option requires DELETE
privileges on the table.
Append: - If data already exists in the table, SQL* Loader appends the new rows to it; if data doesn't
already exist, the new rows are simply loaded.
Trailing nullcols: - The TRAILING NULLCOLS clause tells SQL* Loader to treat any relatively positioned
columns that are not present in the record as null columns.
Fields Terminated by: - This clause tells SQL* LOADER that fields will be terminated by.
Optionally Enclosed By: - This clause tell SQL* LOADER fields can be optionally enclosed by.

In our case, in order to upload data from Text.csv file to Test table, we would need to create control file which is also
called as Test.ctl. Write below code in the control file and save it:LOAD DATA
INFILE F:\CHANCHAL\TEST.CSV
APPEND
INTO TABLE TEST
FIELDS TERMINATED BY ,
OPTIONALLY ENCLOSED BY
TRAILING NULLCOLS
(EMPNO, EMPTYPE, SALARY)
Now query the test table before executing SQL* LOADER.

Now go to the Command prompt. Command prompt will have path like C:\DOCUMENTS AND SETTINGS\USER_NAME.
User_Name will be the user by which you have login to the server or machine.
For execute the SQL* LOADER control file you must be on the path where your control file resides. So we will
change the path as:

Note: - In the blank space above, there would be your user name.
Check whether we have both the files TEST.CSV and TEST.CTL on F:\Chanchal Location as we have specified
same location for both the files.
When you come to F:\CHANCHAL in command prompt, execute the below statement:SQLLDR USERID=USER_NAME/PASSWORD@DATABASE_NAME CONTROL=TEST.CTL

NOTE: IN THE BLANK SPACE ABOVE THERE WILL BE YOUR DATABASE USER NAME / PASSWORD AND @DATABASE NAME.

As I have only 6 records in .csv file, it clearly shows COMMIT POINT REACHED LOGICAL RECORD COUNT 6.
For verification whether the data is inserted in the table or not we will query the TEST table:

As you can see we can find data in the table so it means we have performed all the steps correctly.
While Executing control file there are some files which automatically get c reate in the location from where you are
executing the control file or you can specify the path for same. These are as follows:
1) Log File
2) Bad file

3) Discard file
Log File
The log file contains information about the SQL*loader execution. It should be viewed after each SQL*Loader job is
complete. Especially interesting is the summary information at the bottom of the log, including CPU time and elapsed
time. The data below is a sample of the contents of the log file.
Bad File
A bad file is created, when at least one record from the input file is gets rejected. The rejected records are placed in
this file. A record could be rejected for many reasons, including a non-unique key or a required column being null.
Discard file
Discard file contains information about the data which we have intentionally skipped while uploading.
NOTE: - DONT FORGET TO CHECK THE LOG FILE AFTER EXECUTION OF CONTROL FILE.

External table:-

Scenario:If you required to get data from external files which will be outside the database but will seems like it is in the
database. Your need is, it should look like a table to the user.
What external table is?
External table enables you to access data in external sources as if it were in a table in the database.
There are some restrictions while using external tables. As external tables can be queried, they're not usable in many
ways regular oracle tables are. You cannot perform any DML operations on external tables other than table creation;
one consequence is that you can't create an index on an external table. External tables are largely used as a
convenient way of moving data into and out of the database.
Lets start creating external table.
You will need the oracle directory first so lets create it.
CREATE OR REPLACE DIRECTORY TEST AS F: \CHANCHAL\;

Grant read and writes privileges to required users.


GRANT READ, WRITE ON TEST TO USER_NAME;

Now we are ready to create a table. Create a table like shown below:
Directory name is TEST and file name is TEST.CSV:-

Note: - While creating a table there is a parameter before Default Directory , TYPE ORACLE_LOADER. When you
do not specify there, oracle will by default assume that type is oracle_loader.
Now we can select data from TEST table:
Data would not be present in the table until and unless you select it. So lets query on the table:-

By default, a log of load operations is created in the same windows directory as the load files, but this can be
changed using the LOGFILE parameter.
Any rows that fail to load are written to a bad file. By default, the bad file is created in the same directory as the load
files, but this can be changed using the BADFILE parameter.
In access parameter you can add bad file name and log file name as shown below:ACCESS PARAMETERS
(
RECORDS DELIMITED BY NEWLINE
BADFILE BDUMP:'READ_ALERT_%A_%P.BAD'
LOGFILE BDUMP:'READ_ALERT_%A_%P.LOG'
FIELDS TERMINATED BY ','
MISSING FIELD VALUES ARE NULL
(
LINE CHAR (4000)
)

What is the difference between sql * loader and external tables:While using sql * loader we can perform DML operations one table. but in case of external tables we can do DML
operations. We also cannot create index on external tables nor can create constraints. Lets have an example:-

If you want to perform DML operations on the table which is created while using sql * loader, you can do it like normal
DML operations.

Merge in pl/sql:-

Scenario:When you required to compare two tables and require to update one of the tables if same records are present in
comparing table. In simple words, you have two tables table 1 and table 2. Both the tables almost contain same data,
at the same time table 1 contains 10 records more than the table 2. So you need to update table 2 so it will hold data
same as table 1. To do this, we can use MERGE to compare and insert or update records based on condition
specified.
What merge is?
The SQL MERGE command is combination of sequential conditional INSERT and UPDATE commands in a single
atomic statement, depending on the existence of a record. This operation is commonly known as Upsert
functionality. Upsert is the combination of Update or Insert.
Syntax for Merge statement is as below:MERGE INTO TABLE_NAME USING TABLE_REFERENCE ON (CONDITION)
WHEN MATCHED THEN
UPDATE SET COLUMN1 = VALUE1 [, COLUMN2 = VALUE2 ...]
WHEN NOT MATCHED THEN
INSERT (COLUMN1 [, COLUMN2 ...]) VALUES (VALUE1 [, VALUE2 ...
HERE,
INTO Clause - The INTO clause is used to specify the target table into which you are inserting or updating.
USING Clause - The USING clause specifies the source of the data to be updated or inserted. The source for a
MERGE statement can be a table, view, or the result of a sub-query.

ON Clause - The ON clause specifies the condition that the MERGE operation uses to determine whether it updates
or inserts. When the search condition results to true, Oracle updates the row in the target table with corresponding
data from the MERGE source. If no rows satisfy the condition, then Oracle inserts the row into the target table based
on the corresponding MERGE source row.
merge_update_clause - The merge_update_clause is used to specify the update column values of the target table.
Oracle performs the specified update if the condition of the ON clause is true. As with any normal update, when the
update clause is executed, all update triggers defined on the target table are fired.
Lets have a example of merge:Create a table called Test:-

Here I have not specified any constraint but you may have constraint on your table which can be called well structure
table.
Insert some values in the table TEST:-

Now create a Source table Test_1 and insert some data into it as shown below:-

Above we have created a table same as Table test and also inserted some new records into it.
So there are now 10 records in the table TEST_1 and 5 records in TEST table.
Now our requirement is to update the table TEST and insert the values which are not present in TEST table and
update if that are present. We will use MERGE statement below to fulfill the requirement:CREATE OR REPLACE PROCEDURE ORACLE_MERGE AS
UPDATE_CNT NUMBER(6):= 0; ------VARIABLE DECLARED HARE WHICH WILL HOLD COUNT OF INSERT AND UPDATE.
INSERT_CNT NUMBER(6):= 0;
BEGIN
DBMS_OUTPUT.PUT_LINE('START >> ' || TO_CHAR(SYSDATE,'DD-MON-YY HH:MI:SS AM') );
MERGE INTO TEST A USING TEST_1 B
ON (A.EMPNO=B.EMPNO) ------- YOU CAN SPECIFY HERE AS MUCH PRIMARY KEYS AS YOU HAVE.
WHEN MATCHED THEN
UPDATE SET A.EMPNO=B.EMPNO,
A.EMPTYPE=B.EMPTYPE,
A.SALARY=B.SALARY
WHEN NOT MATCHED THEN
INSERT (EMPNO, EMPTYPE, SALARY)
VALUES (B.EMPNO,
B.EMPTYPE,
B.SALARY);
INSERT_CNT:= MERGE_IN SERTUPDATE_RECORD.GET_MERGE_INSERT_COUNT;
UPDATE_CNT:= MERGE_INSERTUPDATE_RECORD.GET_MERGE_UPDATE_COUNT (SQL%ROWCOUNT);
DBMS_OUTPUT.PUT_LINE ('ROWS UPDATED >> ' || UPDATE_CNT);
DBMS_OUTPUT.PUT_LINE ('ROWS INSERTED >> ' || INSERT_CNT);
DBMS_OUTPUT.PUT_LINE ('END >> ' || TO_CHAR (SYSDATE,'DD-MON-YY HH:MI:SS AM') );
DBMS_OUTPUT.PUT_LINE ('PART PROCESS END >> ' || TO_CHAR (SYSDATE,'DD -MON-YY HH: MI: SS AM'));
MERGE_INSERTUPDATE_RECORD.RESET_COUNTERS;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE ('SOME ERROR OCCURED');
END;

Select the count by querying test and test_1 table, there must be 5 and 10 records respectively:-

Now our requirement is to update or insert records from TEST_1 table. So execute the above created procedure.
Execute Procedure as shown below:-

After execution it clearly shows that rows updated and rows inserted are 5 each which are correct.
Now again Confirm the changes by querying test table:

By using above procedure we have done inserting or updating records by oracle Merge statement.

Composite datatype:In simple words, composite datatype is a collection of multiple scalar data type. For example, if I want to combine
varchar2 and number and date datatype in as a one datatype I can do it by using oracle collections. Composite types
have internal components that can be manipulated individually, such as the elements of an array, record, or table.
There are different types of composite data types. Once again look at the diagram below:-

In composite datatype we have records and collection. Collection again consist of three other composite datatype i.e.
index by tables, varray (variable size array) and nested tables. Each one of them has different meaning and different
usage. Its an advance programming techniques. Composite datatype contains internal component which can be
manipulated individually or as a unit. Lets look at the composite datatype in detail:-

Records:Record is a group of related data items stored in a field which have its own name and its datatype. Each record
defined can have as many fields as necessary. We can assign initial values to records or it can be null as well.
Record types and user define records can be use in any block, subprogram or in a package.
Syntax of the records is:TYPE RECORD_TYPE_NAME IS RECORD (FIRST_FIELD_NAME DATATYPE, SECOND_FIELD_NAME
COLUMM_ DATATYPE...);
Here:-

record_type_name it is the name of the composite type you want to define.


First_field_name, second_field_name:- it is the names the columns within the record.
Column_datatype defines the scalar datatype of the fields.
We can also use %rowtype as datatype of the record element if the record will be associate with one table.
We can use %rowtype like: - TABLE_NAME%ROWTYPE
Suppose we have employee table then it would be: - EMPLOYEE%ROWTYPE;

Sample example of the record type (%ROWTYPE) can be like below:DECLARE


REC_VARIABLE EMPLOYEE%ROWTYPE;
BEGIN
SELECT * INTO REC_VARIABLE FROM EMPLOYEE WHERE EMPNO=4;
DBMS_OUTPUT.PUT_LINE ('THE ROW IS '||REC_VARIABLE.EMPNO||', '||REC_VARIABLE.EMPNAME);
END;

Similarly you can use record to insert values into the table:-

We can also use cursor based record as will.

Cursor based records:Cursor based records are work similar to the %ROWTYPE but instate of table/view name in the type declaration we
need to use cursor name like shown below:CURSOR CUR_NAME AS SELECT_QUERY;
V_VARIABLE CUR_NAME%ROWTYPE;
In above case we are using rowtype which is selected by cursor. So the example can be:DECLARE
CURSOR EMP_CUR IS
SELECT EMPNO, EMPNAME, DEPTNO
FROM EMPLOYEE;
REC_VARIABLE EMP_CUR%ROWTYPE;
BEGIN
OPEN EMP_CUR;
LOOP
FETCH EMP_CUR INTO REC_VARIABLE;
EXIT WHEN EMP_CUR%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(REC_VARIABLE.EMPNO || ',' || REC_VARIABLE.EMPNAME);
END LOOP;
END;

Above we have use cursor name and whatever number of columns that cursor holding.
We have use %ROWTYPE to display and insert values in the table. But this record type (%ROWTYPE) most of the
time would be usable when we do manipulation on a particular (single) table, but what if we want to fetch or
manipulate data from multiple table/ views. To achieve this we can declare record and can use that record in the
anonymous block or any subprograms. So lets try to declare and use user defined record type.

User defined record:User defined record type is a type which is created by user which contains the list of column which are required by
the user. Suppose you need to create two varchar columns and two number columns in a record type and you have
no option but declaring record which will contain all above things. So lets create the same.
Syntax of the user defined record is:TYPE RECORD_TYPE_NAME IS RECORD
(
FIELDNAME_1 DATATYPE_1,
FIELDNAME_2 DATATYPE_2,
FIELDNAME_3 DATATYPE_3,

);
V_VARIABLE_NAME RECORD_TYPE_NAME;
Lets look at the example:DECLARE
TYPE EMP_RECT IS RECORD
(REC_EMPNO NUMBER,
REC_EMPNAME VARCHAR2(20),
REC_DEPTTYPE VARCHAR2(20));
V_VARIABLE EMP_RECT;
BEGIN
V_VARIABLE.REC_EMPNO:=100;
V_VARIABLE.REC_EMPNAME:='CHANCHALL';
V_VARIABLE.REC_DEPTTYPE:='IT';
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NUMBER IS '||V_VARIABLE.R EC_EMPNO||' EMPLOYEE NAME IS '
||V_VARIABLE.REC_EMPNAME||' DEPARTMENT IS '||V_VARIABLE.R EC_DEPTTYPE);
END;

Another example can be like below:DECLARE


TYPE EMP_RECT IS RECORD
(REC_EMPNO NUMBER,
REC_EMPNAME VARCHAR2(20),
REC_DEPTTYPE VARCHAR2(20));
CURSOR CUR IS SELECT A.EMPNO,A.EMPNAME,B.DEPTTYPE
FROM EMPLOYEE A, DEPARTMENT B
WHERE A.DEPTNO=B.DEPTNO;
V_VARIABLE EMP_RECT;
BEGIN
OPEN CUR;
FETCH CUR INTO V_VARIABLE;
CLOSE CUR;
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NUMBER IS '||V_VARIABLE.R EC_EMPNO||' EMPLOYEE NAME IS '
||V_VARIABLE.REC_EMPNAME||' DEPARTMENT IS '||V_VARIABLE.R EC_DEPTTYPE);
END;

Below are the screenshots of above examples:-

Collection:A collection is an ordered group of elements having the same data type. Each element is identified by a unique
subscript that represents its position in the collection.
PL/SQL has three collection types:Index-by tables or Associative array
Nested table
Variable-size array or Varray
Index by tables:An index-by table is also called as associative array is a set of key-value pairs. Each key is unique and is used to
locate the corresponding value. The key can be either an integer or a string.
Syntax of the index by table is:TYPE TYPE_NAME IS TABLE OF ELEMENT_TYPE INDEX BY SUBSCRIBE_TYPE;
Lets look at the example of the index by table:DECLARE
TYPE TAB_TYPE IS TABLE OF NUMBER INDEX BY VARCHAR2(20);
V_VARIABLE TAB_TYPE;
NAME VARCHAR2 (20);
BEGIN
V_VARIABLE ('CHANCHAL') :=1000;
V_VARIABLE ('SCOTT') :=2000;
V_VARIABLE ('TIGER') :=3000;
V_VARIABLE ('JOHN') :=4000;
NAME: = V_VARIABLE.FIRST;
WHILE NAME IS NOT NULL LOOP
DBMS_OUTPUT.PUT_LINE('NAME OF EMPLOYEE IS ' ||NAME||
AND SALARY IS '|| TO_CHAR(V_VARIABLE(NAME)));
NAME:=V_VARIABLE.NEXT(NAME);
END LOOP;
END;

Nested tables:A nested table is like a one-dimensional array with an arbitrary number of elements. However, there is a difference
between array and nested tables:An array has a specific number of elements but nested table does not have the same. The size of a nested
table can increase dynamically but we cannot increase the size of the array.
An array is always dense, it always has consecutive subscripts. A nested array is dense initially, but it can
become sparse when elements are deleted from it.
Syntax of the nested table:TYPE TYPE_NAME IS TABLE OF ELEMENT_TYPE [NOT NULL];
VARIABLE_NAME (TABLE_NAME) TYPE_NAME;
Above syntax looks similar to the index by table but if you see in the above syntax there is no index by clause.
Lets look at the example:DECLARE
TYPE REC_TAB IS TABLE OF VARCHAR2(10);
TYPE REC_TAB_1 IS TABLE OF INTEGER;
V_VARIABLE REC_TAB;
V_VARIABLE_1 REC_TAB_1;
V_VARIABLE_2 INTEGER;
BEGIN
V_VARIABLE := REC_TAB('CHANCHAL','JOHN','JON','SCOTT','TIGER');
V_VARIABLE_1 := REC_TAB_1(10,20,30,40,50);
V_VARIABLE_2 :=V_VARIABLE.COUNT;
FOR REC IN 1 .. V_VARIABLE_2 LOOP
DBMS_OUTPUT.PUT_LINE('NAME OF THE EMPLOYEE IS: '||V_VARIABLE(REC));
END LOOP;
END;

Varray:We can specify the maximum size and the type of elements stored in the varray.
Syntax of the varray is:CREATE OR REPLACE TYPE VARRAY_TYPE_NAME IS VARRAY (N) OF <ELEMENT_TYPE>;
Here:varray_type_name is a valid attribute name,
n is the number of elements (maximum) in the varray,
element_type is the data type of the elements of the array.

Varray best example can be our calendar. We have 365 days in a year so its fixed and we also know it. For that we
can use arrays like shown below:CREATE OR REPLACE TYPE VARRAY_TYPE_NAME IS VARRAY (365) OF NUMBER;

Dbms_output.put_line package:Dbms_output.put_line, oracle supplied package is use to show a message by programmer if they (programmer)
wants to show any output.
While using this package in named pl/sql block, you need to make sure that you have set the parameter
SERVEROUTPUT as ON. Like you can make serveroutput on like shown below:SET SERVEROUTPUT ON;
It will be helpful to you when you want to show any message to the users. Lets look at the below example to
understand this easily:Lets try to show any message on the screen by executing below program:-

It clearly showing procedure successfully completed but does not showing any values. Why? No error and no output
as well. Here serveroutput parameter comes to existence. If you want to see message you must set serveroutput on
then try to execute the same program:-

When we have set serveroutput on and executed same code it showing message. So always remember that
whenever you use pl/sql you must set serveroutput as on.

Pseudo columns:Pseudo columns are the system defined columns of oracle which we can access at a run time.
There are different types of pseudo column, out of which we will see top 10 mostly use pseudo columns:SYSDATE:1) SELECT SYSDATE FROM DUAL;
SYSTIMESTAMP:2) SELECT SYSTIMESTAMP FROM DUAL;
ROWNUM:3) SELECT ROWNUM FROM EMPLOYEE WHERE ROWNUM <=5;
ROWID:4) SELECT ROWID FROM EMPLOYEE WHERE ROWNUM<5;
NEXTVAL:CREATE SEQUENCE SEC_TEST;
5) SELECT SEC_TEST.NEXTVAL FROM DUAL;
6) SELECT SEC_TEST.CURRVAL FROM DUAL;
USER:7) SHOW USER
UID:8) SELECT UID FROM DUAL;
ORA_ROWSCN:9) SELECT ORA_ROWSCN FROM EMPLOYEE WHERE EMPNO=1;
10) In triggers we can call :OLD and :NEW as a pseudo column

Transactions:When we execute any DML statements and it shows statement executed successfully, but it does not mean your
transaction is committed. A successfully executed SQL statement and a committed transaction are not same.
Therefore whenever you execute the statement we need to make that statement commit to save the changes
permanently or we can rollback the changes made.
There are three transaction types:Commit
Rollback
Commit savepoint
Commit:By using commit transaction can be made permanent. Commit is very important while dealing which DML (insert,
update and delete) statements.
Most importantly, when you perform any DML operation and dont commit or rollback then for your particular session
(from which you have performed DML operations) you can see changes made but other users will be able to see the
changes until you permanently save the changes. For example, if you have inserted some values in a table and
without committing that insert you fired select statement then, it will be visible for you but not for others until you
commit that transaction.
Syntax of the commit is:COMMIT;
Lets look at the example:-

Rollback:Rollback will be undone the changes made. For example, if we have inserted some values in a table and rollback the
transaction then it will undone all the insert and the table will contain only the records which were present before
firing the insert statement.
Syntax of the rollback is:ROLLBACK;
Lets take an example:-

Above insert statement have not inserted any values in the employee table since we have undone the entire insert by
using rollback statement.

Savepoint:Savepoint is a kind of mark by using which we can split the DML statement for particular point of time.
Syntax of the savepoint is:SAVEPOINT SAVEPOINT_NAME;
Lets look at the example:-

Now check the employee table:-

Its showing ROBIN instate of ROBERT for the employee number 10.

In this book I have tried to cover the entire concepts of pl/sql which needs to be known by new person to oracle or the
person who is working as a pl/sql programmer for 2 or 3 years. If you think this book has more scope of improvement
then please let us know, we will try our best to improve the same.
My email id is: - chanchalwankhade@gmail.com

Potrebbero piacerti anche