Oracle Material
Oracle Material
De a r S t u de nt F ri en d s,
It Wa s A L on g J ou r ne y i n My C a re e r W it h Y o u r C om m unity , E ve n Th o u gh I Wa s A
St u de nt A t S om e St a ge i n My L if e, I Re a ll y St a rt e d Un de r st a n di ng T he C o nv en ie nc e s
A n d In- C o nv e n ie nce s o f The S tu d en t s L i f e On ly Af te r I St a rt e d T r ai ni n g T hem .
I Re al l y F e el E l at e d A n d En er g e t ic Whe n Y o u P e o p le B e ar Me Wi th S o Muc h P a t ie nc e
in Th e Cl a s se s, M y St u de nt s A re My Re a l In spi r a ti o n An d E ne r g y i n My Da y - T o- Da y
L if e. My St u de nt s K ee p My C o nsc i ou sne s s A liv e A nd Ma k e Me M o re Re s p o ns i bl e i n
Ev er y Ev e nt I E xec ut e Th ro ug h o ut My Day , A s T he y R e al ly Te ac h Me Ho w A H um an
Be in g Sh o u l d B e P a t ie nce A nd Sh o u l d Ge t R e a dy F o r T he H a rd sh i p s Fo r Ga i ni ng A nd
Ac hi ev i ng K n o w le d g e F o r S uc ce ss f u l Id e n tif ic at i o n A nd E x i st e nce i n Thi s C om peti tiv e
Wo r l d.
I R e a l ly S al ut e Wi t h Ho n o r A l l T ho se St ud e nt s Wh o Ga ve Me A Di a s T o S h a re My
E x p e ri e nce s A n d Kn o w le d ge Wit h Th em i n A l l The se Y e ar s i n My C a ree r, A s If Y o u
Nev e r H a d A Mi n d i n R e ce i vi n g T he K n o wl e d g e T h en I C ou l d n t H a ve Do ne A ny T h ing
Gr e at i n My L if e A s A F a c ul ty. My I d en tif ic at i o n A s A T e a c he r O R F ac ul ty i s Onl y
Be c au se of A ll T h o se S tu d en ts Wh o H a d T h e Re c ei v i n g He a rt of Ac c e pt i ng Me T o B e
T he i r T e ac he r. I S tr o n gl y Be l ie v e T h at A T e a che r C an E nj o y H i s S u cce ss Onl y W he n
T he re is A St u de n t Wh o i s in T he Mo o d of R e c eiv i n g A n d A c ce pt i n g The St a n d a r d s o f
K n o wl e d g e T he Te ac he r De liv e rs.
De a r F ri en d I Re a l l y F o r ge t The Wh ol e W orld of Eve nt s Whe n I F in d Y o u Si tt in g i n
F r on t of Me, J u st Wi t h A n E x pec t at i o n of B ui ld i n g Y o ur C ar ee r. T h a t C om m i tm e nt of
Y o urs Re a lly Driv e s Me De e p i n t o Em o ti o ns A s I S t art S h ari n g My K no wl e d g e Wi t h Y o u.
B ut Som et im e s it P i nc he s Me in My C o ns ci o us ne s s Wh e n I Fi n d F ew St ud e nt s Wh o
Re a ll y Don o t C a re T he ir C a ree r An d Le a ve T he S e nse s F or a F ai l ur e T hat T he y Wi ll
E nc o un te r J ust Be c aus e The y Do n o t C on ce nt r at e o n T h e Iss ue s Se ri o u s ly.
Ev er y Obj ec t T h a t i s o n Th i s E a rth C a n Ha v e A S t at e o f Suc c es s i n Th ei r P r oce ss of
L if e, Bu t T he B i g Dif f ere nc e is T he Dif f e re nc e of De nsi ty in T he S ucc ess Wh a t Th ey
Ac hi eve . T he L a w of N at u re S a ys T h a t S ucc e ss On ly F o ll o w s T h o se P e o p le W ho H av e A
T en d en cy T o Wa l k T o w a r ds it , S uc ce ss C a n not B e P a rt of Ou r L if e Whe n We Re al ly
Do n o t H av e A T h o u g ht of H av in g i t. I St r o n gl y B el ie v e T ha t Suc ce s s Ne v e r F ol l o ws A
H um an B e in g , H um an Be in g S h o ul d F ol l ow T he P at h I de nt if y i ng T he Pr o p er L a w s T hat
C a n M a k e Him R e ac h T he Suc c es s Wh a t H e Re a l ly E x p ec ts.
Ev er y J o u rn ey H as i t s Ow n Dis t a nce T o T r a ve l, B ut E ve ry St e p We T a ke i n Th e J o urn ey
Ma k e s Us Dec re a se T he Di st a nc e T o R e a ch T he F in a l P o i nt i n T he J o u rn ey , Th e
H a p p in es s We C a n E x p er ie nce Onc e We Re a c h Ou r De st in a ti o n in T he J o u rne y S ho ul d
Be Self E x pe ri en ce d Bu t C a nn o t B e E x p l a i ne d By Som eb o dy E l se . I H o p e Y o u A ll H av e
Al r e a d y C ro ss e d T he G re a t J ou rne y T o Ac hi e v e Y o ur S uc c e s s i n C a re e r B y T ra ve l i ng
F o r S i xt e e n Ye a rs, B ut M y Onl y Su g g es ti o n i s No t T o Ne g le c t T he L a st F e w Mo n t h s of
T he J o u rney Wh a t Y o u A re S pe n d in g i n Y o ur Da t a b a se C l a ss es, As T hi s is Y ou r F i na l
De st in y T o Ma k e Y o u Mo re C onf i de nt An d Suc c es sf ul i n Ke e pi n g Y o urs el f A he a d o f
Ot he r s i n T he Wo rl d of C om pet i ti o n.
Fi n a l ly I Wi ll Bl es s Yo u F r om T he B ot t o m of My H e a r t, Th a t Y o u Wi l l F i n d A
Wo n de rf ul Pl a ce in Y o ur C a re e r, W it h A ll Th e R i c h ne ss A n d Th e Gr ea t L i fe st yle Y o u
Dr e am ed B ef or e Y o u We re P a rt of My Or a c le S essi o n s
H o p in g T o B e Mo r e C l o se r in Y ou r Th o u g ht s A n d F an t a si es of Be in g S ucc e ssf ul i n Y o u r
C a ree r
Y o urs C or d i al l y
S at hi s h Y e l l an k i
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Representation of Data :
King
10
5500
10-02-06
Blake
10
4500
02-03-05
Clark
20
3500
15-05-04
Smith
30
1800
06-10-00
Miller
20
1100
22-12-03
Taylor
30
3500
24-09-98
Representation of Information:
Employees Information
Organization :
Date : 11 March 2015.
SkyEss Techno Solutions Place : Hyderabad.
Name
King
Blake
Clark
Smith
Miller
Taylor
Department Salary
10
5500
10
4500
20
3500
30
1800
20
1100
30
3500
DOJ
10-02-06
02-03-05
15-05-04
06-10-00
22-12-03
24-09-98
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Data Name.
Definitions.
Length OR Size.
Values Allowed.
Source of Data.
Ownership.
Value
Field Name
Type
Length Min
Empname
DeptNo
EmpSal
HireDate
Alpha Numeric
Integer
Decimal
Date
30
2
7
Max
90
10
1500 50000
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Should not Propagate and Store Data in New Files for Every New
Application.
Provide Easier and Faster Access to Data Even for Novice Users.
Hierarchical DBMS.
Network DBMS.
Relational DBMS.
Object-Oriented DBMS.
Object-Relational DBMS.
Data Warehousing.
Web-Enabled DBMS.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
1960
1970
1980
1990
2000
Flat File
Hierarchical
Network
Relational
Object-Oriented
Object-Relational
Data Warehousing
Web-Enabled
Active Development
Legacy Systems
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Logical Structures :
Physical Structures :
Database Should Have The Ability To Provide Access to External Tables for Files
Outside the Database, as if The Rows in the Files Were Rows in the Table.
The Course of Developing an Application Consists of
Relational Tables
External Tables
Partitioned Tables
Materialized Views
Temporary Tables
Clustered Tables
Dropped Tables
Note: A Database Application may Contain all the Above Categories of Tables
OR May Contain Few Depending on the Application Type.
As the Data in the Database Grows, The Speed and Performance of Database
Decreases.
The Following Indexes are Provided by Oracle Products for Speed of Database
B+ Tree Indexes.
Bitmap Indexes.
Partitioned Indexes.
Text Indexes.
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Domain Indexes.
Table Space :
The Table Space Builds the Bridge Between the Oracle Database and
the File System in which the Table's OR Index Data is Stored.
A Data File can be Part of One and Only One Table Space.
As Per Oracle 10g Minimum Two Table Spaces are Compulsory They are
System and SysAux Table Space, Both Used to Support Oracle Internal
Management.
The System Table Space Stores the Data Dictionary OR Their Base Tables,
Respectively.
In 10g a Big File Table Space can be Created, Which can grow to The Size
of Tera Bytes of Space on Disk.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SGA
SQL*Plus
(Logical Layer or Business Tier)
Dispatch
Queue
Communicate
Describe
Categorize
Specify
Investigate
Evolve
Analyze
Imitate
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Need Not Specify the Access Route to The Tables and Data.
It is highly efficient.
About Oracle 8
Deferrable Constrains.
and
Web
Based
Application
which
are
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
About Oracle 8i
The Internet File System (IFS) Combines The Power FOR Ease of Use a
File System.
End Users Can Easily Access Files and Folders in Oracle IFS via a Variety
of Protocols.
Logic
and
Serve
It is built During the Analysis Phase of the System Developing Life Cycle.
ER Model Separates The Information Required & The Business From the
Activities Performed.
ER Model Benefits
Entity
Attributes
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Relation
The Order of the Rows is Not Significant, While Retrieving the Data.
Column OR Attribute
Field
A Field Can Have Only One Value, OR May Not Have a Value At All.
Each Table Should Contain Data that Describes Exactly Only one Entity.
The Different Categories Into Which the SQL Statements Fall Are As
Follows.
SELECT Statement
INSERT Statement.
UPDATE Statement.
DELETE Statement.
CREATE Statement.
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
ALTER Statement.
DROP Statement.
RENAME Statement.
TRUNCATE statement.
COMMIT Statement.
ROLLBACK Statement.
SAVEPOINT Statement.
GRANT Statement.
REVOKE Statement.
The Current SQL Statement Replaces the Previous SQL Statement in the
Buffer.
The SQL Statement Can be Divided Into Different Lines Within the SQL
Buffer.
Only One Line i.e., The Current Line Can be Active at a Time in the SQL
Buffer.
At SQL Prompt, Editing is Possible Only in The Current SQL Buffer Line.
Start Run Type SQLPlus OR SQLPlusW in Open Box and Click OK.
In the Login Box OR Login Prompt Type the User Name and Password as
Supplied by the Administrator.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Tables in ORACLE 8 / 9 / 10
Tables can be Created at Any Time, Even When The Users are Using the
Database.
The Table Name Should Begin with a Letter and can be 1 30 Characters
Long.
Column_Name2 <DataType>(Width),
Column_NameN <DataType>(Width)
);
Note
No Two Columns in The Same Table Can Have the Same Name.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Data Types.
Literals.
Format Models.
NULLS.
Pseudo Columns.
Comments.
Database Objects.
The Data Type Associates a Fixed Set of Properties With that Value
Stored.
The Values of One Data Type are Different From Another Data Type.
The Data Type Defines The Domain of Values That Each Column Can
Contain.
ROWID DATATYPES.
This Data Type is Less Restrictive Than Other Data Types and has Very
Few Properties.
7 Bit ASCII(American
Interchange) Character Set.
Standard
Code
for
Information
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
CHAR
VARCHAR2
NCHAR
NVARCHAR2
If the Data is less Than the Original Specified Size, Blank Pads Are
Applied.
First Time Defined in ORACLE 9i, and Contains Unicode Data Only.
It Stores Zero, Positive and Negative Fixed and Floating Point Numbers.
to 9.99 * 10+125
NUMBER(P, S)
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Syntax
SELECT Lists
Restrictions
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The Default DATE Accepted by ORACLE DATE is The First Day of the
Current Month.
Syntax
TIMESTAMP[{FractionalSecondsPrecision}]
RAW and LONG RAW Data Types are Intended for Storage of Binary Data
OR BYTE Strings.
They are Mostly Used to Store Graphics, Sounds, Scanned Documents etc.
The ORACLE Converts the RAW & LONG RAW Data into HEXADECIMAL
Form.
* CLOB
* NCLOB
The LOB Data Types Can Store Large and Unstructured Data Like Text,
Image, Video and Spatial Data.
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
They are Provided with Full Transactional Support with Special Methods.
Both Fixed Width and Variable Width Character sets are Supported.
They are Provided With Full Transactional Support with Special Methods.
It Enables Access to Binary File LOBs Which are Stored in the File
Systems Outside ORACLE.
The BFILE Locator Maintains The Directory Alias and the Filename.
The Binary File LOBs do not Participate in Transactions and are Not
Recoverable.
The Rows Address Can be Queried Using the PSEUDO Column ROWID.
NUMBER(6),
VARCHAR2(30),
VARCHAR2(30),
DATE,
DATE,
NUMBER(7,2),
VARCHAR2(1)
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
ProdID
ProdPhoto
ProdGraphic
ProdDesc
);
NUMBER(6),
BLOB,
BFILE,
LONG
Relational Table.
An Object Table
Conventional INSERT.
In Conventional Insert Statement, ORACLE Reuses Free Space in the Table into
Which the Data in Being Inserted and Maintains Referential Integrity
Constraints.
In Direct - Path Insert, ORACLE Appends the Inserted Data after Existing Data
in the Table; the Free Space is not reused.
Syntax
SQL> INSERT INTO <Table_Name>(COL1, COL2, .. )
VALUES(VALUE1, VALUE2, ....);
In This Case the Values Should be Provided to All the Columns That Exist
Inside the Table.
The Order of Values Declared in the VALUES Clause Should Follow the
Original Order of the Columns in Table.
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The CHAR, VARCHAR and DATE Type Data should be declared in Single
Quotes.
In This Case the Order of Columns Declared in INSERT Need Not Be the
Same As That of the Original Table Order.
The Data Values in the VALUES Clause Should Match With that of INSERT
List.
The Columns Not Supplied With Data are Filled With NULL Values, Until
the NOT NULL Constraint is Declared.
It is Better To Specify Empty String Only FOR Character Strings and Dates.
The Targeted Column Should Not be Set With NOT NULL Constraint.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
M
);
The Function Returns the CURRENT DATE and TIME from the System Clock.
USER Function
The Single Ampersand Substitution Variable Applies for Each Instance When
The SQL Statement is Create OR Executed.
The Double Ampersand Substitution Variable Applies for All Instances Until
That SQL Statement is Existing.
Single Ampersand
Substitution Variable
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
VALUES
(
&StudNo,
&FirstName,
&LastName,
&DateofBirth,
25000
);
At the SQL Prompt Use the Save Command including the Required Path and
File Name.
Method 2
SAVE The SQL Statement in the Required Drive and Folder USING SQL
Extension.
SELECT Statement
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
TABLES.
OBJECT TABLES.
VIEWS.
OBJECT VIEWS.
MATERIALIZED VIEWS.
Prerequisites
The User Must Have the SELECT Privileges on the Specified Object.
The SELECT ANY TABLE Allows to Select the Data from Any Recognized
Object.
The SELECT Statement Can be Used to Select OR Retrieve Data From the
Object Using Any One of the Following Criteria.
SELECTION
PROJECTION
JOIN
SELECTION
PROJECTION
JOIN
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
DEPT
Column Name
Data Type
-------------------------------------Deptno
NUMBER
Dname
VARCHAR2
Loc
VARCHAR2
Table Name: Emp
Column Name
Data Type
-------------------------------------Empno
NUMBER
Ename
VARCHAR2
Deptno
NUMBER
Job
VARCHAR2
Sal
NUMBER
Comm
NUMBER
Mgr
NUMBER
HireDate
DATE
Table Name: SalGrade
Column Name
Data Type
-------------------------------------Hisal
NUMBER
Losal
NUMBER
Grade
NUMBER
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Illustrative Examples
SQL> SELECT *
FROM Emp;
EMPNO
-------7839
7698
7782
7566
7654
7499
7844
7900
7521
7902
7369
7788
7876
7934
ENAME
--------KING
BLAKE
CLARK
JONES
MARTIN
ALLEN
TURNER
JAMES
WARD
FORD
SMITH
SCOTT
ADAMS
MILLER
JOB
-------------PRESIDENT
MANAGER
MANAGER
MANAGER
SALESMAN
SALESMAN
SALESMAN
CLERK
SALESMAN
ANALYST
CLERK
ANALYST
CLERK
CLERK
MGR
--------7839
7839
7839
7698
7698
7698
7698
7698
7566
7902
7566
7788
7782
HIREDATE
------------17-NOV-81
01-MAY-81
09-JUN-81
02-APR-81
28-SEP-81
20-FEB-81
08-SEP-81
03-DEC-81
22-FEB-81
03-DEC-81
17-DEC-80
09-DEC-82
12-JAN-83
23-JAN-82
SAL
-----5000
2850
2450
2975
1250
1600
1500
950
1250
3000
800
3000
1100
1300
COMM
--------
1400
300
0
500
DEPTNO
---------10
30
10
20
30
30
30
30
30
20
20
20
20
10
14 rows selected.
SQL> SELECT *
FROM Dept;
DEPTNO
---------10
20
30
40
DNAME
---------------ACCOUNTING
RESEARCH
SALES
OPERATIONS
LOC
-------------NEW YORK
DALLAS
CHICAGO
BOSTON
LOSAL
---------700
1201
1401
2001
3001
HISAL
---------1200
1400
2000
3000
9999
SQL> SELECT *
FROM SalGrade;
GRADE
---------1
2
3
4
5
The SELECT Statement can be typed in one Line OR can be Split into Multiple
Lines.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The Column Names Can be Separated Onto Different Lines Within the SQL
BUFFER.
The Default Justification of The Data After it is Retrieved From the Table is..
The CHARACTER and DATE Column Headings can be Truncated, But Number
Columns Cannot be Truncated.
Perform Calculations.
Arithmetic Operators.
Arithmetic Operators
Addition
Subtraction
Multiply
Divide
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL*Plus Ignores Blank Spaces Before and After the Arithmetic Operator.
Operator Precedence
It is a Value Which is
Unavailable.
Unassigned.
Unknown.
Inapplicable.
If a Row Lacks the Data for a Particular Column, Than That Value is Said to
Be NULL OR to Containing NULL.
NVL Function
Syntax
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
NVL(Expr1, Expr2)
Expr1: It is the Source Value OR Expression That May Contain NULL.
Expr2: It is the Target Value for Converting NULL.
NVL Function Can be Used to Convert Any Data Type, The Return Value is
Always The Same as the Data Type of Expr1.
NVL(Comm, 0)
NVL(Hiredate, 01-JUN-99)
NVL(Job , Not Assigned)
SQL> SELECT Ename, Sal, Comm, Sal + NVL(Comm, 0)
FROM Emp;
SQL> SELECT Ename, Sal, Comm, (Sal * 12) + NVL(Comm, 0)
FROM Emp;
SQL> SELECT Ename, Sal, Comm, (Sal + 500) + NVL (Comm, 0)
FROM Emp;
Column Alias
The Column Alias is Specified in The SELECT List by Declaring the Alias After
the Column Name by Using the Space Separator.
The AS Keyword Can be Used Between The Column Name and Alias.
An Alias Effectively Renames the SELECT List Item for the Duration of that
Query Only.
An Alias Cannot be Used, Any Where in THE SELECT List for Operational
Purpose.
Table Alias
Table Alias Renames the Original Name of the Table in a SQL Statement.
Table Aliases are Very Important When Working With Self Joins.
The Table Alias is Applied for the Current SQL Statement Only.
SQL> SELECT
Empno
Numbers,
Ename
Name,
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Sal
Basic Salary,
Job
Designation
FROM Emp;
SQL> SELECT
Deptno AS Department ID,
Dname AS Department Name,
Loc
AS
Place
FROM Dept;
SQL> SELECT
Hisal
As
Maximum Range,
Losal
As
Minimum Range,
Grade
FROM Salgrade ;
Literals in ORACLE
A LITERAL and a CONSTANT Value are Synonyms to One Another and Refer
to a Fixed Data Value.
TEXT Literals.
INTEGER Literals.
NUMBER Literals.
INTERVAL Literals.
TEXT Literals
Expressions
Conditions
SQL Function
SQL Statements.
Example:
Employee Information
Managers Specification
Nnchar Literal
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
LITERAL Strings of Free-Form Text Can be Included in The Query as Per The
Requirement.
DATE and CHARACTER Literals Must be Enclosed Within the Single Quotation
Marks.
LITERAL Strings of Free-Form Text Can be Included in The Query as Per The
Requirement.
DATE and CHARACTER Literals Must be Enclosed Within the Single Quotation
Marks.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The DISTINCT Qualifier Affects all the Selected Columns, and Represents a
DISTINCT Combination of the Columns.
Filtering of Records
The Number of Rows Returned by a QUERY can be Limited Using the WHERE
Clause.
A WHERE Clause Contains a Condition That Must be Met and Should Directly
Follow the FROM Clause.
Syntax
SQL> SELECT [DISTINCT] [*] {Column1 [Alias] , .}
FROM Table_Name
[WHERE Condition(s)];
Values in Columns
Literal Values
Arithmetic Expressions
Functions
Column Name.
Comparison Operator.
CHARACTER Values are Case Sensitive and DATE Values are Format
Sensitive (DD-MON-YY)
The Comparison Operators are Used in Such Conditions That Compare One
Expression to Another.
Equality Operator =
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
OR
AND Operator
Truth Table
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
AND
TRUE
FALSE
NULL
TRUE
NULL
FALSE
NULL
NULL
NULL
OR Operator
Truth Table
OR
TRUE
FALSE
NULL
TRUE
FALSE
NULL
NULL
NULL
NULL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
NOT Operator
Truth Table
NOT
TRUE
FALSE
NULL
NULL
NOT
SQL> SELECT Ename, Sal, Job
FROM Emp
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
FROM Emp
WHERE (Deptno = 10 AND Job = MANAGER ) OR
(Deptno = 20 AND Sal >= 3000);
NOT Operator
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
AND Operator
OR Operator
SQL*Plus Operators
BETWEEN AND Operator
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
IN Operator
IS NULL Operator
LIKE Operator
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The WILD CARD Symbols Can be Used in Any Combination With Literal
Characters.
For Finding Exact Match For % and _ the ESCAPE Option Has to be Used
along with \ Symbol.
Ordering Information
The ORDER BY Clause Can be Used to SORT The Rows in the Required Order.
The ORDER BY Clause Should be the Last Clause in the Order of All Clauses
in The SELECT Statement.
Numbers 0 9
Strings A Z.
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
NULLS Last.
Syntax
SQL> SELECT [DISTINCT] [*] {Column1 [Alias] , .}
FROM Table_Name
[WHERE Condition(s)]
[ORDER BY {Column, Expr}[ASC/DESC]];
Aliases,
and
Can
Also
be
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL Functions are Built into ORACLE and are available for use in Various
Appropriate SQL Statements.
SQL Functions May Accept Arguments and Always Return a Value, and Can
be Nested.
These Functions Return a Single Result for Every Row of a Queried Table or
View.
These Functions Manipulate GROUPS of Rows and Return One Result Per
Group of Rows.
SELECT List.
CONNECT BY Clause.
CHARACTER Functions.
NUMBER Functions.
DATE Functions.
CONVERSION Functions.
They Can Accept One or More Arguments and Return One Value For Each
Row Returned By the Query.
Variable Value.
Column Name.
Expression.
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Syntax
FunctionName(Column/Expr, [Arg1, Arg2,])
May Return a Data Value of a Different Data Type Than That Referenced.
It Can be Nested.
Accept Character Input and Can Return Both Character and Number Values.
Number Functions
Date Functions
Operate on Values of Date Data Type and Can Return Both Date and
Number.
Conversion Function
General Functions
DECODE Operates on Any Data Type and Can Return Any Data Type.
Character Functions
They Return the Data Type VARCHAR2, Limited to a Length of 4000 Bytes.
If the Return Value Length Exceeds, Then the Return Value is Truncated,
Without an Error.
These Functions are Used to Convert the Casing of the Existing Character
from one Type to Another.
LOWER Function.
UPPER Function.
INITCAP Function.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Lower Function
The Return Value Has the Same Data Type as Argument CHAR Type (CHAR
or VARCHAR2)
Syntax: LOWER(Column/Expression)
SQL> SELECT
ORACLE CORPORATION String,
LOWER(ORACLE CORPORATION) Lower
FROM DUAL;
SQL> SELECT Ename, LOWER(MY INFORMATION) Lower
FROM Emp;
SQL> SELECT Ename, LOWER(Ename) Lower
FROM Emp
WHERE Job = MANAGER;
SQL> SELECT The ||Ename||s Designation is ||Job Employee
FROM Emp
WHERE LOWER(Job) = manager;
Upper Function
The Return Value Has the Same Data Type as the Argument CHAR.
Syntax: UPPER(Column/Expression)
SQL> SELECT
oracle corporation String,
UPPER(oracle corporation) Upper
FROM DUAL;
SQL> SELECT Ename, UPPER(my information) Upper
FROM DUAL;
SQL> SELECT Ename, LOWER(Ename), UPPER(Ename)
FROM Emp
WHERE Job = MANAGER;
SQL> SELECT Ename, Job
FROM Emp
WHERE Job = UPPER(Manager);
SQL> SELECT Ename, Job, Sal, Sal * 12
FROM Emp
WHERE Job = UPPER(LOWER(MANAGER));
SQL> SELECT The ||Ename||s Designation is ||LOWER(Job)
FROM Emp
WHERE Job = UPPER (manager)
ORDER BY Sal;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> SELECT
UPPER(The ||Ename||s Basic Salary is Rupees ||Sal)
FROM Emp
WHERE Job IN(MANAGER, UPPER(clerk))
ORDER BY Sal DESC;
INITCAP Function
It Converts the Alpha Character Values into Uppercase For The First Letter
of Each Word, Keeping all Other Letters in Lower Case.
by
White
Spaces
or
Characters
That
are
Not
Syntax: INITCAP(Column/Expression)
SQL> SELECT
oracle corporation String,
INITCAP(oracle corporation) InitCap
FROM DUAL;
SQL> SELECT
The Job Title for ||INITCAP(Ename)|| is ||LOWER(Job) FROM Emp;
SQL> SELECT
Ename, UPPER(Ename), LOWER(Ename), INITCAP(Ename)
FROM Emp;
SQL> SELECT Empno, INITCAP(Ename), Deptno
FROM Emp
WHERE Ename = UPPER(blake);
CONCAT Function
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> SELECT
CONCAT(CONCAT(INITCAP(Ename), is a ), Job) Job
FROM Emp
WHERE Deptno IN(10, 20);
Syntax: SUBSTR(Col/Expr, m, n)
Points to Remember
If m is 0 , it is Treated as 1.
SQL> SELECT
ABCDEFGH String,
SUBSTR(ABCDEFGH , 3, 4) SubString
FROM DUAL;
SQL> SELECT
ABCDEFGH String,
SUBSTR(ABCDEFGH , -5, 4) SubString
FROM DUAL;
SQL> SELECT
ABCDEFGH String,
SUBSTR(ABCDEFGH , 0 ,4) SubString
FROM DUAL;
SQL> SELECT
ABCDEFGH String,
SUBSTR(ABCDEFGH , 4) SubString
FROM DUAL;
SQL> SELECT
ABCDEFGH String,
SUBSTR(ABCDEFGH, 4, 0) SubString
FROM DUAL;
SQL> SELECT
ABCDEFGH String,
SUBSTR(ABCDEFGH, 4 , -2) SubString
FROM DUAL;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
LENGTH Function
If the String has Data Type CHAR, The Length Includes All Trailing Blanks.
Syntax: LENGTH(Column/Expression)
SQL> SELECT
ORACLE String,
LENGTH(ORACLE) Length
FROM DUAL;
SQL> SELECT
LENGTH (Ename)|| Characters exit in ||INITCAP(Ename) ||s Name.
AS Names and Lengths
FROM Emp;
SQL> SELECT INITCAP(Ename), Job
FROM Emp
WHERE LENGTH(Job) = 7;
SQL> SELECT INTICAP(Ename), Job
FROM Emp
WHERE
SUBSTR(Job, 4, LENGTH(SUBSTR(Job, 4, 3))) = AGE;
INSTRING Function
Searches for Column OR Expression Beginning With its mth Character For
The nth Occurrence of Char2, and Returns the Position of the Character in
Char1, That is the First Character of This Occurrence.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> SELECT
STRING String,
INSTR(STRING, R) InString
FROM DUAL;
SQL> SELECT
CORPORATE FOOR String,
INSTR(CORPORATE FOOR, OR, 3, 2) InString
FROM DUAL;
SQL> SELECT
CORPORATE FOOR String,
INSTR(CORPORATE FLOOR, OR, -3, 2) InString
FROM DUAL;
SQL> SELECT Job, INSTR(Job, A, 1, 2) Position
FROM Emp
WHERE Job = MANAGER;
SQL> SELECT Job, INSTR(Job, A, 2, 2) Position
FROM Emp
WHERE Job = MANAGER;
SQL> SELECT Job, INSTR(Job, A, 3, 2) Position
FROM Emp
WHERE Job = MANAGER;
SQL> SELECT Job, INSTR(Job, A, 2) Position
FROM Emp
WHERE Job = MANAGER;
LPAD Function
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
RPAD Function
LTRIM Function
All The Leftmost Characters That Appear in The SET are Removed.
RTRIM Function
All the Right Most Characters That Appear in The SET are Removed.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Syntax:
TRIM(LEADING/TRAILING/BOTH, Trimchar FROM TrimSource)
SQL> SELECT
MITHSS String,
TRIM(S FROM MITHSS) Trimmed
FROM DUAL;
SQL> SELECT
SSMITH String,
TRIM(S FROM SSMITH) Trimmed
FROM DUAL;
SQL> SELECT
SSMITHSS String,
TRIM(S FROM SSMITHSS) Trimmed
FROM DUAL;
SQL> SELECT
SSMITHSS String,
TRIM(TRAILING S FROM SSMITHSS) Trimmed
FROM DUAL;
SQL> SELECT
SSMITHSS String,
TRIM(LEADING S FROM SSMITHSS) Trimmed
FROM DUAL;
SQL> SELECT
SSMITHSS String,
TRIM(BOTH S FROM SSMITHSS) Trimmed
FROM DUAL;
REPLACE Function
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
TRANSLATE Function
If The Extra Characters Appear in CHAR, They are Removed From the Return
Value.
SQL> SELECT
Job, TRANSLATE(Job, P, )
FROM Emp
WHERE Job = PRESIDENT;
SQL> SELECT Job,
TRANSLATE(Job, MN, DM)
FROM Emp
WHERE Job = MANAGER;
SQL> SELECT Job,
TRANSLATE(Job, A, O)
FROM Emp
WHERE Job = SALESMAN;
CHR Function
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Syntax:
CHR(n)
CHR(n USING NCHAR_CS)
SQL> SELECT CHR(67)||CHR(65)||CHR(84) Sample
FROM DUAL;
SQL> SELECT
CHR(16705 Using NCHAR_CS)
FROM DUAL;
ASCII Function
Syntax:
ASCII(Char)
NUMBER Functions
ROUND Function
Syntax: ROUND(n, m)
m can be Negative, and Rounds off The Digits to The Left of The Decimal
Point.
m Must be an Integer.
TRUNCATE Function
Syntax: TRUNC(n, m)
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> SELECT
15.79 Num1,
TRUNC(15.79, 1) Truncated
FROM DUAL;
SQL> SELECT
15.79 Num1,
TRUNC(15.79, -1) Truncated
FROM DUAL;
SQL> SELECT
15.79 Num1,
TRUNC(45.923, 2) Truncated,
TRUNC(42.923) Truncated,
TRUNC(45.923, -1) Truncated
FROM DUAL;
CEIL Function
Syntax: CEIL(n)
FLOOR Function
Syntax: FLOOR(n)
SQL> SELECT
15.7 Num1,
FLOOR(15.7) Floor
FROM DUAL;
SQL> SELECT
14.27 Num1,
FLOOR(14.27) Floor,
FLOOR(14.2) Floor,
FLOOR(14) Floor
FROM DUAL;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
MODULUS Function
Syntax: MOD(m, n)
It Returns m if n is 0.
SQL> SELECT
MOD(11, 4) Modulus,
MOD(10, 2) Modulus
FROM DUAL;
POWER Function
Syntax: POWER(m, n)
SQL> SELECT
POWER(3, 2) Power,
POWER(-3, 2) Power
FROM DUAL;
SQL> SELECT
POWER(3, -2) Power,
POWER(-3, -2) Power
FROM DUAL;
SQL> SELECT
POWER(-3.5, -2) Power,
POWER(3, -2.5) Power
FROM DUAL;
SQL> SELECT
POWER(-3.5, 2.5) Power,
POWER(3.5, -2.5) Power
FROM DUAL;
SQL> SELECT
SQRT(25)
FROM DUAL;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
ABSOLUTE Function
Syntax: ABS(n)
SIGN Function
Syntax: SIGN(n)
If n < 0 , Returns 1
If n = 0 , Returns 0
If n > 0, Returns 1
The Default Display and Input Format for any Date is DD-MON-YY.
SYSDATE:
Date Arithmetic
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
DATE Functions
ADD_MONTHS Function
Syntax: ADD_MONTHS(D, n)
MONTHS_BETWEEN Function
Syntax: Months_Between(D1, D2)
If d1 and d2 are Either the Same Days of The Months or Both Last Days of
The Months, The Result is Always An Integer.
Next_Day Function
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
It Returns The Date of The First Week Day Named By CHAR, That is Later
Than the Date d.
The CHAR Must be a Day of The Week in the Sessions Date Language.
LAST_DAY Function
Syntax: LAST_DAY(D)
It Returns The Date of The Last Day of The Month That Contains D.
Mostly Used to Determine How Many Days Are Left in the Current Month .
Rounding of Dates
Syntax: ROUND(Date, Format)
Truncating Dates
Syntax: TRUNC(Date, Format)
Date is Truncated to the Nearest Date with the Time Portion of the Day
Truncated to the Specified Unit.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Conversion Functions
The Conversion Functions Convert a Value From One Data Type to Another.
The Assignment Succeeds if the Oracle Server Can Convert the Data Type of
The Value.
In Assignment Operation
VARCHAR2 / CHAR
NUMBER
VARCHAR2 / CHAR
DATE
NUMBER
VARCHAR2
DATE
VARCHAR2
In Expressions
VARCHAR2/ CHAR
Number
VARCHAR2 / CHAR
Date
SQL provides three functions to convert a value from one data type to
another.
TO_CHAR
To Character Conversion.
TO_DATE
To Date Conversion
TO_NUMBER
To Number Conversion.
TO_CHAR(Number Conversion)
TO_CHAR(Date Conversion)
TO_CHAR(Number Conversion)
Syntax: TO_CHAR(NUMBER , fmt, nlsparms)
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
TO_CHAR(Date Conversion)
Syntax: TO_CHAR(DATE, fmt, nlsparams)
Converts Date of DATE Data Type to a Value of VARCHAR2 Data Type in The
Format Specified.
The nlsparams Specifies the Language in Which Month and Day Names And
Abbreviations are Returned.
SQL> SELECT
1234,
TO_CHAR(1234 , 9.9EEEE),
TO_CHAR(1234, 9.99EEEE)
FROM DUAL;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
FROM Emp
WHERE Deptno = 20;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The Date Format Models Can be Used in The TO_CHAR Function to Translate
a DATE Value From Original Format to User Format.
For Input Format Models, Format Items Cannot Appear Twice, and Format
Items That Represent Similar Information Cannot be Combined.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Week Starts on The First Day of The Month and Ends on the Seventh Day.
Week 1 Starts on the First Day of the Year and Continues to the Seventh
Day in That Year.
Quarter Starting With the Month of January and Ending With Every Three
Months.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Returns the Hour of the Day in Twenty Four Hour Clock Mode.(0 23)
Minutes Indicator: MI
Seconds Indicator: SS
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
-, /, !, ., ;, :, text
Date Format Element Suffixes: TH OR SP
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Date Suffixes Are Valid Only on Output, Hence Cannot be Used to Insert a
Date Into the Database.
Format Exact: FX
It Specifies Exact Matching For The Character Argument And Date Format
Model.
TO_NUMBER Function
Syntax: TO_NUMBER(Char, fmt, nlsparam)
TO_DATE Function
Syntax: TO_DATE(Char, fmt, nlsparam)
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The RR Date Format Element Allows to Store The Date to The Previous as
Well as The Next Centuries.
Chart of Identification
Last Two Digits of The Year
Managed By Clock
0 To 49
50 To 99
0 To 49
50 To 99
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> SELECT
CONCAT(
CONCAT(Ename, is a ),
Job
) Designation
FROM Emp
WHERE Empno = 7900;
SQL> SELECT
TRUNC(
TO_DATE(27-OCT-92, DD-MON-YY),
YEAR
) New Year
FROM DUAL;
SQL> SELECT
TO_CHAR(
ADD_MONTHS(
LAST_DAY(Hiredate) , 5
), DD-MON-YYYY
) FIVE MONTHS
FROM Emp
WHERE Ename = MARTIN;
SQL> SELECT
MONTHS_BETWEEN(
TO_DATE(
02-02-1995, MM-DD-YYYY
),
TO_DATE(
01-01-1995, MM-DD-YYYY
)
) MONTHS
FROM DUAL;
SQL> SELECT NEXT_DAY(15-MAR-98, TUESDAY) Next Day
FROM DUAL;
SQL> SELECT Ename,
NVL(TO_CHAR(Comm), Not Applicable) Commission
FROM Emp
WHERE Deptno = 30;
SQL> SELECT
ROUND(
TO_DATE(27-OCT-92 , DD-MON-YY), YEAR
) New Year
FROM DUAL;
SQL> SELECT TO_CHAR(HireDate, MONTH DD, YYYY)
FROM Emp
WHERE Ename = BLAKE;
SQL> SELECT Ename,
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Spelling a Number
SQL> SELECT
TO_CHAR(
TO_DATE(&GiveNumber, J),
JSP
) Spelled Number
FROM DUAL;
Text Encryption
SQL> SELECT
SATISH KUMAR YELLANKI OrgName,
TRANSLATE(
SATISH KUMAR YELLANKI,
ABCDEFGHIJKLMNOPQRSTUVWXYZ,
1234567890!@#$%^&*()-=_+;,.
) EncryptedName
FROM DUAL;
Text Decryption
SQL> SELECT
(1)9(8.!-#1*.;5@@1$!9 EncryptedName,
TRANSLATE(
(1)9(8.!-#1*.;5@@1$!9,
1234567890!@#$%^&*()-=_+;,.
ABCDEFGHIJKLMNOPQRSTUVWXYZ,
) DecryptedName
FROM DUAL;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
These Functions Can Appear in SELECT Lists and HAVING Clauses Only.
These Functions Operate on Sets of Rows to Give One Result Per Group.
The Sets May Be The Whole Table or The Table Split Into Groups.
Average Function
Syntax: AVG(DISTINCT/ALL Col)
SUM Function
Syntax:
SUM(DISTINCT/ALL Col)
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
MAXIMUM Function
Syntax: MAX(DISTINCT/ALL Col)
MINIMUM Function
Syntax: MIN(DISTINCT/ALL Col)
VARIANCE Function
Syntax: VARIANCE(DISTINCT/ALL Col)
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
COUNT Function
Syntax: COUNT(*/DISTINCT/ALL Col)
It Can Be Used to Specify The Count of All Rows or Only Distinct Values of
Col.
The Group By Clause is used to decide the rows in a table into groups.
Syntax 1:
SELECT ColumnName1, ColumnName2,
FROM TableName
WHERE Condition(s)
GROUP BY ColumnName(s)
ORDER BY Column(s);
Syntax 2:
SELECT ColumnName, GRP_FUN(Column)
FROM TableName
WHERE Condition(s)
GROUP BY ColumnName(s)
ORDER BY Column(s);
Guidelines to Use GROUP BY Clause:
The Extra Non Group Functional Columns Should Be Declared in The GROUP
BY Clause.
Using WHERE Clause, Rows Can Be Pre Excluded Before Dividing Them Into
Groups.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The Column Applied Upon GROUP BY Clause Need Not be Part of SELECT list.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The Clause is Used to Filter Data That is Associated With Group Functions.
Syntax:
SELECT Column, Group_Function
FROM Table
[WHERE Condition(s)]
[GROUP BY Group_By_Expr]
[HAVING Group_Condition(s)]
[ORDER BY Column_Name/Alias];
Steps Performs By Having Clause:
Third The Groups That Match The Criteria in The HAVING Clause are
Displayed.
The HAVING Clause can Precede GROUP BY Clause, But it is More Logical to
Declare it After GROUP BY Clause.
GROUP BY Clause Can Be Used, Without a Group Function in The SELECT list.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
GROUP BY Deptno
HAVING MIN (Sal) < 1000;
SQL> SELECT Deptno, SUM(Sal)
FROM Emp
GROUP BY Deptno
HAVING COUNT(Deptno) > 3;
SQL> SELECT Deptno, AVG(Sal), SUM(Sal), MAX(Sal), MIN(Sal)
FROM Emp
GROUP BY Deptno
HAVING COUNT(*) > 3;
SQL> SELECT Deptno, AVG(Sal), SUM(Sal)
FROM Emp
GROUP BY Deptno
HAVING AVG ( Sal ) > 2500;
SQL> SELECT Deptno, Job, SUM(Sal), AVG(Sal)
FROM Emp
GROUP BY Deptno, Job
HAVING AVG(Sal) > 2500;
Miscellaneous Functions
GREATEST Function
Syntax: GREATEST(Expr1, Expr2, )
All Exprs After The First are Implicitly Converted to The Data Type of The
First Expr, Before The Comparison.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
LEAST Function
Syntax: LEAST(Expr1, Expr2, )
All Exprs After The First Are Implicitly Converted to The Data Type of The
First Expr Before the Comparison .
USER Function
Syntax: USER
It Returns the Current Oracle Users Name Within The VARCHAR2 Data Type.
UID Function
Syntax: UID
USERENV Function
Syntax: USERENV(Option)
LANGUAGE
Session .
TERMINAL
Terminal.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
VSIZE Function
Syntax: VSIZE(Expr)
SOUNDEX Function
Syntax: SOUNDEX(CHAR)
It Allows Comparison of Words That are Spelled Differently, But Sound Alike
in English.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
It is a State in Which All The Data Values Stored in The Data Base Are
Correct.
Enforcing Data Integrity Ensures The Quality of The Data in The Data Base.
Entity Integrity
Domain Integrity
Referential Integrity
Entity Integrity
Columns, or the
Illustration: 1
Student Name
Date of Birth
Date of
Admission
Course Name
Course Fee
Sampath
02-Jan-76
15-Jun-00
MCA
25000.00
Sampath
02-Jan-76
15-Jun-00
MBA
25000.00
Srinivas
02-Jan-76
15-Jun-00
MBA
25000.00
Srinivas
02-Jan-76
25-Aug-02
MBA
25000.00
Sampath
10-Dec-80
25-Aug-02
MCA
25000.00
Srinivas
02-Jan-76
25-Aug-02
M.Sc
15000.00
Illustration: 2
Student
Name
Date of Birth
Date of
Admission
Course
Name
Course Fee
Email ID
Sampath
02-Jan-76
15-Jun-00
MCA
25000.00
Sampath
02-Jan-76
15-Jun-00
MBA
25000.00
Srinivas
02-Jan-76
15-Jun-00
MBA
25000.00
Srinivas
02-Jan-76
25-Aug-02
MBA
25000.00
Sampath
10-Dec-80
25-Aug-02
MCA
25000.00
Srinivas
02-Jan-76
25-Aug-02
M.Sc
15000.00
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Illustration: 3
Student
ID
Student
Name
Date of
Birth
Date of
Admission
Course
Course Fee
Name
1000
Sampath
02-Jan-76
15-Jun-00
MCA
25000.00
1001
Sampath
02-Jan-76
15-Jun-00
MBA
25000.00
1002
Srinivas
02-Jan-76
15-Jun-00
MBA
25000.00
1003
Srinivas
02-Jan-76
25-Aug-02
MBA
25000.00
1004
Sampath
10-Dec-80
25-Aug-02
MCA
25000.00
1005
Srinivas
02-Jan-76
25-Aug-02
M.Sc
15000.00
Email ID
Domain Integrity
CHECK Constraint.
Illustration: 4
Student Student
ID
Name
Date of
Birth
Date of
Admission
Course
Name
Course
Fee
Email ID
[email protected]
1000
Sampath 02-Jan-76
15-Jun-00
MCA
25000
1001
SAMPATH
15-Jun-00
MBA
25000
1002
srinivas
02-Jan-76
15-Jun-00
MBA
25000
SRINIVAS 02-Jan-98
04-Aug-07
MBA
25000
25-Aug-02
MCA
25000
M.Sc
15000
1003
1004
sampath
1005
Srinivas
02-Jan-76
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Referential Integrity
Illustration: 5
Courses Information
Course
ID
Course
Name
Course
Fees
C001
MBA
25000
C002
MCA
25000
C003
M.Sc
15000
Students Information
Student
ID
Student
Name
Date of
Birth
Date of
Admission
Course
ID
Email ID
1000
Sampath
02-Jan-76
15-Jun-00
C002
1001
SAMPATH
15-Jun-00
C001
1002
srinivas
02-Jan-76
15-Jun-00
C001
1003
SRINIVAS
02-Jan-98
04-Aug-07
C001
1004
sampath
25-Aug-02
C002
1005
Srinivas
02-Jan-76
C003
It Allows To Define Specific Business Rules That Do Not Fall Into Any One of
The Other Integrity Categories.
These are Business Rules Which Can be Handled at Run Time, Usually
Designed Using Database Triggers in PL/SQL.
Can be Any Situation That Looks Abnormal to the Current Systems Process.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Constraints in Oracle
UNIQUE Constraint.
CHECK Constraint.
REF Constraint.
Declaration Style
Column Level:
Table Level:
Note: NOT NULL Constraint is The Only Constraint Which Should Be Declared
As INLINE Only.
With in a Single User No Two Constraints Can Have The Same Name.
USER_DEFINED OBJECTS.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Exceptions
NOT NULL, FOREIGN KEY, and REF Constraints Are Supported on a Column
of TYPE REF.
To Satisfy the Rule, Every Row in The Table Must Contain a Value For The
Column.
Restrictions:
Syntax
SQL> CREATE Table <Table_Name>
(
Column_Name1 <Data Type>(Width) NOT NULL,
Column_Name2 <Data Type>(Width)
CONSTRAINT ConsName NOT NULL,
Column_NameN <Data Type>(Width)
);
Illustration
SQL> CREATE TABLE Students
(
StudNo
NUMBER(6)
VARCHAR2(25)
VARCHAR2(25)
);
UNIQUE Constraint
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
To Satisfy a UNIQUE Constraint, No Two Rows in The Table Can Have The
Same Value For The UNIQUE Key.
Restrictions:
LOB, LONG, LONG RAW, VARRAY, NESTED TABLE, OBJECT, BFILE, REF,
TIMESTAMP WITH TIME ZONE .
We Cannot Specify a UNIQUE Key When Creating a Sub Table or Sub View in
An Inheritance Hierarchy.
The UNIQUE Key Can Be Specified Only For The Top Level (Root) Table or
View.
Syntax
SQL> CREATE Table <Table_Name>
(
Column_Name1 <Data Type>(Width) UNIQUE,
Column_Name2 <Data Type>(Width)
CONSTRAINT ConsName UNIQUE,
Column_NameN <Data Type>(Width)
);
Illustration: 1
Column Level Syntax
SQL> CREATE Table Promotions
(
Promo_ID
NUMBER(6)
VARCHAR2(20),
PromoCategory
VARCHAR2(15),
PromoCost
NUMBER(10, 2),
PromoBegDate
DATE,
PromoEndDate
DATE
);
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Illustration: 2
Table Level Syntax
SQL> CREATE Table Promotions
(
Promo_ID
NUMBER(6),
PromoName
VARCHAR2(20),
PromoCategory
VARCHAR2(15),
PromoCost
NUMBER(10, 2),
PromoBegDate
DATE,
PromoEndDate
DATE,
Illustration: 3
Composite UNIQUE Constraint Syntax
SQL> CREATE Table WareHouse
(
WareHouseID
NUMBER(6),
WareHouseName
VARCHAR2(30),
Area
NUMBER(4),
DockType
VARCHAR2(50),
WaterAccess
VARCHAR2(10),
RailAccess
VARCHAR2(10),
Parking
VARCHAR2(10),
Vclearance
NUMBER(4),
CONSTRAINT WareHouseUNQ
UNIQUE(WareHouseID,WareHouseName)
);
Illustration: 4
SQL> CREATE TABLE Students
(
StudID
NUMBER(6),
VARCHAR2(30),
DOB
DATE,
DOJ
DATE,
EmailID
VARCHAR2(50)
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Restrictions:
PRIMARY KEY Cannot Be Specified When Creating a Sub Table or Sub View
in An Inheritance Hierarchy.
The PRIMARY KEY Can be Specified Only For The Top Level (ROOT)TABLE or
VIEW.
Syntax
SQL> CREATE Table <Table_Name>
(
Column_Name1
<Data Type>(Width)
CONSTRAINT ColNamePK PRIMARY KEY,
Column_Name2
<Data Type>(Width),
Column_NameN
<Data Type>(Width)
);
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Illustration: 1
Column Level Syntax:
SQL> CREATE TABLE Locations
(
LocationID
NUMBER(4)
PostalCode
VARCHAR2(6)
VARCHAR2(30)
Illustration: 2
Table Level Syntax
SQL> CREATE TABLE Locations
(
LocationID
NUMBER(4),
StAddress
PostalCode
VARCHAR2(6)
VARCHAR2(30)
CustID
ProdID
Qty
SaleDate
SaleDesc
S001
C001
P001
250.00
01-Aug-07
Cash
S001
C001
P002
125.00
01-AUG-07
Cash
S002
C002
P003
50.00
01-Aug-07
Cash
S002
C002
P004
75.00
01-Aug-07
Credit
S002
C002
P010
225.00
01-Aug-07
Credit
S002
C002
P003
125.00
01-Aug-07
Cash
S003
C001
P005
200.00
01-Aug-07
Credit
S003
C001
P002
25.00
01-Aug-07
Cash
S003
C001
P015
354.00
01-Aug-07
Credit
S004
C003
P100
245.00
02-Aug-07
Cash
S005
C001
P002
125.00
03-Aug-07
Cash
S006
C002
P004
75.00
03-Aug-07
Cash
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Illustration: 2
SQL> CREATE TABLE SalesInfo
(
SaleID
NUMBER(6),
CustID
NUMBER(6),
ProdID
NUMBER(6),
Quantity
SaleDate
SaleDesc
CONSTRAINT ProdCustIDPK
PRIMARY KEY(SaleID, ProdID, CustID)
);
The TABLE or VIEW Containing The FOREIGN KEY is Called the Child Object.
The TABLE or VIEW Containing The REFERENCED KEY is Called the Parent
Object.
The FOREIGN KEY And The REFERENCED KEY Can Be in The Same TABLE or
VIEW.
Restrictions:
LOB, LONG, LONG RAW, VARRAY, NESTED TABLE, OBJECT, BFILE, REF,
TIMESTAMP WITH TIME ZONE.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
REFERENCES Clause:
Used When
When The Constraint is OUT OF LINE, We Must Specify The FOREIGN KEY,
Key Word.
ON DELETE Clause:
if We
Want
ORACLE to Remove
Entity OR Table
Column OR Attribute
Relation OR Association
Connecting Line
OR
Types of Relations:
Unary Relation.
Binary Relation.
Ternary Relation.
NAry Relation
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Binary Relation:
Ternary Relation:
Relation Cardinality:
One-TO-One.
1..1
1..* OR 1:M
One-TO-Many.
Relation State:
Mandatory State.
Optional State.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
One
Optional
Many
Types of Tables To Be Identified in Design Process
1. Pure Masters:
These are Tables Which Contain Only Primary Keys, And All The Remaining
Columns are Non Keys.
2. Master Details:
These are Tables Containing Their Own Primary Key and are Also Related To
Them Selves or Other Tables With Foreign Keys.
3. Pure Details:
These are Tables Which Contain Only Foreign Keys, Related To Other Table
or Tables Primary Key.
VARCHAR2(20)
VARCHAR2(20)
These Are Tables Which Can Contain Primary Key of Their Own As Well As
Foreign Keys Referring To Other Primary Masters or To Them Selves.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
NUMBER(6)
VARCHAR2(30)
VARCHAR2(30)
NUMBER(6)
DATE
NUMBER(7, 2),
DeptID
NUMBER(2)
CONSTRAINT DeptID_FK
REFERENCES Dept(Deptno) ON DELETE CASCADE
);
NUMBER(4)
VARCHAR2(20)
DATE
NUMBER(4)
VARCHAR2(20)
DATE
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
NUMBER(4)
CONSTRAINT SampIDRef1_FK
REFERENCES SampMaster1(SampID1),
SampIDRef2
NUMBER(4)
CONSTRAINT SampIDRef2_FK
REFERENCES SampMaster2(SampID2),
SampNameRef
VARCHAR2(20),
SampDateRef
DATE,
CONSTRAINT SampRef_Comp_PK
PRIMARY KEY(SampIDRef1, SampIDRef2)
);
CHECK Constraint
To Satisfy The Constraint, Each Row in The Table Must Make The Condition
Either TRUE or UNKNOWN.
ORACLE Does Not Verify That CHECK CONDITIONS Are Mutually Exclusive.
Restrictions
The Condition of a CHECK Constraint Can Refer To Any Column in The Same
Table, But It Cannot Refer to Columns of Other Tables.
A Single Column Can Have Multiple CHECK Constraints That Can Reference
The Column in The Definition.
The CHECK Constraints Can Be Defined At The Column Level or TABLE Level.
DEFAULT Option
The Option Prevents NULL Values From Entering The Columns, if a Row is
Inserted Without a Value For a Column.
The DEFAULT Expression Must Match The Data Type of the COLUMN.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Example
SQL> CREATE TABLE Dept
(
Deptno
NUMBER(2)
CONSTRAINT CHK_Deptno
CHECK(Deptno BETWEEN 10 AND 90),
Dname VARCHAR2(15) CONSTRAINT Chk_Dname_UP
CHECK(Dname = UPPER(Dname)) DISABLE ,
Loc
VARCHAR2(15)
NUMBER(4)
CONSTRAINT CHK_Ename
CHECK(Ename = UPPER(Ename)),
Job
VARCHAR2(30)
NUMBER(4),
HireDate
DATE
DEFAULT SYSDATE,
Sal
NUMBER(7, 2)
NUMBER(7, 2),
Deptno
NUMBER(2),
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Constraints Maintenance
Adding Constraints to a Table
A Constraint Can Be Added To a Table At Any Time After The Table Was
Created By Using ALTER TABLE Statement, Using ADD Clause.
Syntax
SQL> ALTER TABLE <TableName>
ADD
[CONSTRAINT <ConstraintName>]
CONS_TYPE(Column_Name);
Guidelines
A NOT NULL Can Be Added to Existing Column By Using The MODIFY Clause
of the ALTER TABLE Statement.
NOT NULL Can Be Defined Only When The Table Contains No Rows.
Example
SQL> ALTER TABLE Emp
ADD CONSTRAINT Emp_Mgr_FK
FOREIGN KEY(Mgr) REFERENCES Emp(Empno);
DROPPING Constraints
USER_CONSTRAINTS
The CASCADE Option of the DROP Clause Causes Any Dependent Constraints
Also To Be Dropped.
Syntax
SQL> ALTER TABLE <Table_Name>
DROP
PRIMARY KEY/UNIQUE(Column)/
CONSTRAINT ConstraintName[CASCADE];
Example
SQL> ALTER TABLE Dept
DROP PRIMARY KEY CASCADE;
SQL> ALTER TABLE Emp
DROP CONSTRAINT Emp_Mgr_FK;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
ENABLING Constraints
The ALTER TABLE Statement With The ENABLE Clause is Used for the
Purpose
Syntax
SQL> ALTER TABLE<TableName>
ENABLE CONSTRAINT<ConstraintName>;
Guidelines
The ENABLE Clause Can Be Used Both in CREATE TABLE As Well As ALTER
TABLE Statements.
Examples
SQL> ALTER TABLE Emp
ENABLE
CONSTRAINT Emp_Empno_FK;
VIEWING Constraints
CHECK
PRIMARY KEY
R
U
UNIQUE KEY
REFERENTIAL INTEGRITY
Example
SQL> SELECT
CONSTRAINT_NAME,
CONSTRAINT_TYPE,
SEARCH_CONDITION
FROM USER_CONSTRAINTS
WHERE TABLE_NAME = EMP;
The Names of The Columns That Are Involved in Constraints Can Be Known
By Querying The USER_CONS_COLUMNS Data Dictionary View.
Example
SQL> SELECT
CONSTRAINT_NAME,
COLUMN_NAME
FROM USER_CONS_COLUMNS
WHERE TABLE_NAME = EMP;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
JOINS
A Join is a Query That Combines Rows From Two or More Tables, Views, or
Materialized Views.
The Queries SELECT List Can Select Any Columns From Any of These Tables.
Within
The
Tables
Should
Qualify
All
SQL> SELECT
Empno, Ename, Dname, Loc
FROM Emp, Dept;
SQL> SELECT
Empno, Ename, Sal, Grade
FROM Emp, SalGrade;
SQL> SELECT
Empno, Ename, Dname, Loc, SalGrade
FROM Emp, Dept, SalGrade;
SQL> SELECT
Empno, Ename, Dept.Deptno, Dname, Loc
FROM Emp, Dept;
JOIN Condition
Many Join Queries Contain WHERE Clause, Which Compares Two Columns,
Each From a Different Table.
To Execute a Join
Oracle Combines Pairs of Rows, Each Containing One Row From Each
Table, For Which The JOIN Condition Evaluates to TRUE.
The Columns in The Join Conditions Need Not Be Part of The SELECT List.
The WHERE Clause of Join Query Can Also Contain Other Conditions That
Refer to Columns of Only One Table.
Oracle First Joins Two of The Tables Based on The Join Conditions
Comparing These Columns And Then Joins The Result To Another Join.
Table1
Join 01
Result 01
Table2
Join 02
Table3
Result 02
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The Oracle Optimizer Determines The Order in Which ORACLE Should Join
The Tables Based on
Given JOIN Condition(s).
INDEXES Upon The Tables.
STATISTICS For The Tables.
The LOB Columns Cannot Be Specified in The WHERE Clause, When The
WHERE Clause Contains Any JOINS.
Syntax
WHERE Table1.Column1 = Table2.Column2
Guidelines
When Writing a SELECT Statement That JOINS Tables, Precede The Column
Name With The Table Name For Clarity And Enhance Database ACCESS.
If The Same Column Name Appears in More Than One Table, The Column
Name Must Be Prefixed With The Table Name.
The Above Rule Does Not Apply, if The Table Contains a Concatenated
Primary Key.
It Combines Rows That Have Equivalent Values For The Specified Columns.
The Total Size of Columns in The Equi Join Condition in a Single Table May
Be Limited To The Size of a Data Block Minus Some Overhead.
The Names of The Column Names Should Be Qualified in The WHERE Clause,
With The Table Name To Avoid Ambiguity.
If There Are no Common Column Names Between The Two Tables, The
Qualification is Not Necessary But It is Better.
SQL> SELECT
Emp.Empno
Empno,
Emp.Ename
Ename,
Emp.Deptno
Deptno,
Dept.Deptno
Deptno,
Dept.Dname
Dname,
Dept.Loc
Loc
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> SELECT
Empno, Ename, Sal * 12 AnnSal, Emp.Deptno, Loc
FROM Emp, Dept
WHERE Emp.Deptno = Dept.Deptno;
A Table Alias Gives an Alternate Name For The Existing Queried Table.
Table Aliases Help in Keeping The SQL Code Smaller, Hence Using Less
Memory.
Guidelines:
If a Table Alias is Used For a Particular Table Name in The FROM Clause,
Then That Table Alias Must be Substituted For The Table Name Through Out
The SELECT Statement.
A Table Alias is Valid Only For The Current SELECT Statement Only.
Self Joins
The Same Table Appears Twice in The FROM Clause And is Followed By
Table Aliases.
The Table Aliases Must Qualify The Column Names in The Join Condition.
To Perform a Self Join, Oracle Combines And Returns Rows of The Table
That Satisfy The Join Condition .
Syntax
SQL> SELECT Columns
FROM Table1 T1, Table1 T2
WHERE T1.Column1 = T2.Column2
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Illustrations
SQL> SELECT
E1.Ename Employee Name,
E2. Ename Managers Name
FROM Emp E1, Emp E2
WHERE E1.Mgr = E2.Empno;
SQL> SELECT
E1.Ename||s Managers is||
E2.Ename Employees And Managers
FROM Emp E1, Emp E2
WHERE E1.Mgr = E2.Empno;
SQL> SELECT
E1.Ename||Works For||
E2.Ename Employees And Managers
FROM Emp E1, Emp E2
WHERE(E1.Mgr = E2.Empno) AND
E1.Job = CLERK;
Cartesian Products
The CARTESIAN PRODUCT is a Join Query, that Does Not Contains a Join
Condition.
During Cartesian Product Oracle Combines Each Row of One Table With Each
Row of The Other.
The Data in The Tables in Directly Not Related But Indirectly or Logically
Related Through Proper Values.
Outer Joins
An OUTER Join Returns All Rows That Satisfy The Join Condition And Also
Those Rows From One Table For Which No Rows From The Other Satisfy The
Join Condition.
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
To Perform An OUTER Join of Tables A and B and Returns All Rows From
A, Apply The Outer Join Operator (+) to All Columns of Table B.
For all Rows in A That Have no Matching Rows in B, Oracle Returns NULL
For Any Select List Expressions Containing Columns of B.
Syntax:
SQL> SELECT
Table1.Column, Table2.Column
FROM Table1, Table2
WHERE Table1.Column (+) = Table2.Column;
SQL> SELECT
Table1.Column, Table2.Column
FROM Table1, Table2
WHERE Table1.Column = Table2.Column(+);
The (+) Operator Can Appear in The Context of The Left Correlation in The
FROM Clause, and Can be Applied Only to a Column of a Table or View.
If A and B Are Joined by Multiple Join Conditions, We Must Use The (+)
Operator in All of These Conditions.
A Condition Cannot Compare Any Column Marked With The (+) Operator
With a Sub Query.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The Join is First Executed Upon The Two Most Relevant Tables And Then The
Result is Applied Upon the Third Table.
EName,
Dname,
E.Sal
ESal,
E.Grade
EGrade,
M.Sal
MSal,
SM.Grade
MGrade,
Categories of Joins
Oracle Proprietary Joins (8i And Prior)
Equi Join
Non-Equi Join
Outer Join
Self Join
Cross Joins
Natural Joins
Using Clause
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Natural Join
SQL> SELECT Ename, Deptno, Dname, Loc
FROM Emp NATURAL JOIN Dept
USING Clause
SQL> SELECT Ename, Deptno, Dname, Loc
FROM Emp JOIN Dept
USING(Deptno)
Inner Join
SQL> SELECT Ename, Dept.Deptno, Dname, Loc
FROM Emp JOIN Dept
ON Emp.Deptno = Dept.Deptno;
Self Join
SQL> SELECT
E.Ename Employee,
M.Ename Manager
FROM Emp E INNER JOIN Emp M
ON(E.MGR = M.Empno)
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
FULL Join
SQL> SELECT Ename, Dept.Deptno, Dname, Loc
FROM Emp FULL JOIN Dept
ON Dept.Deptno = Emp.Deptno
SQL> SELECT Ename, Dept.Deptno, Dname, Loc
FROM Emp FULL JOIN Dept
ON Emp.Deptno = Dept.Deptno
Some Complications
SQL> SELECT
E.Ename Employee,
M.Ename Manager
FROM Emp E LEFT OUTER JOIN Emp M
ON(E.MGR = M.Empno)
ORDER BY 2
SQL> SELECT E.Ename, M.Ename, Sal, Grade, D.Deptno, Dname
FROM Emp E INNER JOIN Dept D
ON E.Deptno = D.Deptno
INNER JOIN Emp M
ON E.Empno = M.MGR
INNER JOIN SalGrade S
ON E.Sal BETWEEN LoSal AND HiSal
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Oracle Imposes no Limit on The Number of Sub Query Levels in The FROM
Clause of The Top-Level Query.
Within The WHERE Clause Upto 255 Sub Queries Can be Nested.
Solve a Problem By Combining The Two Queries, Placing One Query Inside
The Other Query.
The Inner Query or The Sub Query Returns a Value That is Used By The
Outer Query Upon The Main Query.
They Are Practically Very Useful When We Need to SELECT ROWS From a
Table With a Condition That Depends on The Data in The Table Itself.
Syntax
SQL> SELECT SelectList
FROM TableName
WHERE ColumnName Operator (
SELECT SelectList
FROM TableName
);
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
These Queries Return Only One Row From The Inner SELECT Statement.
These Queries Return More Than One Row From The Inner SELECT
Statement.
These Queries Return More Than One Column From The Inner SELECT
Statement.
Guidelines To Follow
A Sub Query Must Appear on The Right Side of The Comparison Operator
Only.
Only One ORDER BY Clause Can Be Implemented For The Total SELECT
Statement.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The Data From The Main Query Can Be Displayed By Using a Group Function
in a Sub Query.
As a Group Function Returns a Single Row, The Query Passes Through The
Success State.
The Inner Sub Query Should Not Have a GROUP BY Clause in This Scenario.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The Oracle Server Executes The Sub Query, And The Results Are Returned
Into The HAVING Clause of the Main Query.
The Inner Query Need Not Use Any GROUP Functions in This Scenario.
The Sub Queries That Return More Than One Row Are Called as MULTIPLE
ROW SUB QUERIES.
by Sub Query.
FROM Emp
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
ANY Operator
SQL> SELECT Empno, Ename, Job
FROM Emp
WHERE Sal < ANY(SELECT Sal
FROM Emp
WHERE Job = CLERK
);
SQL> SELECT Empno, Ename, Job, Sal
FROM Emp
WHERE Sal < ANY(SELECT Sal
FROM Emp
WHERE
Deptno = 20 AND Job <> CLERK
);
Note: <ANY Means Less Than The Maximum Value in The List.
SQL> SELECT Empno, Ename, Job
FROM Emp
WHERE Sal >ANY(SELECT Sal
FROM Emp
WHERE Job = CLERK
);
Note: >ANY Means More Than The Minimum Value in The List.
SQL> SELECT Empno, Ename, Job
FROM Emp
WHERE Sal =ANY(SELECT Sal
FROM Emp
WHERE Job = CLERK
);
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
ALL Operator
SQL> SELECT Empno, Ename, Job, Sal
FROM Emp
WHERE Sal >ALL(SELECT AVG ( Sal )
FROM Emp
GROUP BY Deptno
);
Syntax
SQL> SELECT Column1, Column2,
FROM TableName
WHERE
(Column a, Column b ,) IN(SELECT Column a, Column b,
FROM TableName
WHERE Condition
);
The Non Pair Wise Comparison is Also Called Cross Product, We Can Use a
WHERE Clause With Multiple Conditions.
In Non Pair Wise Comparison, The Candidate Row Must Match The Multiple
Conditions in The WHERE Clause But The Values Are Compared Individually.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
If One of The Values Returned By The Inner Query is NULL Value, Then The
Entire Query Returns NO ROWS.
Whenever a NULL Could be Part of a Sub Query, it is Better Not to Use NOT
IN Operator As it is Equivalent to !=ALL Operator.
The Sub Query in The From Clause Defines a Data Source For That Particular
SELECT Statement And Only That SELECT Statement.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
FROM Emp
GROUP BY Deptno
) T2
WHERE T1.Deptno = T2.Deptno AND
Staff >= 5;
SQL> SELECT Deptno, SUM(Sal),
SUM(Sal)/Tot_Sal * 100 Salary%
FROM Emp, (SELECT SUM(Sal) Tot_Sal
FROM Emp
)
GROUP BY Deptno, Tot_Sal;
SQL> SELECT E.EmpCount, D.DeptCount
FROM (SELECT COUNT(*) EmpCount
FROM Emp
) E,
(SELECT COUNT(*) DeptCount
FROM Dept
) D;
SQL> SELECT E.EmpCount, D.DeptCount, S.GradeCnt,
E.EmpCount + D.DeptCount + S.GradeCnt TotalRecCnt
FROM (SELECT COUNT(*) EmpCount
FROM Emp
) E,
(SELECT COUNT(*) DeptCount
FROM Dept
) D,
(SELECT COUNT(*) GradeCnt
FROM SalGrade
)S
SQL> SELECT A.Deptno Department Number,
(A.NumEmp / B.TotalCount ) * 100 %Employees,
(A.SalSum / B.TotalSal ) * 100 %Salary
FROM (SELECT
Deptno,
COUNT(*) NumEmp,
SUM(Sal) SalSum
FROM Emp
GROUP BY Deptno
) A,
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Syntax
SQL> SELECT SelectList
FROM Table1 F_Alias1
WHERE Expr.Operator
(SELECT SelectList
FROM Table2 F_Alias2
WHERE F_Alias1.Column OPERATOR F_Alias2.Column
);
Steps Performed
Passes The Qualified Column Value to the Inner Queries WHERE Clause.
Then The Inner Query or Candidate Query is Executed, And The Result is
Passed To The Outer Queries WHERE Clause.
Depending on The Supplied Value The Condition is Qualified For The Specific
Record.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Hierarchical Queries Are Queries That Are Executed Upon Tables That
Contain Hierarchical Data.
START WITH
It Specifies The Root Rows of The Hierarchy.
CONNECT BY
WHERE
ORACLE Selects The ROOT ROW(s) of The Hierarchy, Which Satisfy The
Condition of The START WITH Clause.
Each Child Row Must Satisfy The Condition of The CONNECT BY Clause, With
Respect to One of The ROOT ROWS.
If The Query Contains a WHERE Clause, ORACLE Removes All Rows From
The Hierarchy That Do Not Satisfy The Condition of The WHERE Clause.
General Representation
Root Node
Child Nodes
7
1
2
1
Leaf Nodes
Restrictions
They Cannot Select Data From a View, Whose Query Performs a Join.
If ORDER BY Clause is Used, Then The Rows Are Returned As Per The
Specification in The ORDER BY Clause.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
CONNECT BY Clause.
If START WITH is Omitted, Oracle Uses All Rows in The Table As ROOT
Rows.
CONNECT By Clause
This Clause Specifies The Relationship Between Parent and Child Rows, in a
Hierarchical Query.
Within The Condition, Some Part of The Condition Must Use The PRIOR
Operator, Which Refers to The Parent Row.
The Clause Can Contain Other Conditions To Further Filter The Rows
Selected By The Query.
Child/Parent
Child/Leaf
Level 1
Child/Parent
Level 2
Child/Parent
Level 3
Child/Leaf
Level 4
Child/Parent
Child/Leaf
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Blake
(7698, 7839)
Jones
(7566, 7839)
Clark
(7782, 7839)
Adams
(7876, 7788)
Ford
(7902, 7566)
Miller
(7934, 7782)
Smith
(7369, 7902)
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
We Should Qualify a Column With This Operator, Then Oracle Returns The
Column Value Using Data From The ROOT Row.
Restriction
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SYS_CONNECT_BY_PATH Function
The Function Returns The Path of a Column Value From Root To Node, With
Column Values Separated By Char For Each Row Returned By CONNECT BY
Condition.
NOCYCLE Keyword
Cycles Are Not Allowed in a True Tree Structure. But Some Hierarchical Data
May Contain Cycles.
SIBLINGS Keyword
The Keyword is Valid Only When We Specify The Hierarchical Query Using
CONNECT BY Clause.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Pseudo Column
Pseudo Columns Behave Like a Table Column, But is Not Actually Stored in a
Table.
CURRVAL
NEXTVAL
LEVEL
ROWID
ROWNUM
These Pseudo Columns Are Applied Upon The SEQUENCE Schema Object.
Restrictions
A Sub Query.
Syntax
The SEQUENCE Values Are Often Used For PRIMARY KEYs and UNIQUE
KEYs.
SCHEMANAME.SEQUENCENAME.CURRVAL
SCHEMANAME.SEQUENCENAME.NEXTVAL
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SCHEMANAME.SEQUENCENAME.CURRVAL@DBLINK
SCHEMANAME.SEQUENCENAME.NEXTVAL@DBLINK
WHEN a SEQUENCE IS Created, We Can Define its INITIAL VALUE And The
INCREMENT Between Its Values.
The First Reference To The NEXTVAL Returns The SEQUENCES Initial Value.
Before The CURRVAL Can Be Used For a SEQUENCE in a Session, First The
SEQUENCE Should Be Incremented With NEXTVAL.
Creating Sequences
Purpose
Syntax
CREATE SEQUENCE SequenceName
INCREMENT BY Integer
START WITH Integer
MAXVAL Integer/NOMAXVALUE
MINVAL Integer/NOMINVALUE
CYCLE/NOCYCLE
CACHE Integer/NOCACHE
ORDER/NOORDER;
INCREMENT BY Clause
MINVALUE Clause
NOMINVALUE Clause
MAXVALUE Clause
NOMAXVAULE Clause
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
CYCLE Clause
NOCYCLE Clause
Specifies The SEQUENCE Cannot Generate More Values After The Targeted
Limit.
CACHE Clause
NOCACHE Clause
ORDER Clause
NO ORDER Clause
Note
If The Above Parameters Are Not Specified By Default
START WITH Will Be 1.
INCREMENT BY WILL BE POSITIVE 1.
SEQUENCE IS NOCYCLE.
The CACHE Value Will Be 20.
SEQUENCE IS ORDER Sequence.
Illustrations
SQL> CREATE TABLE Sample
(
SampID
NUMBER(4)
VARCHAR2(25),
SampDate
DATE
);
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Modifying a Sequence
Increment Value
Maximum Value.
Minimum Value
Cycle Option
Cache Option
Syntax
SQL> ALTER SEQUENCE SequenceName
[INCREMENT BY n]
[{MAXVALUE n/NOMAXVALUE}]
[{MINVALUE n/NOMINVALUE}]
[{CYCLE/NOCYCLE}]
[{CACHE n/NOCACHE}];
Illustration
SQL> ALTER SEQUENCE SampleSeq
MAXVALUE 10
CACHE
NOCYCLE;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Only The Future Sequence Numbers Are Affected By The ALTER SEQUENCE
Statement.
And Then
Confirming Sequences
All SEQUENCES That Have Been Created Are Documented in The Data
Dictionary.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
FROM Emp
START WITH Job = PRESIDENT
CONNECT BY PRIOR Empno = MGR;
SQL> SELECT
LPAD ( , 2 * (LEVEL 1))||Ename Org_Chart,
Empno, MGR, Job ,
Sal
FROM Emp
WHERE Job != ANALYST
START WITH Job = PRESIDENT
CONNECT BY PRIOR Empno = MGR;
SQL> SELECT
LPAD( , 2 * (LEVEL 1))||Ename Org_Chart,
Empno, MGR, Job, Sal
FROM Emp
START WITH Job = PRESIDENT
CONNECT BY PRIOR Empno = MGR AND
LEVEL <= 2;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
For Each Row Returned By a Query, The ROWNUM Pseudo Column Returns a
Number Indicating The Order in Which Oracle Selects The Rows From a Set
of Joined Rows or Non Joined Rows.
The First Row Selected Has a ROWNUM of 1, The Second Has 2. And So On
The ROWNUM Can Be Used To Limit The Number of Rows Returned By The
Query.
Conditions Testing For ROWNUM Values Greater Than a Positive Integer Are
Always FALSE.
Never Use ROWNUM And ORDER BY Clause Together As Oracle First Fetches
The Rows According to ROWNUM And Then Sort's The Found Rows.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> SELECT *
FROM (SELECT *
FROM Emp
ORDER BY Sal DESC
)
WHERE ROWNUM < 6; --Proper Way
This Pseudo Column Returns a ROWs Address For Each Row Stored in The
Database.
The Row Belongs To Which Row in The Data Block (First Row is 0)
The Rows in Different Tables That Are Stored Together in The Same Cluster
Can Have The Same ROWID.
The Date Type of The Values Belonging to The ROWID Are of ROWID Data
Type.
ROWID is The Fastest Means of Accessing a Single Row From Data Base.
A RowID Can Never Change During The Life Time of Its Row.
When a Row is DELETED, ORACLE May Reassign Its ROWID To a New Row
That is Inserted.
The ROWID Pseudo Column Can Be Used in SELECT and WHERE Clauses.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
CONNECT_BY_ISCYCLE
CONNECT_BY_ISLEAF
CONNECT_BY_ISCYCLE Pseudocolumn
CONNECT_BY_ISLEAF Pseudocolumn
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SET Operators
UNION Operator.
UNION ALL Operator.
INTERSECT Operator.
MINUS Operator.
SET Operators Can Combine Two or More Queries Into One Result.
The Result of Each SELECT Statement Can Be Treated As a Set, and SQL Set
Operations Can Be Applied on Those Sets To Arrive At a Final Result.
Set Operations Are Often Called Vertical Joins, As The Result Combines Data
From Two or More SELECTS Based on Columns Instead of Rows.
INTERSECT}
<component query>;
UNION
Combines The Results of Two SELECT Statements Into One Result Set, And
Then Eliminates Any Duplicate Rows From That Result Set.
UNION ALL
Combines The Results of Two SELECT Statements Into One Result Set
Including The Duplicates.
INTERSECT
Returns Only Those Rows That Are Returned By Each of Two SELECT
Statements.
MINUS
Takes The Result Set of One SELECT Statement, And Removes Those Rows
That Are Also Returned By a Second SELECT Statement.
Point of Concentration
The Queries Are All Executed Independently But Their Output is Merged.
The Result Sets of Both The Queries Must Have The Same Number of
Columns.
The Data Type of Each Column in The Second Result Set Must Match The
Data Type of Its Corresponding Column in The First Result Set.
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The Two SELECT Statements May Not Contain An ORDER BY Clause, The
Final Result of The Entire SET Operation Can Be Ordered.
The Columns Used For Ordering Must Be Defined Through The Column
Number.
Illustrations
SQL> SELECT Empno, Ename
FROM Emp
WHERE Deptno = 10
UNION
SELECT Empno, Ename
FROM Emp
WHERE Deptno = 30
ORDER BY 1;
SQL> SELECT Empno, Ename, Job
FROM Emp
WHERE Deptno = (SELECT Deptno
FROM Dept
WHERE Dname = SALES)
UNION
SELECT Empno, Ename, Job
FROM Emp
WHERE Deptno = (SELECT Deptno
FROM Dept
WHERE Dname = 'ACCOUNTING')
ORDER BY 1;
SQL> SELECT Empno, Ename
FROM Emp
WHERE Deptno = 10
UNION ALL
SELECT Empno, Ename
FROM Emp
WHERE Deptno = 30
ORDER BY 1;
SQL> SELECT Empno, Ename
FROM Emp
WHERE Deptno = 10
INTERSECT
SELECT Empno, Ename
FROM Emp
WHERE Deptno = 30
ORDER BY 1;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
MINUS
SELECT Empno, Ename
FROM Emp
WHERE Deptno = 30
ORDER BY 1;
SQL> SELECT Job
FROM Emp
WHERE Deptno = 20
UNION
SELECT Job
FROM Emp
WHERE Deptno = 30;
SQL> SELECT Job
FROM Emp
WHERE Deptno = 20
UNION ALL
SELECT Job
FROM Emp
WHERE Deptno = 30;
SQL> SELECT Job
FROM Emp
WHERE Deptno = 20
INTERSECT
SELECT Job
FROM Emp
WHERE Deptno = 30;
SQL> SELECT Job
FROM Emp
WHERE Deptno = 20
MINUS
SELECT Job
FROM Emp
WHERE Deptno = 10;
SQL> SELECT ROWNUM, Ename
FROM Emp
WHERE ROWNUM < 7
MINUS
SELECT ROWNUM, Ename
FROM Emp
WHERE ROWNUM < 6;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
View
The Tables Upon Which A View is Based Are Called As BASE TABLES.
LOBs
Object Types
Refs
Nested Tables
Varrays
Object View is A View of A User Defined Type, Where Each Row Contains
Objects, And Each Object With An Object Identifier.
Prerequisites
The Owner of The Schema Should Have SELECT, INSERT, UPDATE Or DELETE
Rows From All Tables OR Views on Which The View is Based.
Syntax
SQL> CREATE [OR REPLACE]
[{FORCE/NOFORCE}] VIEW
ViewName
[(AliasName[,AliasName...])]
AS SubQuery
[WITH{CHECK OPTION/READ ONLY}]
[CONSTRAINT ConstraintName];
OR REPLACE
FORCE
Specifies The View Has To Be Created Even If The Base Tables Dows Not
Exist.
NOFORCE
Specifies The View Should Not Be Created If The Base Table Does Not Exist,
Which is Default.
ALIAS_NAME
Specifies That Only Rows That Would Be Retrieved By The Subquery Can
Only Be INSERTED, UPDATED OR DELETED.
CONSTRAINT
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Specifies That Rows Must Only Be Read From The Base Tables.
Restrictions
If A View Has INSERTED Of Trigger, Then All Sub Views Created on It Must
Have INSTEAD OF Triggers, Even If The Views Are Inherently Updatable.
Types of Views
Simple Views
Complex Views
Simple Views:
Which Contains A Subquery That Retrieves Data From Only One Base Table.
Complex Views
Simple Views
SQL> CREATE VIEW Employees
AS
SELECT
Empno ID Number,
Ename Name,
Sal Basic Salary,
Job Designation
FROM Emp;
Complex Views
SQL> CREATE VIEW EmpInfo
AS
SELECT
E.Empno
EmployeeID,
E.Ename
Name,
D.Deptno
DepartmentID,
D.Dname
DepartmentName
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Retrieves The
USER_VIEWS.
VIEW
Definition
From
The
Data
Dictionary
Table
Once The View Has Been Created, We Can Query Upon The DATA
DICTIONARY Table Called USER_VIEWS To See The Name And Definition of
The View.
The Text of The SELECT Statement That Constitutes The VIEW is Stored in A
Long Column.
Modifying A View
The Assigned Column Aliases in The CREATE VIEW Clause, Are Listed in The
Same Order As The Columns in The Subquery.
When A VIEW is Being Created, We Can Specify The Names of The Columns,
That It Can Project, Along With The Views Definition.
The View in This Case Totally Hides The Original Names From The Base
Table.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Dropping A View
Dropping A View Has No Affect on The Tables Upon Which The View is
Created.
We Need DROP ANY VIEW Privilege To Remove The Views From Data
Dictionary.
Syntax
SQL> DROP VIEW ViewName;
Example
SQL> DROP VIEW InsertDept;
Inline Views
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Rules To Follow
Group Function.
A GROUP BY Clause.
Data Can Be Added Through A View, Unless It Contains Any of The Above
Rules And There Does Not Exist Not Null Columns, And Without Default
Value.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Many Times These Transactions Look Consistent But It is Not TRUE, Hence
Care Should Be Taken When Implementing Them.
To Ensure That DML on The View Stays Within The Domain of The VIEW We
Use The WITH CHECK Option Clause.
Using Views We Can Protect The Data Integrity, But The Use is Very Limited.
The WITH CHECK OPTION Clause Specifies That INSERTS, & UPDATES
Performed Through The VIEW Are Not Allowed To CREATE Rows, That The
VIEW Cannot SELECT.
By Adding The WITH READ ONLY Option We Can Ensure That No DML
Operations Are Executed Through VIEW.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
CONSTRAINT_STATE
Constraint Clauses
Deferrable And Not Deferrable Clauses
If We Omit This Clause While Creating The Table, Then The Default is NOT
DEFERRABLE.
INITIALLY Clause
VALIDATE OR NOVALIDATE
ENABLE Clause
ENABLE VALIDATE Specifies That All Old And New Data Also Complies With
The Constraint.
ENABLE NOVALIDATE
Ensures That All New DML Operations on The
Constrained Data Comply With The Constraint.
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
DISABLE Clause
DISABLE VALIDATE Disables The Constraint And Drops The Index on The
Constraint, But Keeps The Constraint Valid.
RELY Clause
RELY And NORELY Are Valid Only When We Are Modifying An Existing
Constraint.
NUMBER(2)
VARCHAR2(10)
CONSTRAINT MastNameCHK
CHECK(MastName = UPPER(MastName),
MastDate
DATE
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
NUMBER(2),
MastID
NUMBER(2),
DetailName
VARCHAR2(10)
CONSTRAINT DetailNameCHK
CHECK(DetailName = UPPER(DetailName)),
DetailDate
DATE
View Constraint
Only UNIQUE, PRIMARY KEY And FOREIGN KEY Constraints Can Be Specified
on Views.
The RELY And NO RELY Key Words Will Instruct The Oracle Server When The
View Constraint Should Be Enforced.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
It Is A Schema Object Which Contains An Entry For Each Value That Appears
In The Indexed Column(s) Of The Table Or Cluster.
Types of Indexes
Normal Indexes
Bitmap Indexes
Partitioned Indexes:
They Contain Partitions Containing An Entry For Each Value That Appears In
The Indexed Columns of The Table.
Domain Indexes
Pre Requisites
For FUCTION Based Indexes, The Function Used For Indexing Must Be
Marked As Deterministic.
Restrictions
If The TABLE is TEMPORARY TABLE, Then INDEX is Also Temporary With The
Same Scope, As That of The Table.
Syntax
SQL> CREATE {[UNIQUE]/[BITMAP]}
INDEX IndexName
ON
TableName(ColumnName [,ColumnName..])
TABLESPACE TableSpaceName;
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
These Indexes Are Generally Created Using The Algorithm of B-Tree Index.
Specify UNIQUE To Indicate That The Value of The Column OR Columns Upon
Which The INDEX is Based Must Be UNIQUE.
Restrictions
These Indexes Are Used To Tune Queries That Use Non Selective Columns in
Their Limiting Conditions
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Restrictions
Start ROWID
End ROWID
Bit Pattern
10
AAANsYAAEAAABSGAAA
AAANsYAAEAAABSGAAN
10100000000001
20
AAANsYAAEAAABSGAAA
AAANsYAAEAAABSGAAN
00010000011110
30
AAANsYAAEAAABSGAAA
AAANsYAAEAAABSGAAN
01001111100000
Each Row in The Table Being Indexed Adds Only One Bit to The Size of The
Bitmap Pattern Column For The Bitmap Index.
The INDEX Expressions Are Built From Table Columns, Containing SQL
Functions OR User Defined Functions.
To Ensure That Oracle Uses The INDEX Rather Than Performing A Full Table
Scan, We Should Be Sure That The Value of The Function is NOT NULL in The
Subsequent Queries.
The Function Based Indexes Are Used Only When The Query Statement is
Executed Through The Specified Function.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Automatic.
Manual.
Specifications of An INDEX
INDEX Reduces The Disk I/O By Using Rapid Path Access Method To Locate
The Data Quickly.
Indexs Can Be Created OR Dropped At Any Time And Have No Effect on The
Base Tables OR Other Indexes.
On One Table More Than One Index Can Be Created, But This Does Not Mean
That, More The Indexes, Lead To More Faster Performance.
Each DML Operation That is Committed on A Table With Index, Means That
The Index Must Be Updated.
Dropping An Index
Syntax
SQL> DROP INDEX INDEX_NAME;
When To Create An Index
The Table is Large And Most Queries Are Expected To Retrieve Less Than 2
To 4 % of The Rows.
The
Column
That
USER_IND_COLUMNS.
Are
Involved
in
An
Index
By
Querying
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Database Security
GRANT Command
Syntax
SQL> GRANT <PrivilageName1>, <PrivilageName2>,
ON <ObjectName>
TO <UserName>;
GRANT Command Can Be issued Not Only on TABLE OBJECT, But Also on
VIEWS, SYNONYMS, INDEXES, SEQUENCES Etc.
REVOKE Command
Syntax
SQL> REVOKE <PrivilegeName1>, <PrivilegeName2>,
ON <ObjectName>
FROM <UserName>;
Types of Privileges
System Privileges
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Object Privileges
The Schema Object That Stores The Information About The Privileges
Granted is USER_TAB_PRIVS_MADE
GRANTEE
TABLE_NAME
GRANTOR
PRIVILEGE
GRANTABLE
HIERARCHY
SQL> SELECT
GRANTEE, TABLE_NAME "Table", GRANTOR, PRIVILEGE
FROM USER_TAB_PRIVS_MADE;
The Schema Object That Stores The Information About The PRIVILEGES That
Are Received is USER_TAB_PRIVS_RECD.
OWNER
TABLE_NAME
GRANTOR
PRIVILEGE
GRANTABLE
HIERARCHY
SQL> SELECT
OWNER, TABLE_NAME "Table", GRANTOR, PRIVILEGE
FROM USER_TAB_PRIVS_RECD;
Once A Particular USER Has Been Granted An Object Privilege, The Specific
USER Can Perform The Tasks As Granted By The Privilege.
Steps To Be Performed
Connect To The Required User Using The USER Name and PASSWORD.
SQL> SELECT *
FROM SCOTT.EMP;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Advantages
When You Add OR Delete A Privilege From A Role, All Users And Roles
Assigned That ROLE Automatically Receive OR Lose Those Privileges.
ROLEs Creation
Role Creation
Syntax
SQL> CREATE ROLE <RoleName>
[IDENTIFIED BY <Password>];
SQL> CREATE ROLE Sales_Manger
IDENTIFIED BY SalesAudit;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
USERNAME
GRANTED_ROLE
ADMIN_OPTION
DEFAULT_ROLE
OS_GRANTED
ROLE
PRIVILEGE
ADMIN_OPTION
ROLE
COLUMN_NAME
OWNER
PRIVILEGE
TABLE_NAME
GRANTABLE
Revoking a ROLE
SQL> REVOKE Sales_Manager
FROM SCOTT;
Dropping A ROLE
Syntax
DROP ROLE <RoleName>;
SQL> DROP ROLE Sales_Manager;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
By Using A Synonym, We Can Avoid The Entry of The SCHEMA Name, When
Referencing Upon OBJECTS That Belong To Other SCHEMA.
Syntax
SQL> CREATE [PUBLIC] SYNONYM <SynonymName>
FOR <SchemaName>. <ObjectName>;
Illustration
SQL> CREATE SYNONYM EmpInfo
FOR SCOTT.Emp;
SYNONYM Types
PRIVATE SYNONYM
PUBLIC SYNONYM
Dropping A Synonym
Syntax
DROP [PUBLIC] SYNONYM <SynonymName>;
Illustration
SQL> DROP SYNONYM EmpInfo;
SQL> DROP PUBLIC SYNONYM EmpInfo;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Some Features For Query Processing in ORACLE Include The Use Of ONLINE
ANALYTICAL PROCESSING(OLAP) Upon The Data Base.
OLAP Features Are Useful For Data Warehousing And Data Mart Applications.
TOP_N QUERIES.
GROUP BY.
CUBE.
ROLLUP.
ROLLUP Option
Syntax
GROUP BY ROLLUP ( Column1, Column2,..)
Illustrations
SQL> SELECT Deptno, SUM(SAL)
FROM Emp
GROUP BY ROLLUP(Deptno);
SQL> SELECT Job, SUM(Sal)
FROM Emp
GROUP BY ROLLUP(Job);
SQL> SELECT Job, AVG(Sal)
FROM Emp
GROUP BY ROLLUP(Job);
When Multiple Columns Are Passed To ROLLUP, The ROLLUP, Groups The
Rows Into Blocks With The Same Column Values.
NULL Values in The Output Of ROLLUP Operations Typically Mean That The
Row Contains Subtotal Or Grant Total Information.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
CUBE Option
Cube Allows To Take A Specified Set of Grouping Columns And Crate Sub
Totals For All Possible Combinations of Them.
The Implementation
Tabulation.
Cross
DECODE Function
We Can Pass A Variable Number Of Values Into The Call Of The DECODE()
Function.
The First Item is Always The Name Of The Column That Need To Be Decoded.
Syntax
SQL> SELECT DECODE(ColumnName,
Value 1, Substitute1,
Value 2, Substitute2,
ReturnDefault)
FROM TableName;
The Function Has No Restriction on The INPUT And OUTPUT Data Type.
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The Function Can Work For only an Analysis That Considers an Equality
Operator in The Logical Comparision.
SQL> SELECT
DECODE(GROUPING(Deptno),
1, All Departments,
Deptno) Departments,
SUM(Sal)
FROM Emp
GROUP BY ROLLUP(Deptno);
SQL> SELECT
DECODE(GROUPING(Job),
1, All Designations,
Job) Designations , SUM(Sal)
FROM Emp
GROUP BY ROLLUP(Job);
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
They Work With Equality Comparison Only, Almost All Similar To DECODE.
It Has A Selector Which Associates To The Compared Value Either From The
Column or Constant.
The Value in The Selector is Used For Comparison With The Expressions
Used in The WHEN Clause.
Syntax
SQL> CASE Search_Expr
WHEN Expr 1 THEN Result 1
WHEN Expr 2 THEN Result 2
ELSE Default_Result
END
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Illustration
SQL> SELECT Ename, Deptno,
CASE Deptno
WHEN 10 THEN ACCOUNTS
WHEN 20 THEN RESEARCH
WHEN 30 THEN SALES
WHEN 40 THEN OPERATIONS
ELSE NOT FOUND
END
FROM Emp;
Syntax
SQL> CASE
WHEN Condition 1 THEN Result 1
WHEN Condition 2 THEN Result 2
WHEN Condition n THEN Resultn
ELSE DefaultResult
END
Illustration
SQL> SELECT Ename, Deptno,
CASE
WHEN Deptno = 10 THEN ACCOUNTING
WHEN Deptno = 20 THEN RESEARCH
WHEN Deptno = 30 THEN SALES
WHEN Deptno = 40 THEN OPERATIONS
ELSE Not Specified
END
FROM Emp;
SQL> SELECT Ename, Sal,
CASE
WHEN Sal >= 800 AND Sal <= 2000 THEN LOWEST PAY
WHEN Sal >= 2001 AND Sal <= 4000 THEN MODERATE PAY
ELSE HIGH PAY
END
FROM Emp;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Materialized Views
They Are Used To Increase The Speed of Queries on Very Large Scale
Databases.
Query Rewrite
Queries Are Then Directed To The Materialized View And Not To The
Underlying Detail Tables OR Views.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
GROUPING_ID() Function
The Function Accepts One OR More Columns And Returns The Decimal
Equivalent of The GROUPING BIT VECTOR.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Top N Queries.
Standard Query
The Group of Rows Are Called As WINDOW And is Defined By The Analytic
Clause.
The Window Define The Range of Rows Used To Perform The Calculation For
The Current Row.
All JOINS, WHERE Clause, GROUP BY, And HAVING Clauses Are Completed
Before The Analytic Functions Are Processed.
Analytic Functions Can Appear Only in The SELECT List OR ORDER BY Clause.
Syntax
AnalyticFunction(Arg 1, Arg2, Ar3)
OVER(Partition Clause
ORDER BY Clause
Windowing Clause)
The Analytic Functions Are Applied For Each Group Independently, And They
Are Reset For Each Group.
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The ORDER BY Clause Specifies How Data is Stored Within Each GROUP
(Partition).
Window Functions
Reporting Functions
Enable To Calculate The Rank And Percentile That A New Row Would Have If
A Value is Inserted Into A Table.
Normal Ranking
SQL> SELECT EName, Deptno, Sal,
RANK()
OVER(ORDER BY Sal) EmpRank
FROM Emp
GROUP BY Deptno, EName, Sal ORDER By Emprank;
SQL> SELECT
DENSE_RANK()
OVER(ORDER BY Sal DESC) EmpRank
FROM Emp
GROUP BY Deptno, EName, Sal
ORDER BY EmpRank;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
TOP Sal
Emp
Applying Windows
Row WINDOW
SQL> SELECT DeptNo, Ename, Sal,
SUM(SAL)
OVER(PARTITION BY DeptNo
ORDER BY EName
ROWS 2 PRECEDING) Sliding Total
FROM Emp
ORDER BY DeptNo, EName;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Range WINDOW
Range Units Are Not Valid if Data Type is Other Than Number OR Dates.
Can
Either
Be
Numeric
Comparisons
OR
Date
Lag Provides Access To More Than One Row of A Table At The Same Time
Without The Use of SELF JOIN.
The Optional Default Value is Returned if The Offset Goes Beyond The Scope
of The Window.
Syntax
LAG(ValueExpr(, Offset)(, DEFAULT))
OVER((Query-Partition-Clause)
ORDER BY CLAUSE)
LEAD Function
LEAD Provides Access To More Than One Row of A Table At The Same Time
Without The Use of A SELF JOIN.
Syntax
LEAD(ValueExpr(, Offset)(, Default))
OVER((Query-Partition_Clause)
ORDER BY Clause)
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Illustration
SQL> SELECT Ename, HireDate, Sal,
LAG(Sal, 1, 0)
OVER(ORDER BY HireDate) PreSal
FROM Emp;
SQL> SELECT Ename, HireDate, Sal,
LEAD(Sal, 1, 0)
OVER(ORDER BY HireDate) NextSal
FROM Emp;
FIRST_VALUE Function
If The First Value in The Set is NULL, Then The Function Returns NULL
Unless IGNORE NULLS is Specified.
Syntax
FIRST_VALUE(EXPR IGNORE NULLS)
OVER(Analytic_Clause )
LAST_VALUE Function
If The Last Value in The Set is NULL, Then The Function Returns NULL Unless
IGNORE NULLS is Specified.
Syntax
LAST_VALUE(EXPR IGNORE NULLS)
OVER(Analytic_Clause )
Illustration
SQL> SELECT Ename, Deptno, Sal,
FIRST_VALUE(Ename)
OVER(PARTITION BY DeptNo
ORDER BY Sal DESC) Max_Sal_Name
FROM
Emp
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
ROW_NUMBER Function
Syntax
ROW_NUMBER()
OVER([Query_Partition_Clause]
ORDER_BY_Clause )
SQL> SELECT
ROW_NUMBER()
OVER(PARTITION BY Deptno
ORDER BY Sal DESC NULLS LAST) RowNo,
Ename, Sal, Deptno,
FROM Emp;
A CROSSTAB Query Can Be Used To Get A Result With Rows And Columns in
A Matrix Form.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
INTEGER
VARCHAR2(10)
INTEGER
INTEGER
CONSTRAINT ItemTypeIDFK
REFERENCES ItemTypes(ItemTypeID),
ItemName
VARCHAR2(10)
VARCHAR2(100),
Price
NUMBER(5, 2)
);
SQL> CREATE TABLE Divisions
(
DivID
CHAR(3)
VARCHAR2(15)
CHAR(3)
VARCHAR2(20)
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
INTEGER
CHAR(3)
CHAR(3)
VARCHAR2(10)
VARCHAR2(10)
NUMBER(6, 0)
);
SQL> CREATE TABLE AllSales
(
Year
Month
ItemTypeID
REFERENCES ItemTypes(ItemTypeID),
EmpID
INTEGER
NUMBER(8, 2),
CONSTRAINT AllSalesPk
PRIMARY KEY (Year, Month, ItemTypeID, EmpID)
);
Insert Sample Data Into Itemtypes Table
SQL> INSERT INTO ItemTypes (ItemTypeID, ItemTName)
VALUES (1, 'Book');
SQL> INSERT INTO ItemTypes (ItemTypeID, ItemTName)
VALUES (2, 'Video');
SQL> INSERT INTO ItemTypes (ItemTypeID, ItemTName)
VALUES (3, 'DVD');
SQL> INSERT INTO ItemTypes (ItemTypeID, ItemTname)
VALUES (4, 'CD');
SQL> INSERT INTO ItemTypes (ItemTypeID, ItemTname)
VALUES (5, 'Magazine');
SQL> COMMIT;
Insert Sample Data Into Products Table
SQL> INSERT INTO
Items (ItemID, ItemTypeID, itemName, Description, Price)
VALUES
(1, 1, 'Modern Science', 'A Desc of modern science', 19.95);
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> COMMIT;
Insert Sample Data Into Divisions Table
SQL> INSERT INTO Divisions(DivID, DivName)
VALUES('SAL', 'Sales');
SQL> INSERT INTO Divisions(DivID, DivName)
VALUES ('OPE', 'Operations');
SQL> INSERT INTO Divisions(DivID, DivName)
VALUES ('SUP', 'Support');
SQL> INSERT INTO Divisions(DivID, DivName)
VALUES ('BUS', 'Business');
SQL> COMMIT;
Insert Sample Data Into Jobs Table
SQL> INSERT INTO JobMaster(JobID, JobName)
VALUES ('WOR', 'Worker');
SQL> INSERT INTO JobMaster(JobID, JobName)
VALUES ('MGR', 'Manager');
SQL> INSERT INTO JobMaster(JobID, JobName)
VALUES ('ENG', 'Engineer');
SQL> INSERT INTO JobMaster(JobID, JobName)
VALUES ('TEC', 'Technologist');
SQL> INSERT INTO JobMaster(JobID, JobName)
VALUES ('PRE', 'President');
SQL> COMMIT;
Insert Sample Data Into Empstores Table
SQL> INSERT INTO
EmpStores
(EmpID, DivID, JobID, FirstName, LastName, Sal)
VALUES (1, 'BUS', 'PRE', 'James', 'Smith', 800000);
SQL> INSERT INTO
EmpStores
(EmpID, DivID, JobID, FirstName, LastName, Sal)
VALUES (2, 'SAL', 'MGR', 'Ron', 'Johnson', 350000);
SQL> INSERT INTO
EmpStores
(EmpID, DivID, JobID, FirstName, LastName, Sal)
VALUES (3, 'SAL', 'WOR', 'Fred', 'Hobbs', 140000);
SQL> INSERT INTO
EmpStores
(EmpID, DivID, JobID, FirstName, LastName, Sal)
VALUES ( 4, 'SUP', 'MGR', 'Susan', 'Jones', 200000);
SQL> INSERT INTO
EmpStores
(EmpID, DivID, JobID, FirstName, LastName, Sal)
VALUES (5, 'SAL', 'WOR', 'Rob', 'Green', 350000);
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
PARTITION BY Clause
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
CUME_DIST() Function
PERCENT_RANK() Function
NTILE() Function
Bucket specifies the number of buckets into which groups of rows are
placed.
ROW_NUMBER() Function
PERCENTILE_DIST()
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
PERCENTILE_CONT()
It examines the percent rank values in each group until it finds one
that is greater than or Equal to x.
SQL> SELECT
PERCENTILE_CONT(0.6)
WITHIN GROUP(ORDER BY SUM(SaleAmt)
DESC) Percentile_Cont ,
PERCENTILE_DIST(0.6)
WITHIN GROUP(ORDER BY SUM(SaleAmt)
DESC) Percentile_Dist
FROM AllSales
WHERE Year = 2003
GROUP BY ItemTypeID;
WINDOW FUNCTIONS
The WINDOW Functions are used to calculate Cumulative Sums and moving
averages within a specified range of rows.
UNBOUNDED PRECEDING
Specifies that the window starts at the first row of the partition.
UNBOUNDED FOLLOWING
Specifies that the window starts at the last row of the partition.
CURRENT ROW
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
RATIO_TO_REPORT() Function
The function is used to compute the ratio of a value to the sum of a set of
values.
They Are used to get a value in a row, where that row is a certain number of
rows away from the current row.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Prerequisites
Syntax:
SQL> UPDATE <Table_Name>
SET <Specification>
WHERE Clause;
SQL> UPDATE EMP
SET Comm = NULL
WHERE Job = CLERK;
SQL> UPDATE Emp
SET
(Job, Deptno) = (SELECT Job, Deptno
FROM Emp
WHERE Empno = 7499)
WHERE Empno = 7698;
SQL> UPDATE Emp
SET Deptno = (SELECT Deptno
FROM Emp
WHERE Empno = 7788)
WHERE Job = (SELECT Job
FROM Emp
WHERE Empno = 7788);
Returning Clause
The Clause Can Be Specified For Tables And Materialized Views And For
Views With A Single Base Table.
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Restrictions:
MERGE Statement
The MERGE Statement is Used To SELECT Rows From One OR More Sources
For UPDATE OR INSERT Into One OR More Tables.
Illustrations
SQL> CREATE TABLE MyBonus
(
Empno NUMBER,
Bonus NUMBER DEFAULT 100
);
SQL> INSERT INTO MyBonus(Empno)
(SELECT E.Empno
FROM Emp E
WHERE Job = 'SALESMAN');
SQL> MERGE INTO MyBonus B
USING (SELECT Empno, Sal, Deptno
FROM Emp
WHERE Deptno = 30) S
ON (B.Empno = S.Empno)
WHEN MATCHED THEN
UPDATE
SET B.Bonus = B.Bonus + S.Sal * 0.1
DELETE
WHERE (S.Sal > 4000)
WHEN NOT MATCHED THEN
INSERT(B.Empno, B.Bonus)
VALUES(S.Empno, S.Sal * 0.1)
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
VARCHAR2(12),
DELETE Statement
Prerequisites
To DELETE Rows From A Table, The TABLE Must Be in The USERS SCHEMA.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
DELETE ANY TABLE System Privilege Allows To DELETE Rows From Any
TABLE OR PARTITION TABLE OR Form The Base Table of Any VIEW.
Syntax
SQL> DELETE [FROM] <Table_Name>
[WHERE Condition];
Using RETURNING Clause
SQL> DELETE FROM Emp
WHERE Empno = 7864;
SQL> DELETE FROM Emp
WHERE Deptno = 20;
SQL> DELETE FROM Emp
WHERE Deptno = (SELECT Deptno
FROM Dept
WHERE Dname = SALES);
SQL> VARIABLE Salary NUMBER;
SQL> DELETE FROM Emp
WHERE Job = SALESMAN AND HireDate < SYSDATE
RETURNING SUM(Sal) INTO :Salary;
SQL> PRINT :Salary;
Transaction Control
A Transaction
Encountered.
Begins
When
The
First
Executable
SQL
Statement
is
COMMIT
SAVEPOINT <Name>
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Every Data Change Made During The Transaction is Temporary Until The
Transaction is Committed.
Data Manipulation Operations Primarily Do Not Affect The State of The Data,
Hence The Can Be Recovered.
The Current User Can Review The Results of The Data Manipulation
Operation By Querying The Tables.
Other Users Cannot View The Results of The Data Manipulation Operations
Made By The Current User.
The Oracle Server Institutes Read Consistency To Ensure That Each User
Sees Data As It Existed At The Time of Last Commit.
All Users Can View The Results of The Recent Transactional Change.
SQL> COMMIT;
State OF The Data After Rollback
SQL> ROLLBACK;
Rolling Back Changes To A Savepoint
SQL> ROLLBACK
TO
<SAVEPOINTName>;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
If The Table Contains Records, Before The Column is Added, The New
Column Contains NULL Values.
Modifying A Column
We Can Decrease The Width of A Column If The Column Contains Only NULL
Values And If The Table Has No Rows.
Dropping A Column
The DROP COLUMN Clause is Used For This Purpose And The Feature is
Enabled From Oracle 8i Onwards.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The SET UNUSED OPTION Marks One OR More Columns As Unused Such That
They Can Be Dropped When The Demand on System Resources is Less(8i).
Unused Columns Are Treated As if They Were Dropped, Even Trough Their
Column Data Remains in The Tables Rows.
After A Column Has Been Marked Unused, We Cannot Have Access To That
Column.
The Names And Types of Columns Marked Unused Will Not Be Displayed
During A Describe.
We Can ADD To A TABLE A New Column With The Same Name As An Unused
Column.
This Option Removes From The Table All Columns Currently Marked As
Unused.
The Option is Used When We Want To Reclaim The Extra Disk Space From
Unused Columns in The Table.
If The Table Does Not Contain UNUSED Columns The Statement Returns
With No Errors.
Dropping A Table
The Command Not Only Drops The TABLE But The ENTIRE DATABASE is Lost
Along With The ASSOCIATED INDEXES.
Syntax
SQL> DROP TABLE <TableName>
[CASCADE CONSTRAINTS];
SQL> DROP TABLE Dept30
CASCADE CONSTRAINTS;
Any VIEWS And SYNONYMS Will Remain But Are Kept in Invalid State.
Only The Creator OR Owner of The Table OR A USER With DROP ANY TABLE
Privilege Can Remove A Table From Database.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
TABLE
VIEW
SEQUENCE
SYNONYM
Syntax
SQL> RENAME <OldName> TO <NewName>;
Illustration
SQL> RENAME Dept TO Department;
Truncating A Table
It Is Used To Remove All Rows From A TABLE And To Release The STORAGE
SPACE Used By The Specific TABLE.
Syntax
SQL> TRUNCATE TABLE <TableName>;
Illustration
SQL> TRUNCATE TABLE Department;
To A TABLE OR A
ALL_COL_COMMENTS
ALL_TAB_COMMENTS
USER_COL_COMMENTS
USER_TAB_COMMENTS
Syntax
SQL> COMMENT ON TABLE <TableName>/ COLUMN
<Tablename.Column> is Text;
Illustration
SQL> COMMENT ON TABLE Emp
IS
The Table Storing Employee Information;
SQL> COMMENT ON COLUMN Emp.MGR
IS
This Column is Actually Storing The Registered Employee Numbers As
Manager Numbers, With A Self Relation;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Dropping A Comment
Syntax
SQL> CREATE TABLE <TableName>
AS
SELECT Columns
FROM TableName;
[WHERE Condition];
The CREATE TABLE AS SELECT Command Will Not Work If one of The
Selected Columns Use LONG Data Type.
When The New Table is Described It Reveals That It Has INHERITED The
Column Definition From The Existing Table.
Using This Style We Can Include All Columns Using Asterisk OR A Subset of
Columns From Table.
The New Table Can Contain INVENTED COLUMNS Which Are The Product of
Function of The Combination of Other Columns.
The Column Definition Will Adjust To The Size Necessary To Contain The
Data in The INVENTED COLUMNS.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The REDO LOG Entries Generation Can Be Avoided By Using The NOLOGGING
Keyword.
As The New Table Creation is Not Being Written To The REDO LOG Files ,The
Table Will Not Be Able To Re-Create, Following A Database Failure.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
An Index Organized Table Keeps Its Data Stored According To The PRIMARY
Key Column Values in The Table.
An Index Organized Table Stores Its Data As if The Entire Table Was Stored
in An INDEX.
Illustration
SQL> CREATE TABLE Sample
(
SampID
NUMBER(4),
SampName
VARCHAR2(20),
SampDate
DATE,
CONSTRAINT SampIDSampNamePK
PRIMARY KEY(SampID, SampName)
)
ORGANIZATION INDEX;
An Index
Organized Table is Most Effective When The Primary Key
Constitutes A Large Part of The Tables Columns.
Dividing The Rows of A Single Table Into Multiple Parts is Called Partitioning
of A Table.
The Table That is Partitioned is Called PARTITIONED TABLE And The Parts
Are Called PARTITIONS.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The Maximum Value Need Not Be Specified For The Last Partition, The
MAXVALUE Keyword is Specified.
The MAXVALUE Specifies Oracle To Use The Partition To Store Any Data That
Could Not Be Stored In The Earlier Partitions.
We Can Create Multiple Partitions Each With Its Own Upper Value Defined.
The Minimum Value For The Range is Implicitly Determined By Oracle From
The Definition of The Preceding Partition.
In Hash Partition Consecutive Values of The Partition Key Are Not Generally
Stored in The Same Partition.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
NUMBER(6)
VARCHAR2(30),
Job
VACHAR2(30),
Deptno
NUMBER(2)
CHECK Deptno IN(10, 20, 30, 40, 50, 60, 70, 80, 90),
Sal
NUMBER(8, 2),
CONSTRAINT Deptnofk_Hash
FOREIGN KEY(Deptno)
REFERENCES Dept(Deptno )
)
PARTITION BY HASH(Deptno)
PARTITIONS 9;
Format Choices
NUMBER(4)
VARCHAR2(20),
Sal
NUMBER(8, 2),
Hiredate Date,
Deptno
NUMBER(2),
Job
VARCHAR2(15),
CONSTRAINT DeptnoFK
FOREIGN KEY(Deptno) REFERENCES Dept(Deptno)
)
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
PARTITION BY LIST(Job)
(
PARTITION Jpart1
VALUES (PRESIDENT, ANALYST),
PARTITION Jpart2
VALUES(MANAGER, SALESMAN, CLERK)
);
RANGE Partitions
HASH Partitions
Ename
VARCHAR2(30),
Sal
NUMBER(8, 2),
Deptno
NUMBER(2),
Job
VARCHAR2(30),
CONSTRAINT Deptnofk
FOREIGN KEY(Deptno)
REFERENCES Dept(Deptno)
)
PARTITION BY RANGE(Ename)
SUBPARTITION BY HASH(JOB)
SUBPARTITIONS 5
(
PARTITION Namep1
VALUES LESS THAN(M),
PARTITION Namep2
VALUES LESS THAN(MAXVALUE)
);
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Jsalesman
The LOCAL Keyword Tells Oracle To Create A Separate Index For Each
Partition on The Table.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Object Tables
Object Tables Are Created By Using The User Defined Data Types.
The OID is Generated And Assigned By Oracle When The Row OR Object is
Created.
All Object Tables Automatically Inherit The Data Types From The User
Defined Data Types.
All Object Types Are Associated With Default Methods Applied Upon The
Relational Tables i.e. INSERT, DELETE, UPDATE And SELECT.
The Relational DML Operation Style is Accepted Only When The User Defined
Data Type is A Collection of Built-in Data Types, And The Object Table Does
Not Contain Any REF Constraints.
All User Defined Data Types Are Schema Objects of The Database.
The User Defined Object Data Type Can Be Used As Reference in Other
Tables, OR Instantiated As Object Table Directly.
All User Defined Data Types And Objects Are Stored Permanently in The
Data Dictionaries
USER_TYPES
USER_OBJECTS
We Can Query For The User Defined Data Types And Objects Using The
Relational SELECT.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
NUMBER(6)
,Sname
VARCHAR2(20)
,DOB
DATE
,DOA
DATE
,FEES
NUMBER(7, 2)
);
The Above Statement Creates The User Defined Object Data Type Called As
Student And Stores it in The Data Dictionary Called USER_TYPES.
This Data Type is Also Called As Collection in Oracle, And This Collection is
Reusable Where Ever The Same Data Type Collection is Expected in Project
Development.
Each Row in The Object Table Has An OID Value Generated By Oracle Server.
Relational INSERT
SQL> INSERT INTO McaStudent
VALUES(1234, Kumar, 07-Oct-98, SYSDATE, 15000);
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The Abstract Data Types Column Can Be Referred As A Part of The Tables
Columns.
SQL> SELECT *
FROM McaStudent;
SQL> SELECT StudID, Sname
FROM McaStudent;
SQL> SELECT StudID, Sname
FROM McaStudent
WHERE StudID = 1234
STUDENT,
Semester
VARCHAR2(10),
SemStartDate
DATE,
SemEndDate
DATE,
Specialization
VARCHAR2(20)
);
Once The User Defined Data Types Are Created We Can Instantiate Them in
The Normal Relational Tables.
These Instances Look As Normal Attributes With in The Table, But Can Be
Operated Only With CONSTRUCTOR METHOD OR OBJECT VIEWS.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The OID Assigned To Each Row Can Be Seen By Using The REF Function
REF() Always Returns The OID of The Registered Objects in The Object
Table.
The REF(A) Value Will Be Different Under Different Systems And May Be
Wrapped Onto Multiple Lines.
The REF() Function Can Only Reference Row Objects ,Hence We Cannot Use
REF() For Referencing Column Objects.
LOBs.
Collections.
The REF() Function By Itself Does Not Give Any Useful Information.
DEREF() Function
The DEREF() Function Takes A Reference Value i.e, The OID Generated For A
Reference And Returns The Original Value of The Row Object.
VARCHAR2(30),
StudentIncharge
REF STUDENT
);
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The REF() Function Returns The OID For The ROW OBJECT Selected.
The
StudentIncharges Table Actually
Contains The Name of The
StudentIncharge And A REFERENCE To A ROW OBJECT in The McaStudent
Table.
SQL> SELECT *
FROM StudentIncharges;
The Reference Value Cannot Be Seen Until We Use The DEREF() Function.
The Parameter For The DEREF() Function is The Column Name of The REF
Column But Not The Table Name.
Points To Note
The Query Uses A Reference To A Row Object To Travel From One Table To
The Second.
The Name of The Object Table Need Not Be Known To DEREF The Values.
The Entire Referenced Object is Returned Not Just Part of The Row.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The VALUE() Function Allows To Query The Formatted Values Directly From
The Object Table.
We Can Select The Values From Object Table Without Using The DEREF
Query Upon The StudentIncharges, StudentIncharge Column.
Invalid References
MCAStudent
Object
Table
To
Which
SQL> DELETE
FROM MCAStudent
WHERE SName = SESHU;
DANGLING REF
As Oracle Generates A OID For The Row Object Which Can Be Referenced By
Any Other Row From Other Object Table When The Row Object is DELETED
The OID is Lost And The Oracle Doesnt Reuse The OID Numbers.
Hence If A New Record For SESHU is Inserted This is Given An OID Value,
But The StudentIncharge Record Still Points To The OLD Value Only.
In An OOP System The Join is Between Objects, Hence The Fact That Two
Objects Having The Same Data Does Not Mean They Are Same.
We Can Create Abstract Data Type And Use Them Within The Object View of
An Existing Table.
NUMBER(6)
VARCHAR2(30),
Street
VARCHAR2(40),
CityName
VARCHAR2(25),
StateName
VARCHAR2(40),
Pincode
NUMBER(6)
);
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
VARCHAR2(40),
CityName
VARCHAR2(25),
StateName
VARCHAR2(40),
Pincode
NUMBER(6)
);
SQL> CREATE OR REPLACE TYPE MyStudent
AS OBJECT
(
SName
VARCHAR2(30),
Saddress
Myaddress
);
As Student Table Was Created Without Using The MyAddress And MyStudent
Data Types It Has To Be Accessed Via OBJECT VIEWS.
An OBJECT VIEW Can Be Specified Upon The Abstract Data Types To Apply
Onto The Relational Table.
We Can Access The Students Table Directly As A Relational Table OR Via The
CONSTRUCTOR Methods of The Abstract Data Types.
Selecting Data From The Relational Table Using The OBJECT VIEW
SQL> SELECT *
FROM StudentOV;
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
If The Students Table is Related To Another Table, Then The Object Views
Can Be Created As A Reference Between These Tables.
By Using The Above Concept ORACLE Uses The Existing PRIMARY KEY OR
FOREIGN KEY Relationships To Simulate OIDs For Use By REFs Between
The Tables.
When The Tables Are Treated As OBJECTS We Can Use The REFs, To
Automatically Perform JOINS Upon The Tables Using The DEREF() Function.
NUMBER(6),
StudID
NUMBER(6),
BookTitle
VARCHAR2(50),
LendingDate
DATE,
CONSTRAINT LibtreamNoPK
PRIMARY KEY(LibTranNO, Studid),
CONSTRAINT StudentBooksFK
FOREIGN KEY(Studid)
REFERENCES Students(StudID)
);
GENERATING OIDs
As First Step Create An ABSTRACT DATA TYPE That Has The Same Structure
As The Student Table i.e. The Relational Table.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
NUMBER(6),
Sname
VARCHAR2(30),
Street
Varchar2(40),
Cityname
VARCHAR2(25),
Statename
VARCHAR2(40),
Pincode
NUMBER(6)
);
As The Next Step Create A View Based Upon The StudentType By Assigning
OID Values To The Records in Student Table.
The First Part of The Statement Tells The Database To CREATE A VIEW Based
on The Structure Defined in Student Type.
The Next Part of The CREATE VIEW Tells The Database How To Construct
OID Values For The Rows in Students Table.
With The Above Step The Rows of Students Are Now Accessible As ROW
OBJECTS Via The StudentOV View.
The OID Values Generated For The StudentOV Rows Are Called As PKOIDs
As They Are Based Upon Students Primary Key Values.
The Relational Tables Can Be Accessed As Row OBJECTS If The Object Views
Are Created Upon Them.
Generating References
From The StudentOV Object View That Has Been Created, The Rows in
Students Table Can Be Accessed Via OIDs.
Once The REFs Are Created We Can Use DEREF() Function To Access The
Students Data From Student Books.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
MAKE_REF() Function
We Use The DEREF() Function To SELECT The Value of The Referenced Data.
Steps Performed
The Query Finds The Records in The StudentBooks Table For Which The
LendingDate is The Current System Date.
Taking The StudID Value From That Record Evaluates Its Reference.
The StudentOV Object View Returns The Record Whose PKOID Matched The
Referenced Value.
The DEREF() Function Then Gets Activated Returning The Value of The
Referenced Row.
The Query Returns Rows From Students Even Though The USER Actually
Queried on StudentBooks.
Things To Note
Object Views of Column Objects Enable To Work With Table As if They Were
Both Relational Tables And Object Relational Tables.
When OBJECT Views Are Extended To Row OBJECT They Enable To Generate
OID Values Based on Established FOREIGN KEY OR PRIMARY KEY
Relationship.
They Help in Using OOP Features Such As REFERENCES Against The Object
TABLES.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Once The Above Specifications Are Completed We Can Work With The Data
As if it Was Stored in OBJECT TABLES.
Object That
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Procedural Extensions To
Structured Query Language
Using
PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
PL/SQL is A Part of The Oracle RDBMS, And Hence Can Reside in Two
Environments, The Client And The Server.
The SQL Statement Processor is Always Located On The Oracle Server And
Hence All SQL Statements Are Processed on The Server Only.
SERVER Side.
CLIENT Side.
Rules
That
Determine
How
Programming
When PL/SQL Engine is Located Upon The SERVER, The Whole PL/SQL Block
is Passed To The PL/SQL Engine on The ORACLE SERVER For Processing
Including Client Components.
This Concept Gives Security, Less Load And Performance For Applications.
When The PL/SQL Engine is Located Upon The Client, The PL/SQL
Processing is Done on The Client Side.
All SQL Statements That Are
Embedded Within The PL/SQL Block, Are Sent To The ORACLE SERVER For
Further Processing.
Because of The Above Concept, The Application Load in The Network Will
Highly Reduce And The System Becomes highly Loose Coupled in The
Development Process, Giving High Accessibility For Easy Maintenance.
The Entire
Advantages of PL/SQL
Completely Portable.
Better Performance.
Higher Productivity.
Tight Security.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
PL/SQL
Block
PL/SQL
Statements
SQL
Statements
PL/SQL Engine
Oracle Server
PL/SQL in Client/Server Architecture
Client Side
Application
Using SQL
Application Using
PL/SQL
Block of SQL
Statements
And Their
Result Sets
SQL Statement
Processor
PL/SQL Engine
Server Side
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The PL/SQL Data Types Correspond With SQLs Column Types Making
Learning Process Easier.
The Basic Units That Make Up A PL/SQL Program Are Logical Blocks.
A Block Groups Related Declarations And Statements into One Single Unit.
The Declarations Are Local To The Block And Cease To Exist OR Lost When
The Block Completes.
Cluttered
Namespaces
For
Variable
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Declarative Part
Executable Part
Any Exceptions That Are Raised During The Program Execution Are Handled
Here.
Local Sub Programs Can Be Defined in The Declarative Part of Any Block.
Local Sub Programs Can Be Called From The Block in Which They Are
Declared.
SQL> DECLARE
Variable Declarations,
Cursor Declarationa,
User_Defined Execption
BEGIN
SQL Statements
PL/SQL Statement
EXCEPTION
Action To Perform When Errors
Occur.
END;
We Can Define Local Sub Programs in The Declarative Part of Any Block.
However, We Can Call Local Subprograms Only From The Block in Which
They Are Defined.
NULL BLOCK
END;
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> BEGIN
RETURN;
END;
SQL> DECLARE
BEGIN
NULL;
END;
SQL> DECLARE
BEGIN
NULL;
EXCEPTION
Place A Period (.) To Close A SQL*Plus Buffer With Out Running The PL/SQL
Program.
Semicolon Within The PL/SQL Block Does Not Closes OR Runs The SQL
Buffer.
Anonymous Blocks
SQL> DECLARE
BEGIN
NULL;
EXCEPTION
WHEN OTHERS THEN
NULL;
END;
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Named Blocks
They Have All The Features As Specified For The Anonymous Blocks,
The Only Difference is That Each Block Can Be Named if Necessary.
But
They Give The Specifications of The Named Spaces As Provided in High Level
OO Languages Like C++ And JAVA.
SQL> <<FirstBlock>>
DECLARE
BEGIN
NULL;
EXCEPTION
Named Blocks Make The PL/SQL Blocks More Clear and Readable.
Sub-Programmed Blocks
These Are Named PL/SQL Blocks That Can Take Parameters And Can Be
Invoked With in The Other Anonymous OR Sub-Programmed PL/SQL Blocks.
The Sub-Programmed Blocks Add The Concept of Code Reusability and Help
The Developer To Achieve The Modular Approach.
Data Can Be Temporarily Stored in One OR More Variables For Use When
Validating Data Input For Processing The Data in The Data Flow Process.
Data Manipulation
Reusability
Ease of Maintenance
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Handling Variables
There Are Three Parameter Modes, They Are IN (The Default), OUT And IN
OUT.
Storage Format
Constraints
Valid Range
Main Data Types Are Those That Correspond To Column Types in Oracle
Server Tables.
They Help in Keeping All The Related Data Items Together As One Collection.
%ROWTYPE.
RECORD Type.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
They Are Very Essential When Manipulating Collection of Data Items in SubPrograms.
They Hold Values Called Locators, Specifying The Location of Large Objects
That Are Stored Out of Line in The PL/SQL Program.
IdentifierName
Constant
DataType
NOT NULL
Constraints A Variable Such That It Must Contain A Value And Raises If NULL
is Identified.
DEFAULT
Sets The Default Value For The Value in The PL/SQL Program if Not
Attended.
Expr
Illustration
DECLARE
V_Sample1
NUMBER(2);
V_Sample2
V_Sample3
V_Sample4
NUMBER(2) := 50;
V_Sample5
A To Z OR a OR z
0 To 9
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
PL/SQL Key Words Are Not Case Sensitive, Hence Lower Case Letters Are
Equivalent To Corresponding Upper Case Letters.
Lexical Units
A
Group of Characters That Are Contained Within A Line of PL/SQL
Statement Are Called As Lexical Units.
Delimiters
Identifiers
Literals
Comments
Delimiters
Identifiers
Constants
Variables
Exception
Cursor Variables
Subprograms
Packages
Identifiers Are Not Case Sensitive, Until They Are Not Declared Within
Quotes.
Valid Identifier
Invalid Identifier
This&That
P2
YouMe
V_Phone#
Show/Off
V_Phone$
Number
Delimiters
Reserved Words
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Predefined Identifiers
Error
Prone
As
The
Local
Quoted Identifiers
Employee(s)
Status On/Off
Literals
Comments In PL/SQL
*/)
It is Most Preferable To Use Multi Line Comments Rather Than Single Line
Comments.
Declarations in PL/SQL
As The Program Executes, The Values of Variables Can Change But The
Values of Constants Cannot Change.
Any Variable Can Be Declared Only in The Declarative Part of Any PL/SQL
Block, Subprogram OR Package.
Illustration
DECLARE
AdmnDate
DATE;
PatientName
VARCHAR2(30);
BPCount
SMALLINT := 0;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The Package Enables To Display Output From PL/SQL Blocks And SubPrograms.
Syntax
DBMS_OUTPUT.PUT_LINE(Message);
The Size of The Buffer Can Be Set Between 2000 To 10,00,000 Bytes.
Illustrations
SQL> BEGIN
DBMS_OUTPUT.PUT_LINE('First Program in PL/SQL');
DBMS_OUTPUT.PUT_LINE('Illustration By');
DBMS_OUTPUT.PUT_LINE('''Satish K Yellanki''');
END;
/
Steps To Compile And Produce Output
DBMS_OUTPUT.ENABLE Once
Process to Get Activated.
Declared
Will
Make
The
SERVEROUTPUT
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> DECLARE
V_Sample1 NUMBER(2);
V_Sample2 CONSTANT NUMBER(2) := 99;
V_Sample3 NUMBER(2) NOT NULL := 0;
V_Sample4 NUMBER(2) := 50;
V_Sample5 NUMBER(2) DEFAULT 25;
BEGIN
DBMS_OUTPUT.PUT_LINE('The Value in Sample1 : '|| V_Sample1);
DBMS_OUTPUT.PUT_LINE('The Value in Sample2 : '|| V_Sample2);
DBMS_OUTPUT.PUT_LINE('The Value in Sample3 : '|| V_Sample3);
DBMS_OUTPUT.PUT_LINE('The Value in Sample4 : '|| V_Sample4);
DBMS_OUTPUT.PUT_LINE('The Value in Sample5 : '|| V_Sample5);
END;
/
SQL> BEGIN
DBMS_OUTPUT.PUT_LINE('Text With Out Quotes');
DBMS_OUTPUT.PUT_LINE('''Text With in Quotes''');
DBMS_OUTPUT.PUT_LINE('''Text'' ''With'' ''in'' ''Quotes''');
DBMS_OUTPUT.PUT_LINE(Q'!'Text With in Quotes'!');
DBMS_OUTPUT.PUT_LINE(Q'!'Text' 'With' 'in' 'Quotes'!');
END;
/
SQL> DECLARE
MyNumber1 NUMBER := 10;
MyNumber2 NUMBER := 20;
BEGIN
DBMS_OUTPUT.PUT_LINE('Your First Number is : '||MyNumber1);
DBMS_OUTPUT.PUT_LINE('Your Second Number is : '||MyNumber2);
DBMS_OUTPUT.PUT_LINE('The Sum of '||MyNumber1||' and
'||MyNumber2||' is : '||TO_CHAR(MyNumber1 + MyNumber2,
'999D99'));
END;
/
SQL> DECLARE
String1 VARCHAR2(30) := '&String1';
String2 VARCHAR2(30) := '&String2';
BEGIN
DBMS_OUTPUT.PUT_LINE('Your First String is : '||String1);
DBMS_OUTPUT.PUT_LINE('Your Second String is : '||String2);
DBMS_OUTPUT.PUT_LINE('Your Final String is : '||String1||String2);
END;
/
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> DECLARE
V_FirstName
VARCHAR2(30) := '&FName';
V_MiddleName
VARCHAR2(30) := '&MName';
V_LastName
VARCHAR2(30) := '&LName';
V_DOB
DATE := '&DateOfBirth';
BEGIN
DBMS_OUTPUT.PUT_LINE('Your First Name is : '||V_FirstName);
DBMS_OUTPUT.PUT_LINE('Your Middle Name is : '||V_MiddleName);
DBMS_OUTPUT.PUT_LINE('Your Last Name is : '||V_LastName);
DBMS_OUTPUT.PUT_LINE('******Concatenating******');
DBMS_OUTPUT.PUT_LINE('Your Full Name is : '||V_FirstName||'
'||V_MiddleName||' '||V_LastName);
DBMS_OUTPUT.PUT_LINE('Your Date of Birth is : '|| V_DOB);
DBMS_OUTPUT.PUT_LINE('Your Were Born on : '|| TO_CHAR(V_DOB,
'Day'));
DBMS_OUTPUT.PUT_LINE('Your Present Age is : '|| TRUNC((SYSDATE V_DOB)/365));
END;
/
SQL> DECLARE
V_FirstNum NUMBER := &FNumber;
V_SecondNum NUMBER := &SNumber;
V_Result NUMBER := 0;
BEGIN
DBMS_OUTPUT.PUT_LINE('You Gave Me '||V_FirstNum||' And
'||V_SecondNum);
DBMS_OUTPUT.PUT_LINE('I Executed Their Sum And The Result is : '||
TO_CHAR(V_FirstNum + V_SecondNum, '9999.99'));
DBMS_OUTPUT.PUT_LINE('As You Did Not Reinitialize The Result
Variable It is Having : '||V_Result||' Only');
END;
/
Operators in PL/SQL
Logical
Arithmetic
: +, -, *, /
Concatenation
: ||
Exponentiation
: **
Comparison
SQL*Plus
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Operator Precedence
Operator Precedence
Equal Precedence
**, NOT
+, - (Identity, Negation)
*, /
+, -
AND, OR
Scope
Once The Scope of The Variable is Lost it Means That The Life of The Variable
No More.
All Variables Loose Their Scope As Soon As The PL/SQL Block Ends OR
Terminates.
Oracle Automatically Releases The Space Upon That Variable Once its Scope
is Closed.
Visibility
If A Variable Looses Its Visibility But is Carrying Scope, Then We Can Extend
The Visibility of The Variable Using The Qualified Name.
Within The Sub Block, Only The Local Identifier Are Visible.
The Same Identifier Can Be Declared In Two Different Blocks, The Change In
One Does Not Affect The Other.
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Concepts of Scoping
Even When The Data Types Are Differing, Variables And Parameters Cannot
Share The Same Name.
SQL> DECLARE
V_Boolean
BOOLEAN;
V_Boolean
VARCHAR2(5) := 'SAMPLE';
BEGIN
DBMS_OUTPUT.PUT_LINE('The Value is : '||V_Boolean);
V_Boolean := FALSE;
END;
The Names of Database Columns Take Precedence Over The Names of Local
Variables And Formal Parameters.
The Variable Y Can Reference The Variable Named X, But The Variable X
Cannot Reference Variable Y.
If The Variable Named Y In The Nested Block is Given The Same Name As
The Variable Name X In The Outer Block Its Value is Valid Only For The
Duration of The Nested Block.
They Cannot Be Repeated in The Same Block, In Different Blocks They Are
Referenced Using The Name Resolution Technique.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> DECLARE
X REAL := 205;
BEGIN
DBMS_OUTPUT.PUT_LINE('The Value
of Outer X : '||X);
DECLARE
X REAL := 405;
BEGIN
DBMS_OUTPUT.PUT_LINE('The Value of Inner X : '||X);
END;
DBMS_OUTPUT.PUT_LINE('The Value
of Outer X : '||X);
END;
/
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
DECLARE
D REAL := 500;
A VARCHAR2(30) := 'Hello Gals';
BEGIN
DBMS_OUTPUT.PUT_LINE('The Value of Last D is Availabe : ' ||D);
DBMS_OUTPUT.PUT_LINE('The Value of Last String A is Availabe
Here : ' ||A);
END;
DBMS_OUTPUT.PUT_LINE('The Value of Outer String A is Availabe : '
||A);
DBMS_OUTPUT.PUT_LINE('The Value of Outer Real B is Availabe : ' ||B);
END;
/
SQL> <<FirstBlock>>
DECLARE
A VARCHAR2(30) := 'Hello Guys';
B REAL := 300;
BEGIN
DBMS_OUTPUT.PUT_LINE('The Value of Outer String A is Availabe Here :
' ||A);
DBMS_OUTPUT.PUT_LINE('The Value of Outer Real B is Availabe Here : '
||B);
DECLARE
A INTEGER := 2000;
B REAL := 400;
BEGIN
DBMS_OUTPUT.PUT_LINE('The Value of Inner Integer A is Availabe
Here : ' ||A);
DBMS_OUTPUT.PUT_LINE('The Value of Inner Real B is Availabe : '
||B);
DBMS_OUTPUT.PUT_LINE('The Value of Outer String A is Availabe
Here : ' ||FirstBlock.A);
END;
DECLARE
D REAL := 500;
A VARCHAR2(30) := 'Hello Gals';
BEGIN
DBMS_OUTPUT.PUT_LINE('The Value of Last D is Available : ' ||D);
DBMS_OUTPUT.PUT_LINE('The Value of Outer String and Last
String together is : ' ||FirstBlock.A||' and '||A);
END;
DBMS_OUTPUT.PUT_LINE('The Value of Outer String A is Available : '
||A);
DBMS_OUTPUT.PUT_LINE('The Value of Outer Real B is Available : '
||B);
END <<FirstBlock>>;
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Bind Variables
PL/SQL Variables
Bind Variables
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Step 1
SQL> DECLARE
V_Sal NUMBER(7, 2);
V_Empno NUMBER(4) := &GiveEmpno;
BEGIN
SELECT Sal INTO V_Sal
FROM Emp
WHERE Empno = V_Empno;
:B_Sal := V_Sal;
:B_Empno := V_Empno;
END;
/
Step 2
SQL> DECLARE
V_Comm NUMBER(7, 2);
BEGIN
SELECT Comm INTO V_Comm
FROM Emp
WHERE Empno = :B_Empno;
:B_Comm := V_Comm;
END;
/
Step 3
SQL> BEGIN
DBMS_OUTPUT.PUT_LINE('The Total Salary of '||(:B_Empno)||' is
'||(:B_Sal + NVL(:B_Comm, 0)));
END;
/
PL/SQL Variables
These Are Substitution Variables That Are Directly Declared Within The
Program.
The Life of PL/SQL Variable is With in The Scope of The PL/SQL Block Only.
SQL> DECLARE
V_Number1 NUMBER(9, 2) := &P_Number1;
V_Number2 Number(9, 2) := &P_Number2;
V_Result NUMBER(9, 2);
BEGIN
V_Result := (V_Number1 / V_Number2) + V_Number2;
DBMS_OUTPUT.PUT_LINE(V_Result);
END;
/
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL Statements,
Uppercasing.
The Names of Local Variables And Formal Parameters Take Precedence Over
The Names of Database Tables.
The Names of Columns Take Precedence Over The Names of Local Variables.
PL/SQL
Key
Words
And
Data
Types
Are
Kept
In
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Branching
Selection And
Looping.
Conditional Statements.
Iterative Statements.
IF-THEN-ELSE
END IF
ELSIF
CASE
END CASE
END
LOOP
FOR-LOOP
WHILE-LOOP
END LOOP
EXIT-WHEN And
GOTO.
Conditional Statements
Branching Statements.
Selection Statements.
Branching Statements
In PL/SQL Branching
Statements.
is
Implemented
IF ELSE..END IF Statements.
IF..ELSIF..END IF Statements.
The
Using
The
IFTHENELSE
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
General Syntax
IF Condition1 THEN
Statement1;
Statement2;
END IF;
General Points To Ponder
The END IF is A Reserved Phrase That Indicates The End of The IF..THEN
Construct.
After The Actual Job of IF Has Been Completed, The Control Structure
Returns The Job To The Original State of The PL/SQL Block.
SQL> DECLARE
V_Number1 NUMBER := &Number1;
V_Number2 NUMBER := &Number2;
V_TEMP NUMBER;
BEGIN
DBMS_OUTPUT.PUT_LINE('Original V_Number1 = '|| V_NUMBER1);
DBMS_OUTPUT.PUT_LINE('Original V_Number2 = '|| V_Number2);
IF V_Number1 > V_Number2 THEN
V_TEMP := V_Number1;
V_Number1 := V_Number2;
V_Number2 := V_TEMP;
END IF;
DBMS_OUTPUT.PUT_LINE('Swapped V_Number1 = '|| V_NUMBER1);
DBMS_OUTPUT.PUT_LINE('Swapped V_Number2 = '|| V_Number2);
END;
IFTHENELSEEND IF Statement
One Group is Evaluated When The Condition Evaluates To TRUE, The Next
Group is Evaluated When The Condition Evaluates To FALSE.
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Syntax
IF Condition THEN
Statement 1;
ELSE
Statement 2;
END IF;
This Concept Should Be Used When Trying To Choose Between Two Mutually
Exclusive Actions.
SQL> DECLARE
V_Num NUMBER := &EnterNumber;
BEGIN
IF MOD(V_Num,2) = 0 THEN
DBMS_OUTPUT.PUT_LINE(V_Num||' is an Even Number.');
ELSE
DBMS_OUTPUT.PUT_LINE(V_Num||' is an Odd Number.');
END IF;
END;
/
SQL> DECLARE
V_Number1 NUMBER := &Number1;
V_Number2 NUMBER := &Number2;
BEGIN
IF
V_Number1 > V_Number2 THEN
DBMS_OUTPUT.PUT_LINE('The Greatest Number is : '||V_Number1);
ELSE
IF V_Number2 > V_Number1 THEN
DBMS_OUTPUT.PUT_LINE('The Greatest Numeber is :
'||V_Number2);
ELSE
DBMS_OUTPUT.PUT_LINE('The Numbers are equal '||V_Number1
||' and '||V_Number2);
END IF;
END IF;
END;
Behavior of NULLs
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> DECLARE
V_Num1 NUMBER := &Number1;
V_Num2 NUMBER := &Number2;
BEGIN
IF V_Num1 = V_Num2 THEN
DBMS_OUTPUT.PUT_LINE('Given Numbers are Equal');
END IF;
DBMS_OUTPUT.PUT_LINE('Did you Watch The NULL Effect.');
END;
/
Each IF Block That is Opened Needs A Proper Close With END IF. Else
PL/SQL Raises Exceptions.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Syntax:
IF Condition THEN
IF Condition THEN
IF Condition THEN
Statement1;
ELSE
Statement2;
END IF;
ELSE
Statement3;
END IF;
ELSE
Statement4;
END IF;
SQL> DECLARE
V_Year NUMBER := &Year;
BEGIN
IF MOD(V_Year,4) = 0 THEN
IF MOD(V_Year,100) <> 0 THEN
DBMS_OUTPUT.PUT_LINE(V_Year || ' is a Leap Year');
ELSE
IF MOD(V_Year,400) = 0 THEN
DBMS_OUTPUT.PUT_LINE(V_Year || ' is a Leap Year');
ELSE
DBMS_OUTPUT.PUT_LINE(V_Year || ' is a not a Leap Year');
END IF;
END IF;
ELSE
DBMS_OUTPUT.PUT_LINE(V_Year || ' is a not a Leap Year');
END IF;
END;
/
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Syntax1
IF Condition1 AND Condition2 THEN
Statement1;
Statement2;
ELSE
Statement3;
Statement4;
END IF;
Syntax2
IF Condition1 OR Condition2 THEN
Statement1;
Statement2;
ELSE
Statement3;
Statement4;
END IF;
Syntax3
IF Condition1 AND Condition2 OR Condition3 THEN
Statement1;
Statement2;
ELSE
Statement3;
Statement4;
END IF;
SQL> DECLARE
V_Name VARCHAR2(20) := INITCAP('&GiveName');
V_Graduate CHAR(1) := UPPER('&Graduate');
V_Passport CHAR(1) := UPPER('&Passport');
V_Toefl CHAR(1) := UPPER('&Toefl');
BEGIN
IF V_Graduate = 'Y' AND V_Passport = 'Y' AND V_Toefl = 'Y' THEN
DBMS_OUTPUT.PUT_LINE('Congratulations '||V_Name||' You Are
Eligible To Apply For US Universities.');
ELSE
DBMS_OUTPUT.PUT_LINE('Sorry! '||V_Name||' Requirements Do
Not Match. Try Again.');
END IF;
END;
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
/
SQL> DECLARE
V_Name VARCHAR2(20) := INITCAP('&GiveName');
V_PAN CHAR(1) := UPPER('&PAN');
V_DRLicence CHAR(1) := UPPER('&DRLicence');
V_VoterCard CHAR(1) := UPPER('&VoterCard');
BEGIN
IF V_PAN = 'Y' AND
(V_DRLicence = 'Y' OR V_VoterCard = 'Y') THEN
DBMS_OUTPUT.PUT_LINE('Congratulations, '||V_Name||' You Are
Eligible For Taking The Bank Loan.');
ELSE
DBMS_OUTPUT.PUT_LINE('Sorry! '||V_Name||' Requirements Do Not
Match. Try Again.');
END IF;
END;
ELSEIF Ladder
In This Case Each FALSE State Has An ELSE With A Condition Applied With
One Block of Branching State.
Syntax
IF Condition1 THEN
Statement1;
ELSE
IF Condition2 THEN
Statement2;
ELSE
IF Condition3 THEN
Statement3;
ELSE
Statement4;
END IF;
Statement5;
END IF;
Statement6;
END IF;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> DECLARE
V_operator VARCHAR2(2) := '&Operator';
V_Number1 NUMBER := &Operand1;
V_Number2 NUMBER := &Operand2;
BEGIN
IF V_Operator = '+' THEN
DBMS_OUTPUT.PUT_LINE('The Sum of '||V_Number1||' and
'||V_Number2||' is : '||TO_NUMBER(V_Number1 + V_Number2));
ELSE IF V_Operator = '-' THEN
DBMS_OUTPUT.PUT_LINE('The Difference of '||V_Number1||'
and '||V_Number2||' is : '||TO_NUMBER(V_Number1 V_Number2));
ELSE IF V_Operator = '*' THEN
DBMS_OUTPUT.PUT_LINE('The Product of
'||V_Number1||' and '||V_Number2||' is :
'||TO_NUMBER(V_Number1 * V_Number2));
ELSE IF V_Operator = '/' THEN
DBMS_OUTPUT.PUT_LINE('The Quotient of
'||V_Number1||' and '||V_Number2||' is :
'||TO_NUMBER(V_Number1 / V_Number2));
ELSE IF V_Operator = '**' THEN
DBMS_OUTPUT.PUT_LINE('The Power of
'||V_Number1||' and '||V_Number2||' is :
'||TO_NUMBER(V_Number1 **
V_Number2));
ELSE
DBMS_OUTPUT.PUT_LINE('Invalid
Operator... Please Check Your Self...!');
END IF;
END IF;
END IF;
END IF;
END IF;
END;
/
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> DECLARE
V_Number1 NUMBER := &Number1;
V_Number2 NUMBER := &Number2;
BEGIN
IF V_Number1 > V_Number2 THEN
DBMS_OUTPUT.PUT_LINE('The Greatest Number is : '||V_Number1);
ELSE
IF V_Number2 > V_Number1 THEN
DBMS_OUTPUT.PUT_LINE('The Greatest Number is :
'||V_Number2);
ELSE
DBMS_OUTPUT.PUT_LINE('The Numbers are equal '||V_Number1
||' and '||V_Number2);
END IF;
END IF;
END;
/
ELSIF Statements
Syntax:
IF Condition1 THEN
Statements1;
ELSIF Condition2 THEN
Statement2;
ELSIF Condition3 THEN
Statement3;
ELSE
Statement n;
END IF;
Syntax:
IF Condition1 THEN
Statement1;
ELSE IF Condition2 THEN
Statement2;
ELSE IF Condition3 THEN
Statement3;
ELSE
Statement4;
END IF;
END IF;
END IF;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> DECLARE
V_operator VARCHAR2(2) := '&Operator';
V_Number1 NUMBER := &Operand1;
V_Number2 NUMBER := &Operand2;
BEGIN
IF V_Operator = '+' THEN
DBMS_OUTPUT.PUT_LINE('The Sum of '||V_Number1||' and
'||V_Number2||' is : '||TO_NUMBER(V_Number1 + V_Number2));
ELSIF V_Operator = '-' THEN
DBMS_OUTPUT.PUT_LINE('The Difference of '||V_Number1||'
and '||V_Number2||' is : '||TO_NUMBER(V_Number1 V_Number2));
ELSIF V_Operator = '*' THEN
DBMS_OUTPUT.PUT_LINE('The Product of '||V_Number1||' and
'||V_Number2||' is : '||TO_NUMBER(V_Number1 *
V_Number2));
ELSIF V_Operator = '/' THEN
DBMS_OUTPUT.PUT_LINE('The Quotient of '||V_Number1||' and
'||V_Number2||' is : '||TO_NUMBER(V_Number1 /
V_Number2));
ELSIF V_Operator = '**' THEN
DBMS_OUTPUT.PUT_LINE('The Power of '||V_Number1||' and
'||V_Number2||' is : '||TO_NUMBER(V_Number1 **
V_Number2));
ELSE
DBMS_OUTPUT.PUT_LINE('Invalid Operator... Please Check Your
Self...!');
END IF;
END;
/
SQL> DECLARE
V_Sal NUMBER(8,2) := 25005;
V_Name VARCHAR2(30) := INITCAP('&GiveName');
V_Result VARCHAR2(400);
V_Gender CHAR(1) := UPPER('&GiveGender');
V_Marital CHAR(1) := UPPER('&GiveMaritalStatus');
V_Country VARCHAR2(30) := UPPER('&GiveCountry');
BEGIN
DBMS_OUTPUT.PUT_LINE('The Country you Gave is : '||V_Country);
IF V_Marital IN('M','S') THEN
IF V_Gender = 'M' THEN
V_Result := 'Mr. '||INITCAP(V_Name)||', Your Salary as per
your country is';
ELSIF V_Gender = 'F' THEN
IF V_Marital = 'S' THEN
V_Result := 'Miss. '||INITCAP(V_Name)||', Your Salary as
per your country is';
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
ELSE
V_Result := 'Mrs. '||INITCAP(V_Name)||', Your Salary as
per your country is';
END IF;
ELSE
DBMS_OUTPUT.PUT_LINE('Sorry !'||INITCAP(V_Name)||'! the
gender you gave cannot be processed...Please Try Again.');
END IF;
IF V_Country IN('INDIA','BHUTAN') THEN
DBMS_OUTPUT.PUT_LINE(V_Result||' : INR '||TO_CHAR(V_Sal,'0,99,999.99'));
ELSIF V_Country = 'MAURITIUS' THEN
DBMS_OUTPUT.PUT_LINE(V_Result||' : MUR '||TO_CHAR(V_Sal,'0,99,999.99'));
ELSIF V_Country = 'NEPALESE' THEN
DBMS_OUTPUT.PUT_LINE(V_Result||' : NPR '||TO_CHAR(V_Sal,'0,99,999.99'));
ELSIF V_Country = 'PAKISTAN' THEN
DBMS_OUTPUT.PUT_LINE(V_Result||' : PKR '||TO_CHAR(V_Sal,'0,99,999.99'));
ELSIF V_Country = 'SEYCHELLES' THEN
DBMS_OUTPUT.PUT_LINE(V_Result||' : SCR '||TO_CHAR(V_Sal,'0,99,999.99'));
ELSIF V_Country = 'SRI LANKAN' THEN
DBMS_OUTPUT.PUT_LINE(V_Result||' : LKR '||TO_CHAR(V_Sal,'0,99,999.99'));
ELSIF V_Country = 'INDONESIA' THEN
DBMS_OUTPUT.PUT_LINE(V_Result||' : LKR '||TO_CHAR(V_Sal,'0,99,999.99'));
ELSE
DBMS_OUTPUT.PUT_LINE('Sorry '|| INITCAP(V_Name) ||'! Your
Country Does not Exist...Plese Try Again.');
END IF;
ELSE
DBMS_OUTPUT.PUT_LINE('Sorry !'||INITCAP(V_Name)||'! Your Marital
Status Cannot be confirmed properly.');
END IF;
END;
/
Selections in PL/SQL
The SELECTION
STATEMENTS.
Simple CASE
Searched CASE
Strategy
is
Implemented
In
PL/SQL
Using
CASE
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The Reserved Word CASE Marks The Beginning of The CASE Statement.
The Selector is Evaluated Only Once For The Whole Selection Process.
Simple CASE is Not Suitable for Multi Conditional Analysis And Other Than
The Equality Operator.
SQL> DECLARE
V_Grade CHAR := UPPER('&EnterGrade');
BEGIN
CASE V_Grade
WHEN 'A' THEN
DBMS_OUTPUT.PUT_LINE('You are Awarded with Excellent Grade');
WHEN 'B' THEN
DBMS_OUTPUT.PUT_LINE('You are Awarded with Very Good Grade');
WHEN 'C' THEN
DBMS_OUTPUT.PUT_LINE('You are Awarded with Good Grade');
WHEN 'D' THEN
DBMS_OUTPUT.PUT_LINE('You are Awarded with Fair Grade');
WHEN 'E' THEN
DBMS_OUTPUT.PUT_LINE('You are Awarded with Poor Grade');
ELSE
DBMS_OUTPUT.PUT_LINE('Sorry!...No Such Grade is Existing');
END CASE;
END;
/
SQL> DECLARE
V_operator VARCHAR2(2) := '&Operator';
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Searched CASE
The Searched CASE Can Evaluate Multiple Conditions Using The Range
Evaluation Method.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> DECLARE
V_Grade CHAR := UPPER('&EnterGrade');
BEGIN
CASE
WHEN V_Grade = 'A' THEN
DBMS_OUTPUT.PUT_LINE('You are Awarded with Excellent
Grade');
WHEN V_Grade = 'B' THEN
DBMS_OUTPUT.PUT_LINE('You are Awarded with Very Good
Grade');
WHEN V_Grade = 'C' THEN
DBMS_OUTPUT.PUT_LINE('You are Awarded with Good
Grade');
WHEN V_Grade = 'D' THEN
DBMS_OUTPUT.PUT_LINE('You are Awarded with Fair Grade');
WHEN V_Grade = 'E' THEN
DBMS_OUTPUT.PUT_LINE('You are Awarded with Poor Grade');
ELSE
DBMS_OUTPUT.PUT_LINE('Sorry!...No Such Grade is Existing');
END CASE;
END;
/
SQL> DECLARE
V_operator VARCHAR2(2) := '&Operator';
V_Number1 NUMBER := &Operand1;
V_Number2 NUMBER := &Operand2;
BEGIN
CASE
WHEN V_Operator = '+' THEN
DBMS_OUTPUT.PUT_LINE('The Sum of '||V_Number1||' and
'||V_Number2||' is : '||TO_NUMBER(V_Number1 +
V_Number2));
WHEN V_Operator = '-' THEN
DBMS_OUTPUT.PUT_LINE('The Difference of '||V_Number1||'
and '||V_Number2||' is : '||TO_NUMBER(V_Number1 V_Number2));
WHEN V_Operator = '*' THEN
DBMS_OUTPUT.PUT_LINE('The Product of '||V_Number1||' and
'||V_Number2||' is : '||TO_NUMBER(V_Number1 *
V_Number2));
WHEN V_Operator = '/' THEN
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
CASE Expressions
CASE Expressions Reduce The Redundancy of The Code And Help in Result
Reusability.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> DECLARE
V_operator VARCHAR2(2) := '&Operator';
V_Number1 NUMBER := &Operand1;
V_Number2 NUMBER := &Operand2;
V_Result VARCHAR2(300);
BEGIN
V_Result := CASE
WHEN V_Operator = '+' THEN
'The Sum of '||V_Number1||' and '||V_Number2||'
is : '||TO_NUMBER(V_Number1 + V_Number2)
WHEN V_Operator = '-' THEN
'The Difference of '||V_Number1||' and
'||V_Number2||' is : '||TO_NUMBER(V_Number1 V_Number2)
WHEN V_Operator = '*' THEN
'The Product of '||V_Number1||' and
'||V_Number2||' is : '||TO_NUMBER(V_Number1 *
V_Number2)
WHEN V_Operator = '/' THEN
'The Quotient of '||V_Number1||' and
'||V_Number2||' is : '||TO_NUMBER(V_Number1 /
V_Number2)
WHEN V_Operator = '**' THEN
'The Power of '||V_Number1||' and '||V_Number2||'
is : '||TO_NUMBER(V_Number1 ** V_Number2)
END;
DBMS_OUTPUT.PUT_LINE(V_Result);
END;
/
GOTO Provides The Ability To Jump Through A Program From One Place To
Another.
Syntax
GOTO LabelName;
Rules To Cross Check:
GOTO Cannot Navigate From The EXCEPTION Section To Any Other Section
of The PL/SQL Block.
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> DECLARE
V_MyNumber NUMBER := &GiveNumber;
BEGIN
IF MOD(V_MyNumber, 2) = 0 THEN
GOTO L_EVEN;
ELSE
GOTO L_ODD;
END IF;
<<L_EVEN>>
DBMS_OUTPUT.PUT_LINE('Even
Number.');
RETURN;
<<L_ODD>>
DBMS_OUTPUT.PUT_LINE('Odd
Number.');
RETURN;
END;
/
Iterations In PL/SQL
WHILE Loop.
FOR Loop.
Syntax
LOOP
Statements;
EXIT [When Condition];
END LOOP;
EXIT Statement
Once The Loop is Terminated, The Control Passes To The Next Statement
After The END LOOP.
The EXIT Statement Should Always Be Placed Inside The Loop Only.
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The EXIT Condition Can Be At The Top of The Loop OR At The End of The
Loop As Per Logical Convenience.
Depending Upon The Circumstances We Can Make Use of This LOOP As PreTested Loop OR Post-Tested Loop Construct.
But Under Major Construct it is Convenient To Use This Loop As Post Tested
Loop Construct Only.
The Loop Terminates Its Process When The Conditional State is TRUE.
SQL> DECLARE
V_Num NUMBER := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE ('The Line ' || V_Num || ' Output is ' ||
V_Num);
V_Num := V_Num + 1;
IF V_NUM > 5 THEN
EXIT;
END IF;
END LOOP;
DBMS_OUTPUT.PUT_LINE ('The Total Lines of Outputs are ' ||
(V_Num - 1));
END;
/
Nested Loops
The Outer Loop And The Inner Loop Get Associated With One Another And
Execute Simultaneously.
The Overall Loop Terminates is Dictated By The Outer Loops EXIT WHEN
Condition OR EXIT Condition.
SQL> DECLARE
V_Num NUMBER := 1;
BEGIN
LOOP
EXIT WHEN V_Num
> 10;
LOOP
EXIT WHEN V_Num > 5;
DBMS_OUTPUT.PUT_LINE('Inner Loop : ' ||
V_Num := V_Num
V_Num);
+ 1;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Outer Loop : ' ||
V_Num
:= V_Num
V_Num);
+ 1;
END LOOP;
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
END;
/
Label Loops By Placing The Label Before The Word Loop Within The Label
Delimiters.
When The Loop is Labeled, The Label Name Can Be Optionally Included After
The END LOOP Statement For Clarity.
SQL> DECLARE
V_Num NUMBER := 1;
BEGIN
<<OuterLoop>>
LOOP
<<InnerLoop>>
LOOP
EXIT WHEN V_Num > 5;
DBMS_OUTPUT.PUT_LINE('Inner Loop : ' || V_Num);
V_Num := V_Num
+ 1;
:= V_Num
+ 1;
> 10;
WHILE Loop
Syntax
WHILE Condition
LOOP
Statement1;
Statement2;
END LOOP;
If The Condition Yields NULL, The LOOP is Bypassed And Control Passes To
The Next Statement.
SQL> DECLARE
V_Number NUMBER(2) := 1;
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
V_Output VARCHAR2(100);
BEGIN
WHILE V_Number <= 5
LOOP
V_Output := V_Output ||' '||V_Number;
V_Number := V_Number + 1;
END LOOP;
DBMS_OUTPUT.PUT_LINE(V_Output);
END;
/
SQL> DECLARE
V_Num NUMBER;
V_Position NUMBER;
V_Result NUMBER := 0;
BEGIN
V_Num := &NumberToReverse;
WHILE V_Num > 0
LOOP
V_Position := MOD(V_Num, 10);
V_Result := (V_Result * 10) + V_Position;
V_Num := TRUNC(V_Num / 10);
END LOOP;
DBMS_OUTPUT.PUT_LINE('The Reverse of the Entered Number is : ');
DBMS_OUTPUT.PUT_LINE(V_Result);
END;
FOR Loop
Syntax:
FOR Counter IN [REVERSE] LowerBound..UpperBound
LOOP
Statement1;
Statement2;
END LOOP;
Counter
Reverse
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The Lower Bound And The Upper Bound of The Loop Can Be Literals,
Variables, OR Expressions, But They Should Be Evaluated To Integers.
The Lower And Upper Bounds of A Loop Statement Need Not Be Numeric
Literals, They Can Be Expressions That Covert To Numeric Values At Run
Time.
For Loops Take Their Range Itself As The Conditional Statement, Hence They
Are More Suitable When Working On Database Oriented Logic.
SQL> DECLARE
V_StartRange NUMBER := &StartRange;
V_EndRange NUMBER := &EndRange;
V_Result VARCHAR2(500) := NULL;
BEGIN
DBMS_OUTPUT.PUT_LINE('Illustration of For Loop...!');
FOR MyIndex IN V_StartRange..V_EndRange
LOOP
V_Result := V_Result||' '||V_StartRange;
V_StartRange := V_StartRange + 1;
END LOOP;
DBMS_OUTPUT.PUT_LINE(V_Result);
END;
/
SQL> DECLARE
V_NumFact NUMBER := &GiveNumber;
V_Factorial NUMBER := 1;
BEGIN
FOR IndexI IN 1..V_NumFact
LOOP
V_Factorial := V_Factorial * IndexI;
END LOOP;
DBMS_OUTPUT.PUT_LINE(' The Factorial of '||V_NumFact|| ' is :
'||V_Factorial);
END;
/
SQL> DECLARE
V_NumFact NUMBER := &GiveNumber;
V_Factorial NUMBER := 1;
BEGIN
FOR IndexI IN REVERSE 1..V_NumFact
LOOP
V_Factorial := V_Factorial * IndexI;
DBMS_OUTPUT.PUT_LINE(' The IndexI Number is
'||IndexI);
END LOOP;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
<<OuterLoop>>
FOR MyIndex IN 1..V_OuterLoopRange
LOOP
DBMS_OUTPUT.PUT_LINE('When Outer Loop Index Value =
'||MyIndex);
<<InnerLoop>>
FOR MyIndex2 IN 1..V_InnerLoopRange
LOOP
DBMS_OUTPUT.PUT_LINE('Outer Loop Index Value
='||OUTERLOOP.MyIndex||' , '||'Inner Loop Index Value =
'||MyIndex2);
END LOOP InnerLoop;
END LOOP OuterLoop;
END;
/
SQL> DECLARE
V_MyChar VARCHAR2(20);
BEGIN
<<OuterLoop>>
FOR MyIndex1 IN 1..15
LOOP
<<InnerLoop>>
FOR MyIndex2 IN 1..MyIndex1
LOOP
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
All SQL Functions Can Be Used Within The Same Syntax As That of The SQL.
The Data Manipulation Statements From SQL Can Be Used More Intelligently
in PL/SQL As We Have The Liberty of Controlling The Transactions And Data
Manipulations Using The Control Structures.
Using
The
COMMIT
And
All The Data Retrieved From The Database Server Has To Be Transferred into
The Local PL/SQL Variables Before Processing The Business Logic.
The SELECT
PL/SQL Tables.
The TABLE LIST in The FROM Clause Can Be One OR More TABLES,
VIEWS OR INLINE VIEWS.
The WHERE Clause Restricts The Result Set As Per The Condition Defined.
When Selecting A Value Into A Variable, Be Sure To Return One And Only
One Value into The Variable.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Note
SQL> DECLARE
V_Empno
NUMBER := &EnterEmpno;
V_EName
VARCHAR2(30);
V_Job
VARCHAR2(30);
V_Sal
NUMBER(7, 2);
BEGIN
SELECT
Ename, Job, Sal
INTO
V_Ename, V_Job, V_Sal
FROM EMP
WHERE Empno = V_Empno;
DBMS_OUTPUT.PUT_LINE('The Name : '||V_Ename);
DBMS_OUTPUT.PUT_LINE('The job : '||V_Job);
DBMS_OUTPUT.PUT_LINE('The Sal: '||V_Sal);
END;
/
SQL> DECLARE
V_Empno
NUMBER(4):=&EnterEmpno;
V_EName
VARCHAR2(30);
V_Sal
NUMBER(7,2);
V_Comm
NUMBER(7,2);
BEGIN
SELECT
EName, Sal, Comm
INTO V_EName, V_Sal, V_Comm
FROM EMP
WHERE Empno = V_Empno;
DBMS_OUTPUT.PUT_LINE('The Name : '||INITCAP(V_Ename));
DBMS_OUTPUT.PUT_LINE('The Salary : '||TO_CHAR(V_Sal,
'99,999.99'));
DBMS_OUTPUT.PUT_LINE('The Commission :
'||NVL(TO_CHAR(V_Comm), 'No Commission'));
DBMS_OUTPUT.PUT_LINE('The Total Sal is : '||TO_CHAR(V_Sal +
NVL(V_Comm, 0)));
END;
SQL> DECLARE
V_Empno
NUMBER(4) :=
V_Ename
VARCHAR2(30);
V_Deptno
NUMBER(2);
V_Job
VARCHAR2(30);
V_MGR
NUMBER(4);
&EnterEmpNo;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
V_HireDate DATE;
V_Sal
NUMBER(7,2);
V_Comm
NUMBER(7,2);
BEGIN
SELECT
Ename, Deptno, Job, MGR, HireDate, Sal, Comm
INTO
V_Ename, V_Deptno, V_Job, V_MGR, V_HireDate,
V_Sal, V_Comm
FROM Emp
WHERE Empno = V_Empno;
DBMS_OUTPUT.PUT_LINE('The Details of Employee Number
'||V_Empno||' Requested by You Are ...');
DBMS_OUTPUT.PUT_LINE('The Employee Name : '||V_Ename);
DBMS_OUTPUT.PUT_LINE('The Department Number : '||V_Deptno);
DBMS_OUTPUT.PUT_LINE('The Designation : '||V_Job);
DBMS_OUTPUT.PUT_LINE('The Manager Number : '||V_MGR);
DBMS_OUTPUT.PUT_LINE('The Joining Date : '||V_HireDate);
DBMS_OUTPUT.PUT_LINE('The Basic Salary : '||V_Sal);
DBMS_OUTPUT.PUT_LINE('The Commission Earned : '||V_Comm);
END;
/
SQL> DECLARE
V_Empno
NUMBER(4) := &EnterEmpNo;
V_Ename
VARCHAR2(30);
V_Deptno
NUMBER(2);
V_Job
VARCHAR2(30);
V_MGR
NUMBER(4);
V_HireDate DATE;
V_Sal
NUMBER(7,2);
V_Comm
NUMBER(7,2);
V_MGRName
VARCHAR2(30);
BEGIN
SELECT
Ename, Deptno, Job, MGR, HireDate, Sal, Comm
INTO
V_Ename , V_Deptno, V_Job, V_MGR, V_HireDate, V_Sal, V_Comm
FROM Emp
WHERE Empno = V_Empno;
IF V_MGR IS NOT NULL THEN
SELECT Ename INTO V_MGRName
FROM Emp
WHERE Empno = V_MGR;
ELSE
SELECT Ename INTO V_MGRName
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
FROM Emp
WHERE MGR IS NULL;
END IF;
DBMS_OUTPUT.PUT_LINE('The Details of Employee Number
'||V_Empno||' Requested by You Are ...');
DBMS_OUTPUT.PUT_LINE('The Employee Name :
'||INITCAP(V_Ename));
DBMS_OUTPUT.PUT_LINE('The Department Number : '||V_Deptno);
DBMS_OUTPUT.PUT_LINE('The Designation : '||INITCAP(V_Job));
DBMS_OUTPUT.PUT_LINE('The Manager Number :
'||NVL(TO_CHAR(V_MGR),'"Cannot be Managed"')||', and his Name is :
'||V_MGRName);
DBMS_OUTPUT.PUT_LINE('The Joining Date :
'||TO_CHAR(V_HireDate,'FMDD, Month Year'));
DBMS_OUTPUT.PUT_LINE('The Basic Salary : '||CONCAT('INR
',TO_CHAR(V_Sal,'99,999.99')));
DBMS_OUTPUT.PUT_LINE('The Commission Earned :
'||NVL(TO_CHAR(V_Comm),'No Commission...Sorry!'));
END;
/
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Syntax
Variablename
TableName.ColumnName%TYPE;
This Method Keeps The PL/SQL Program To Be Unaffected Even When The
Data Types Within The Database Are Changing.
Illustration
SQL> DECLARE
V_EmpNo
Emp.Empno%TYPE;
V_Ename
Emp.Ename%TYPE;
V_Sal
Emp.Sal%TYPE;
BEGIN
/*Executable Statements*/
END;
SQL> DECLARE
V_Empno
Emp.Empno%TYPE := &EnterEmpno;
V_EName
Emp.EName%TYPE;
V_Job
Emp.Job%TYPE;
V_Sal
Emp.Sal%TYPE;
BEGIN
SELECT
Ename, Job, Sal
INTO
V_Ename, V_Job, V_Sal
FROM EMP
WHERE Empno = V_Empno;
DBMS_OUTPUT.PUT_LINE('The Name : '||V_Ename);
DBMS_OUTPUT.PUT_LINE('The Job : '||V_Job);
DBMS_OUTPUT.PUT_LINE('The Sal : '||V_Sal);
END;
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
/
SQL> DECLARE
V_Empno
Emp.Empno%TYPE := &EnterEmpNo;
V_Ename
Emp.Ename%TYPE;
V_Deptno
Emp.Deptno%TYPE;
V_Job
Emp.Job%TYPE;
V_MGR
Emp.MGR%TYPE;
V_HireDate
Emp.HireDate%TYPE;
V_Sal
Emp.Sal%TYPE;
V_Comm
Emp.Comm%TYPE;
V_MGRName
Emp.Ename%TYPE;
BEGIN
SELECT Ename, Deptno, Job, MGR, HireDate, Sal, Comm INTO
V_Ename , V_Deptno, V_Job, V_MGR, V_HireDate, V_Sal, V_Comm
FROM Emp
WHERE Empno = V_Empno;
IF V_MGR IS NOT NULL THEN
SELECT Ename INTO V_MGRName
FROM Emp
WHERE Empno = V_MGR;
ELSE
SELECT Ename INTO V_MGRName
FROM Emp
WHERE MGR IS NULL;
END IF;
DBMS_OUTPUT.PUT_LINE('The Details of Employee Number
'||V_Empno||' Requested by You Are ...');
DBMS_OUTPUT.PUT_LINE('The Employee Name :
'||INITCAP(V_Ename));
DBMS_OUTPUT.PUT_LINE('The Department Number : '||V_Deptno);
DBMS_OUTPUT.PUT_LINE('The Designation : '||INITCAP(V_Job));
DBMS_OUTPUT.PUT_LINE('The Manager Number :
'||NVL(TO_CHAR(V_MGR),'"Cannot be Managed"')||' , and his Name is :
'||V_MGRName);
DBMS_OUTPUT.PUT_LINE('The Joining Date :
'||TO_CHAR(V_HireDate,'FMDD, Month Year'));
DBMS_OUTPUT.PUT_LINE('The Basic Salary : '||CONCAT('INR
',TO_CHAR(V_Sal,'99,999.99')));
DBMS_OUTPUT.PUT_LINE('The Commission Earned :
'||NVL(TO_CHAR(V_Comm),'No Commission...Sorry!'));
END;
/
%ROWTYPE.
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
NESTED TABLE.
VARRAY.
%ROWTYPE Declaration
The Fields in The Record Take Their Names And Data Types From The
Columns of The Table OR View.
The Record Can Also Store An Entire Row of Data Fetched From CURSOR
Variable.
Syntax
VariableName TableName%ROWTYPE;
Illustration
V_EmpRecord Emp%ROWTYPE;
Advantages
It is Mostly Useful When Retrieving The Data For The Entire Row With The
SELECT Statement Using Projection * Operator.
SQL> DECLARE
V_EmpRecord Emp%ROWTYPE;
BEGIN
SELECT * INTO V_EmpRecord
FROM EMP
WHERE Empno = &EnterEmpno;
DBMS_OUTPUT.PUT_LINE('The Name : '|| V_EmpRecord.Ename);
DBMS_OUTPUT.PUT_LINE('The Job : '|| V_EmpRecord.Job);
DBMS_OUTPUT.PUT_LINE('The Salary : '||V_EmpRecord.Sal);
DBMS_OUTPUT.PUT_LINE('The Commission : '|| V_EmpRecord.Comm);
DBMS_OUTPUT.PUT_LINE('The Gross Salary : ' ||(V_EmpRecord.Sal +
NVL(V_EmpRecord.Comm, 0)));
END;
/
SQL> DECLARE
EmpRecord Emp%ROWTYPE;
V_EmpRecord EmpRecord%TYPE;
BEGIN
SELECT * INTO V_EmpRecord
FROM EMP
WHERE Empno = &EnterEmpno;
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
PL/SQL Records
The DEFAULT Key Word Can Also Be Used When Defining Fields.
After The Record Data Type is Created It Should Be Instantiated, Before The
Operational Process Can Be Implemented.
Syntax
TYPE TypeName IS
RECORD
(
FieldName1,
FieldName2,
FieldNameN
);
FieldName { FieldDataType(Width) OR
RecordVariable%TYPE OR
Table.Column%TYPE OR
Table%ROWTYPE }
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
[NOT NULL]
[:=[DEFAULT] Expr]
Defining And Declaring A PL/SQL Record
Field Declarations Are Like Variable Declarations Each Field Has A Unique
Name And A Specific Data Type.
The Most Important Point To Note is We Must Create The Data Type First
And Then Declare An Identifier Using The Declared Data Type.
Illustration
DECLARE
TYPE EmpRecordType IS RECORD
(
Empno NUMBER(4) NOT NULL := 0,
Ename Emp.Ename%TYPE,
Job
Emp.Job%TYPE
);
After The RECORD Type Has Been Created, We Should Instantiate The
Individual RECORD Type Variables For Operations.
Illustration
EmpRecordInstance
EmpRecordDataType;
Syntax
RecordName.FieldName
Illustration
EmpRecord.Ename := SAMPATH;
SQL> DECLARE
V_Empno NUMBER(4) := &EnterEmpNo;
TYPE EmpRecordType IS RECORD
(
V_Ename VARCHAR2(30),
V_Deptno NUMBER(2),
V_Job
VARCHAR2(30)
);
EmpRecord EmpRecordType;
BEGIN
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
VARCHAR2(30),
Deptno
Job
NUMBER(2),
VARCHAR2(30),
MGR
NUMBER(4),
HireDate DATE,
Sal
NUMBER(7,2),
Comm
NUMBER(7,2)
);
EmpRecord EmpRecordType;
BEGIN
SELECT
Ename,
Deptno,
Job, MGR,
HireDate,
Sal,
Comm
INTO
EmpRecord.Ename ,
EmpRecord.Deptno,
EmpRecord.Job,
EmpRecord.MGR,
EmpRecord.HireDate,
EmpRecord.Sal,
EmpRecord.Comm
FROM Emp
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Illustration1
Atomic Type Collection
TYPE AtomicTypesRec IS RECORD
(
Empno
Emp.Empno%TYPE,
MgrName
Emp.Ename%TYPE
);
Nested Type Collection
TYPE AllTablesRecord IS RECORD
(
EmpRecord
Emp%ROWTYPE,
DeptRecord
Dept%ROWTYPE,
SalGrRecord SalGrade%ROWTYPE,
AtomicType
AtomicTypesRec
);
Type Instantiation
V_AllTablesRecord AllTablesRecord;
Illustration2
Employee Type Creation
TYPE EmpRecordType IS RECORD
(
Ename
Emp.Ename%TYPE,
Deptno
Emp.Deptno%TYPE,
Job
Emp.Job%TYPE,
MGR
Emp.MGR%TYPE,
HireDate
Emp.HireDate%TYPE,
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Sal
Emp.Sal%TYPE,
Comm
Emp.Comm%TYPE
);
Department Type Creation
TYPE DeptRecordType IS RECORD
(
Deptno
Dept.Deptno%TYPE,
Dname
Dept.Deptno%TYPE,
Loc
Dept.Deptno%TYPE
);
Sal Grade Type Creation
TYPE SalGradeRecordType IS RECORD
(
Grade
SalGrade.Grade%TYPE,
LoSal
SalGrade.LoSal%TYPE,
HiSal
SalGrade.HiSal%TYPE
);
Integrating All Types As One Collection
TYPE AllTablesRecord IS RECORD
(
EmpRecord
EmpRecordType,
DeptRecord
DeptRecordType,
SalGradeRecord
SalGradeRecordType
);
Instantiating The Final Collection For Usage
V_AllTablesRecord AllTablesRecord;
Illustration3
Employee Type Creation
TYPE EmpRecordType IS RECORD
(
Ename
Emp.Ename%TYPE,
Deptno
Emp.Deptno%TYPE,
Job
Emp.Job%TYPE,
MGR
Emp.MGR%TYPE,
HireDate
Emp.HireDate%TYPE,
Sal
Emp.Sal%TYPE,
Comm
Emp.Comm%TYPE
);
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Illustrative Example
SQL> DECLARE
TYPE AtomicTypes IS RECORD /*Atomic Type Creation*/
(
Empno Emp.Empno%TYPE,
MgrName Emp.Ename%TYPE
);
TYPE AllTablesRecord IS RECORD /*Nested Type Creation*/
(
EmpRecord Emp%ROWTYPE,
DeptRecord Dept%ROWTYPE,
SalGradeRecord SalGrade%ROWTYPE,
AtomicType AtomicTypes /*Type Instance in Another Type*/
);
V_AllTablesRecord AllTablesRecord; /*Type Instantiation*/
BEGIN
V_AllTablesRecord.AtomicType.Empno := &EnterEmpno;
SELECT
Ename,
Deptno,
Job,
MGR,
HireDate,
Sal,
Comm
INTO
V_AllTablesRecord.Emprecord.Ename ,
V_AllTablesRecord.Emprecord.Deptno,
V_AllTablesRecord.Emprecord.Job,
V_AllTablesRecord.Emprecord.MGR,
V_AllTablesRecord.Emprecord.HireDate,
V_AllTablesRecord.Emprecord.Sal,
V_AllTablesRecord.Emprecord.Comm
FROM Emp
WHERE Empno = V_AllTablesRecord.AtomicType.Empno;
SELECT
Dname,
Loc
INTO
V_AllTablesRecord.DeptRecord.Dname,
V_AllTablesRecord.DeptRecord.Loc
FROM Dept
WHERE Deptno = V_AllTablesRecord.Emprecord.Deptno;
SELECT
Grade
INTO
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
V_AllTablesRecord.SalGradeRecord.Grade
FROM SalGrade
WHERE V_AllTablesRecord.Emprecord.Sal
BETWEEN LoSal AND HiSal;
IF V_AllTablesRecord.Emprecord.MGR IS NOT NULL THEN
SELECT
Ename
INTO
V_AllTablesRecord.AtomicType.MgrName
FROM Emp
WHERE Empno = V_AllTablesRecord.Emprecord.MGR;
ELSE
SELECT
Ename
INTO
V_AllTablesRecord.AtomicType.MgrName
FROM Emp
WHERE MGR IS NULL;
END IF;
DBMS_OUTPUT.PUT_LINE('The Details of Employee Number
'||V_AllTablesRecord.AtomicType.Empno||' Requested by You Are ...');
DBMS_OUTPUT.PUT_LINE('The Employee Name :
'||V_AllTablesRecord.Emprecord.Ename);
DBMS_OUTPUT.PUT_LINE('The Department Number :
'||V_AllTablesRecord.Emprecord.Deptno||', Department Name is
'||INITCAP(V_AllTablesRecord.DeptRecord.Dname)||', and is Situated at
'||INITCAP(V_AllTablesRecord.DeptRecord.Loc));
DBMS_OUTPUT.PUT_LINE('The Designation :
'||V_AllTablesRecord.Emprecord.Job);
DBMS_OUTPUT.PUT_LINE('The Manager Number :
'||NVL(TO_CHAR(V_AllTablesRecord.Emprecord.MGR),'"Cannot be
Managed"')||', and his Name is :
'||V_AllTablesRecord.AtomicType.MgrName);
DBMS_OUTPUT.PUT_LINE('The Joining Date :
'||V_AllTablesRecord.Emprecord.HireDate);
DBMS_OUTPUT.PUT_LINE('The Basic Salary : '||CONCAT('INR
',TO_CHAR(V_AllTablesRecord.Emprecord.Sal,'99,999.99'))||' and his
Grade as Per Salary is '||V_AllTablesRecord.SalGradeRecord.Grade);
DBMS_OUTPUT.PUT_LINE('The Commission Earned :
'||NVL(TO_CHAR(V_AllTablesRecord.Emprecord.Comm),'No
Commission...Sorry!'));
END;
/
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
PL/SQL Tables
PL/SQL TABLES Use A PRIMARY KEY To Give Array Like Access To Rows.
Things To Note
Syntax
TYPE TypeName IS
TABLE OF
{Column Type OR Variable%TYPE OR Table.Column%TYPE OR
Table%ROWTYPE} [NOT NULL]
INDEX BY BINARY_INTEGER;
PLSQLTableInstance TypeName;
Illustration
Primary Key
Emp.Ename%TYPE
KING
BLAKE
CLARK
JONES
ADAMS
SMITH
Binary Integer
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
TYPE EnameTableType
IS
TABLE OF
Emp.Ename%TYPE
INDEX BY BINARY_INTEGER;
EnameTable
EnameTableType;
PL/SQL Tables Can Have One Column For data Storage And A Primary Key
For Index Management, Neither of Which Can Be Named.
The Data Column Can Belong To Any Scalar OR Record Data Type, But The
PRIMARY KEY Must Belong To Type BINARY_INTEGER Only.
The Primary Key Value Can Be Negative Indexing Need Not Start With 1.
EXISTS(N)
COUNT
PRIOR(N)
Returns The Index Number That Precedes Index N In A PL/SQL
Table.
NEXT(N)
EXTEND(N.I)
EXTEND(N)
EXTEND(N, i)
TRIM
TRIM(N)
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
DELETE
TableName(Index).Field
SQL> DECLARE
TYPE Dept_Table_Type
IS
TABLE OF
Dept.Dname%TYPE
INDEX BY BINARY_INTEGER;
My_Dept_Table Dept_Table_Type;
V_Count
NUMBER(2);
BEGIN
SELECT COUNT(*)
INTO V_Count
FROM Dept;
FOR MyIndex IN 1..V_Count LOOP
SELECT Dname
INTO My_Dept_Table(MyIndex)
FROM Dept
WHERE Deptno = MyIndex * 10;
END LOOP;
FOR MYIndex IN
1..V_Count LOOP
DBMS_OUTPUT.PUT_LINE(My_Dept_Table(MyIndex));
END LOOP;
END;
/
SQL> DECLARE
TYPE Dept_Table_Type
IS
TABLE OF
Dept%ROWTYPE
INDEX BY
BINARY_INTEGER;
My_Dept_Table
V_Count
Dept_Table_Type;
NUMBER(2);
BEGIN
SELECT COUNT(*)
INTO V_Count
FROM
Dept;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
FROM Dept
WHERE
END
LOOP;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
END;
/
SQL> DECLARE
TYPE Dept_Table_Type IS TABLE OF Dept.Dname%TYPE
INDEX BY BINARY_INTEGER;
My_Dept_Table Dept_Table_Type;
V_Count
NUMBER(2);
V_RecNo
NUMBER(2) := &EnterRecordNumber;
BEGIN
SELECT COUNT(*)
INTO V_Count
FROM Dept;
FOR MyIndex IN 1..V_Count LOOP
SELECT Dname
INTO My_Dept_Table(MyIndex)
FROM Dept
WHERE Deptno = MyIndex * 10;
END LOOP;
FOR MYIndex IN
1..V_Count LOOP
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The Data in The Database is Manipulated Using The DML Commands From
PL/SQL.
The DML Commands INSERT, UPDATE And DELETE Can Be Used in PL/SQL
Without Any Restrictions.
The ROW LOCKS And TABLE LOCKS in The Database Are Released Using The
COMMIT And ROLLBACK Statements.
Inserting Data
The SQL INSERT Statement is Used As it Exists, in The PL/SQL Block For
Data Insertion Standards.
We Can Use All The Required SQL Built-in Functions, Like SYSDATE As Per
Requirements.
The PRIMARY
SEQUENCES.
KEY
Values
Can
Be
Generated
Using
The
Database
SQL> BEGIN
INSERT INTO
Emp(Empno, Ename, Deptno, Job, MGR, HireDate, Sal, Comm)
VALUES(
EmpSequence.NEXTVAL,
SATISH,
10,
MANAGER,
7839,
22-NOV-1998,
4500,
NULL
);
COMMIT;
END;
/
SQL> DECLARE
V_Empno NUMBER(4) := &EnterEmpNo;
V_Ename VARCHAR2(15) := '&EnterEname';
V_Deptno NUMBER(2) := &EnterDepto;
V_Job VARCHAR2(15) := '&EnterJob';
V_MGR NUMBER := &EnterMGRNo;
V_HireDate Emp.HireDate%TYPE := '&EnterHireDate';
V_Sal Emp.Sal%TYPE := &EnterSal;
V_Comm Emp.Comm%TYPE := &EnterComm;
BEGIN
INSERT INTO
Emp(Empno, Ename, Deptno, Job, MGR, HireDate, Sal, Comm)
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
VALUES(
V_Empno,
V_Ename,
V_Deptno,
V_Job,
V_MGR,
V_HireDate,
V_Sal,
V_Comm
);
COMMIT;
END;
/
Updating Data
The Data Updation is Also Similar To The UPDATE Statements Used In SQL.
A Small Amount of Ambiguity Can Arise in The SET Clause of The UPDATE
Statement, As The Identifier on The Right Side of The Assignment Operator
Can Be A PL/SQL Variable, OR Another Database Column Also.
In The Set Clause, The Identifier on The Left is Always A Database Column.
SQL> DECLARE
V_SalRaise Emp.Sal%TYPE := 3500;
BEGIN
UPDATE Emp
SET Sal = Sal + V_SalRaise
WHERE Job = 'ANALYST';
END;
SQL> DECLARE
V_JobChng Emp.Job%TYPE := UPPER(&GiveJob);
V_Empno
Emp.Empno%TYPE := &GiveEmpno;
BEGIN
UPDATE Emp
SET
Job = V_JobChng
WHERE Empno = V_Empno;
END;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Deleting Data
Points To Note
The Child And Parent Relations Should Be Cross Checked While Deletion
Takes Place, To Avoid Orphan Records Generation.
SQL> DECLARE
V_Deptno Emp.Deptno%TYPE := 30;
BEGIN
DELETE FROM Emp
WHERE Deptno = V_Deptno;
END;
SQL> DECLARE
V_Deptno Dept.Deptno%TYPE := 40;
BEGIN
DELETE FROM Dept
WHERE Deptno = V_Deptno;
END;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Every Query Contains An ACTIVE SET, Which Refers To The Rows That Will
Be Returned By The Query.
CURSOR Definition
CURSOR Usage
Using A CURSOR, The PL/SQL Program Can Control The CONTEXT AREA, As
The SQL Statement is Being Processed.
CURSOR Features
Cursor Types
Implicit Cursors
Explicit Cursors
Implicit Cursors
Explicit Cursor
This Cursor is Declared Within The PL/SQL Block, And Allows Sequential
Process of Each Row of The Returned Data From Database.
Implicit Cursors
All UPDATE And DELETE Statements Have Cursors That Identify The Set
of Rows That Will Be Affected By The Operations.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Cursor Attributes
%ISOPEN
%NOTFOUND
%FOUND
%ROWCOUNT
The Attributes Return Information About The Execution Status of The Data
Manipulation Statement Through CURSOR.
%ISOPEN
%NOTFOUND
Evaluates To TRUE If The Most Recent Fetch Does Not Return A Row Else
Evaluates To FALSE.
%FOUND
Evaluates To TRUE If The Most Recent Fetch Returns A Row Else Evaluates
To FALSE.
%ROWCOUNT
Returns A Number.
SQL> DECLARE
V_Deptno Emp.Deptno%TYPE := &DepartmentNumber;
BEGIN
UPDATE Emp
SET Sal = 1500
WHERE Deptno = V_Deptno;
DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT||' Rows were Updated.');
IF SQL%NOTFOUND
THEN
DBMS_OUTPUT.PUT_LINE('Data Not Found... Updation Abruptly
Terminated.');
END IF;
END;
/
As The Records Are Retrieved Into Memory At The Time The Cursor Is
Opened, The Data Throughout The Transaction Has A Consistent View.
After A Cursor is Opened, The New OR Changed Data is Not Reflected In The
Cursor Result Set.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> DECLARE
V_Deptno Emp.Deptno%TYPE := &DeptNumber;
BEGIN
DELETE FROM Emp
WHERE Deptno = V_Deptno ;
DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT||' Row(s) Affected.');
IF SQL%NOTFOUND
THEN
DBMS_OUTPUT.PUT_LINE('Data Not Found... Deletion Abruptly
Terminated.');
END IF;
END;
/
Explicit Cursor
Advantages
Explicit Cursors Are Designed To Work With SELECT Statements That Return
More Than One Record At A Time.
Cursor Declaration.
CURSOR Opening.
CURSOR Fetching.
CURSOR Closing.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Illustration1
SQL> DECLARE
V_Deptno Dept.Deptno%TYPE := &Deptno;
CURSOR EDeptCursor
IS
SELECT Empno, Ename, Deptno, Sal, Job
FROM Emp
WHERE Deptno = V_Deptno;
BEGIN
OPEN EDeptCursor;
Place Required FETCH Statements;
CLOSE EDeptCursor;
END;
Illustration2
SQL> DECLARE
CURSOR EmpDetailsCursor
IS
SELECT Empno, Ename, D.Deptno, Dname
FROM Emp E, Dept D
WHERE E.Deptno = D.Deptno;
V_EmpDept EmpDetailsCursor%ROWTYPE;
BEGIN
OPEN EmpDetailsCursor;
Place Required FETCH Statements;
CLOSE EmpDetailsCursor;
END;
Cursor Declaration
Syntax
CURSOR CursorName{parameter List}
[RETURN ReturnType]
IS Query
[FOR UPDATE[OF(ColumnList)]
[NOWAIT]];
Parameter List is Optional And Can Be Any Valid Parameter Used For Query
Execution.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The FOR UPDATE Clause LOCKS The Records When The Cursor is Opened,
And Maintains The Status of The Cursor As READ ONLY.
Illustration1
SQL> DECLARE
CURSOR EmpCursor
IS
SELECT Ename, Sal, Job
FROM Emp
WHERE Deptno = 10;
Illustration2
SQL> DECLARE
CURSOR EmpCursor(V_EmpDept NUMBER)
IS
SELECT Ename, Sal, Job
FROM Emp
WHERE Deptno = V_EmpDept;
Opening The Cursor
Any Cursor Can Be Opened Only Once in The PL/SQL Module, Second Time
Opening of The Cursor Raises An Exception.
Syntax
OPEN CursorName[(Parameter Values)];
Illustration1
1. OPEN EmpCursor;
2. OPEN EmpCursor(20);
Things To Note When Cursor is Opened
On The Opening of The Cursor, The Active Record Set is The First One
Returned By The Cursors Query.
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
OPEN Cursor
Active Record Set
To First Row
Actual Table
Row1
Row2
Row3
Row4
Row5
Row6
Row7
Evaluate
Binds
CURSOR
SELECT
Context Area
Row1
Row3
Row6
FETCH Retrievers Records From The CONTEXT AREA Into A Variable Such
That The Variable Can Be Used For Business Logic.
The FETCH Command Operates On The Current Record Only And Processes
Through The Result Set One Record At A Time.
Syntax
FETCH CursorName INTO VariableName(s) OR PL/SQL_RECORD;
Illustration
FETCH EmpCursor INTO V_EmpRecord;
Closing The Cursor
The Explicit Cursor Should Be Closed, Else It May Lead To Memory Leak.
Syntax
CLOSE CursorName;
Illustration
SQL> DECLARE
V_Ename EMP.ENAME%TYPE;
V_Sal EMP.SAL%TYPE;
CURSOR MyCursor IS
SELECT Ename, Sal
FROM EMP;
BEGIN
OPEN MyCursor;
FETCH MyCursor INTO V_Ename, V_Sal;
DBMS_OUTPUT.PUT_LINE(V_Ename||' Salary is $ '||V_Sal);
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Note
After All Bind Variables Are Declared Declare The Required Cursor.
The Cursor Attributes That Are Implemented Upon The Implicit Cursor Can
Be Used As They Exit Along With Some Additional Attributes
%BULK_EXCEPTIONS
The Attribute is Used For ARRAY OR BULK COLLECT Operations Done in OLAP
Applications.
%BULK_ROWCOUNT
Cursor Loops
Within The Loop Each Record in The Active Set is Retrieved And Used.
Each Loop Iteration Advances The Cursor Pointer By One Record in The
Active Set.
Points To Note
The Loop Can Be Implemented As Pre Tested And Post Tested Loop.
Before The Attribute Can Be Implemented The Context Area Status Han To
Be Maintained With Minimum One Record of Fetching.
With
Proper
Cursor
Attribute
Operating
on
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> DECLARE
CURSOR EmpCursor
IS
SELECT *
FROM Emp;
V_EmpData EmpCursor%ROWTYPE;
BEGIN
OPEN EmpCursor;
LOOP
FETCH EmpCursor INTO V_EmpData;
EXIT WHEN EmpCursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(V_EmpData.Ename);
END LOOP;
CLOSE EmpCursor;
END;
/
SQL> DECLARE
CURSOR EmpCursor IS
SELECT * FROM Emp;
V_EmpData EmpCursor%ROWTYPE;
BEGIN
OPEN EmpCursor;
LOOP
FETCH EmpCursor INTO V_EmpData;
DBMS_OUTPUT.PUT_LINE('Record Number :
'||EmpCursor%ROWCOUNT||' '||V_EmpData.Ename);
EXIT WHEN EmpCursor%NOTFOUND;
END LOOP;
CLOSE EmpCursor;
END;
/
SQL> DECLARE
CURSOR EmpCursor IS
SELECT * FROM Emp;
V_EmpData EmpCursor%ROWTYPE;
BEGIN
OPEN EmpCursor;
DBMS_OUTPUT.PUT_LINE('The Details of Employees in Your
Organization are as Follows');
DBMS_OUTPUT.PUT_LINE('--------------------------------------------------------------');
DBMS_OUTPUT.PUT_LINE('
Salary '||' Annual Salary
DBMS_OUTPUT.PUT_LINE('
'||' --------------- ');
Name
'||' Designation
'||'
Basic
');
------
'||' -------------
'||'
------------
LOOP
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Within The Loop Each Record in The Active Set is Retrieved And Used.
Each Loop Iteration Advances The Cursor Pointer By One Record in The
Active Set.
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The Loop Depends on Minimum One TRUE State To Commence And Minimum
One Condition To Terminate.
The Loop Needs One FETCH Before The Loop To Make it To Commence, And
One FETCH Inside The Loop To Keep it in Processing State.
SQL> DECLARE
CURSOR EmpCursor IS
SELECT * FROM Emp;
V_EmpData EmpCursor%ROWTYPE;
BEGIN
OPEN EmpCursor;
FETCH EmpCursor INTO V_EmpData;
WHILE EmpCursor%FOUND
LOOP
DBMS_OUTPUT.PUT_LINE(V_EmpData.Ename);
FETCH EmpCursor INTO V_EmpData;
END LOOP;
CLOSE EmpCursor;
END;
/
SQL> DECLARE
CURSOR EmpCursor IS
SELECT * FROM Emp;
V_EmpData EmpCursor%ROWTYPE;
BEGIN
OPEN EmpCursor;
FETCH EmpCursor INTO V_EmpData;
WHILE EmpCursor%FOUND
LOOP
DBMS_OUTPUT.PUT_LINE('Record Number :
'||EmpCursor%ROWCOUNT||' '||V_EmpData.Ename);
FETCH EmpCursor INTO V_EmpData;
END LOOP;
CLOSE EmpCursor;
END;
/
Within The Loop Each Record in The Active Set is Retrieved And Used.
Each Loop Iteration Advances The Cursor Pointer By One Record in The
Active Set.
The Loop is Very Useful When Traveling The Entire Data in The Database
Table.
It is More Dynamic in Operation Than The Simple Loop And Basic Loop.
Most Applications Are Implemented in Real Time Using The FOR LOOP
Concept.
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
While Using A FOR LOOP, The Cursor Does Not Require Explicit OPEN,
FETCH, And CLOSE.
The INDEX Variable Within The FOR LOOP Need Not Be Explicitly Declared.
The Cursor For Loops Make The Program More Compact And Simple in
Representation.
If Proper Care is Not Taken in Implementing The Cursor Attributes, The Loop
Can Be Confusional.
The Loop Range is Associated With Proper Cursor Attributes, To Keep The
Loop in Finite State.
SQL> DECLARE
CURSOR EmpCursor IS
SELECT * FROM Emp;
V_EmpData EmpCursor%ROWTYPE;
BEGIN
FOR V_EmpData IN EmpCursor
LOOP
DBMS_OUTPUT.PUT_LINE(V_EmpData.Ename);
END LOOP;
END;
/
SQL> DECLARE
CURSOR EmpCursor IS
SELECT * FROM Emp;
BEGIN
FOR EmpCursorIndex IN EmpCursor
LOOP
DBMS_OUTPUT.PUT_LINE('Record Number :
'||EmpCursor%ROWCOUNT||' '||EmpCursorIndex.Ename);
END LOOP;
END;
/
SQL> DECLARE
CURSOR EmpCursor IS
SELECT * FROM Emp
ORDER BY Sal DESC;
BEGIN
FOR V_EmpData IN EmpCursor
LOOP
DBMS_OUTPUT.PUT_LINE('Rank No : '||EmpCursor%ROWCOUNT||'
'||V_EmpData.Ename||' With Salary of '||V_EmpData.Sal);
EXIT WHEN EmpCursor%ROWCOUNT = 5;
END LOOP;
END;
/
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
In This Case The Sub Query is Embedded Into The FOR LOOP.
SQL> DECLARE
V_Dname Dept.Dname%TYPE;
V_Loc Dept.Loc%TYPE;
BEGIN
FOR EmpRecord IN (SELECT Ename, Deptno
FROM Emp
ORDER BY Deptno
)
LOOP
SELECT
Dname,
Loc
INTO
V_Dname,
V_Loc
FROM Dept
WHERE Deptno = EmpRecord.Deptno;
DBMS_OUTPUT.PUT_LINE(EmpRecord.Ename||
||EmpRecord.Deptno|| ||V_Dname|| ||V_Loc);
END LOOP;
END;
SQL> BEGIN
DBMS_OUTPUT.PUT_LINE('The Departments Available in Our
Organization Are...');
FOR DeptRecord IN (SELECT *
FROM Dept
)
LOOP
DBMS_OUTPUT.PUT_LINE('Department '||DeptRecord.Deptno||'
Named '||DeptRecord.Dname||' Located At '||DeptRecord.Loc);
END LOOP;
END;
/
SQL> DECLARE
V_EmpCount
NUMBER(2);
V_SumInvest
NUMBER(7);
V_AvgInvest
NUMBER(7, 2);
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
BEGIN
DBMS_OUTPUT.PUT_LINE('The Departments Available in Our
Organization Are...');
FOR DeptRecord IN (SELECT *
FROM Dept
)
LOOP
SELECT
COUNT(*),
SUM(Sal),
AVG(Sal)
INTO
V_EmpCount,
V_SumInvest,
V_AvgInvest
FROM Emp
WHERE Deptno = DeptRecord.Deptno;
DBMS_OUTPUT.PUT_LINE('Department '||DeptRecord.Deptno||' Named
'||DeptRecord.Dname||' Located At '||DeptRecord.Loc||' With
'||V_EmpCount||' Employees '||' Invested With '||NVL(V_SumInvest,
0)||' Averaging '||NVL(V_AvgInvest, 0));
END LOOP;
END;
/
SQL> DECLARE
V_Empno Emp.Empno%TYPe;
V_Ename Emp.Ename%TYPE;
V_Sal Emp.Sal%TYPE;
V_Desig Emp.Job%TYPE;
CURSOR EmpCursor
IS
SELECT Empno, Ename, Sal, Job
FROM Emp;
BEGIN
IF NOT EmpCursor%ISOPEN THEN
OPEN EmpCursor;
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
END IF;
LOOP
FETCH EmpCursor
INTO V_Empno, V_Ename, V_Sal, V_Desig;
EXIT WHEN
EmpCursor%ROWCOUNT > 10 OR EmpCursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Row Number : '||EmpCursor%ROWCOUNT||'
'||RPAD(V_Empno, 12)||RPAD(V_Ename, 12)||RPAD(V_Desig,
12)||LPAD(V_Sal, 10));
END LOOP;
CLOSE EmpCursor;
END;
/
Cursors In Real Time Practice Are Used To Handle Business Logic More
Effectively.
The Data Fetched From One Table Can Be Used For Validation Purpose,
Before Transacting On Another Table.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
VALUES(V_Ename, V_Sal);
FETCH EmpCursor INTO V_Ename, V_Sal;
END LOOP;
CLOSE EmpCursor;
COMMIT;
END;
/
SQL> CREATE TABLE BigHeads1
(
Ename VARCHAR(20),
Salary NUMBER(6)
);
SQL> DECLARE
V_Number NUMBER(2) := &GiveNumber;
V_Ename Emp.Ename%TYPE;
V_CurrentSal Emp.Sal%TYPE;
V_LastSal Emp.Sal%TYPE;
V_Job Emp.Job%TYPE;
CURSOR EmpCursor
IS
SELECT Ename, Sal, Job
FROM Emp
WHERE Sal IS NOT NULL
ORDER BY Sal DESC;
BEGIN
DELETE BigHeads1;
COMMIT;
OPEN EmpCursor;
FETCH EmpCursor INTO V_Ename, V_CurrentSal, V_Job;
WHILE EmpCursor%ROWCOUNT <= V_Number AND
EmpCursor%FOUND
LOOP
INSERT INTO
BigHeads1(Ename, Salary)
VALUES(V_Ename, V_CurrentSal);
V_LastSal := V_CurrentSal;
FETCH EmpCursor INTO V_Ename, V_CurrentSal, V_Job;
IF V_LastSal = V_CurrentSal THEN
V_Number := V_Number + 1;
END IF;
END LOOP;
CLOSE EmpCursor;
COMMIT;
END;
/
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Syntax
CURSOR CursorName(ParameterName Datatype,.)
IS
SELECT Statement;
Illustration
SQL> DECLARE
CURSOR EmpCursor(
PDeptno NUMBER,
PDesig VARCHAR2
)
IS
SELECT Empno, Job
FROM Emp
WHERE Deptno = PDeptno AND Job = PDesig;
Methods of Opening A Parametric Cursor:
1. Open Empcursor(20, CLERK);
2. DECLARE
V_EmpJob Emp.Job%TYPE := &GiveJob;
BEGIN
OPEN(10, V_EmpJob);
3. DECLARE
V_EmpJob Emp.Job%TYPE := &GiveJob;
V_EmpDept Emp.DeptNo%TYPE := &GD;
BEGIN
OPEN(V_EmpDept, V_EmpJob);
4. DECLARE
CURSOR EmpCursor(
PDeptno NUMBER,
PDesig VARCHAR2
)
IS
SELECT Empno, Job
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
FROM Emp
WHERE Deptno = PDeptno AND Job = PDesig;
BEGIN
FOR EmpRecord IN
EmpCursor(10, ANALYST)
LOOP
Points To Note
The Concept
Repeatedly.
is
More
Useful
When
The
Same
Cursor
is
Must
Have
Referenced
The Values That Are Fetched By One Cursor Can Be Passed As Parameters To
The Other Cursor And Make The Programming More Dynamic.
In This Case The Data Fetched By The Outer Cursor Are Used As Parameters
By The Inner Cursor For Business Validation OR Transaction.
SQL> DECLARE
CURSOR DeptCursor
IS
SELECT Deptno, Dname
FROM Dept
ORDER BY Deptno;
CURSOR EmpCursor(V_Deptno Emp.Deptno%TYPE)
IS
SELECT Ename, Job, HireDate, Sal
FROM Emp
WHERE Deptno = V_Deptno;
V_CurrDeptno Dept.Deptno%TYPE;
V_CurrDname Dept.Dname%TYPE;
V_Ename Emp.Ename%TYPE;
V_Job Emp.Job%TYPE;
V_Mgr Emp.MGR%TYPE;
V_HireDate Emp.HireDate%TYPE;
V_Sal Emp.Sal%TYPE;
BEGIN
OPEN DeptCursor;
LOOP
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
END LOOP;
DBMS_OUTPUT.PUT_LINE ('The Investment on Department
'||V_Deptno||' is '||TO_CHAR(SUMAmount));
CLOSE MyCursor;
END;
BEGIN
SUMAmount := 0;
V_DeptNo := 20;
OPEN MyCursor(V_Deptno);
LOOP
FETCH MyCursor INTO V_MyCursor;
EXIT WHEN MyCursor%NOTFOUND;
SUMAmount := SUMAmount + V_MyCursor.Sal;
END LOOP;
DBMS_OUTPUT.PUT_LINE ('The Investment on Department
'||V_Deptno||' is '||TO_CHAR(SUMAmount));
CLOSE MyCursor;
END;
BEGIN
SUMAmount := 0;
V_DeptNo := 30;
OPEN MyCursor(V_Deptno);
LOOP
FETCH MyCursor INTO V_MyCursor;
EXIT WHEN MyCursor%NOTFOUND;
SUMAmount := SUMAmount + V_MyCursor.Sal;
END LOOP;
DBMS_OUTPUT.PUT_LINE ('The Investment on Department
'||V_Deptno||' is '||TO_CHAR(SUMAmount));
CLOSE MyCursor;
END;
END;
/
Many Times While Working in Real Time We Have To LOCK Rows During
Data UPDATION And Data DELETIONS.
The FOR UPDATE Clause in The Cursor Query is Used To LOCK The Affected
Rows While The Cursor is Opened.
When FOR UPDATE Clause is Used We Need Not Use COMMIT As Oracle
Server Releases LOCKS At The End of Each Transaction Automatically.
The FOR UPDATE Cursors Are Compulsory While Operating With Real Time
Data Updations And Deletions in Client Server Architecture.
Syntax
CURSOR CursorName IS
SELECT
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
FROM
FOR UPDATE [OF ColumnReference] [NOWAIT];
The FOR UPDATE Clause is The Last Clause in The SELECT Statement.
If The ORACLE SERVER Cannot Acquire The LOCKS on The Rows Then It
Needs To Wait Indefinitely IF NOWAIT Clause is Not Used.
Illustration
SQL> DECLARE
CURSOR EmpCursor IS
SELECT EmpNo, EName, Sal FROM Emp
WHERE DeptNo = 30
FOR UPDATE OF Sal NOWAIT;
The WHERE CURRENT OF Clause:
The Clause Allows To Apply UPDATES And DELETES To The Row Currently
Being Addressed By The Cursor, Without The Need To Explicitly Reference
ROWID From The SQL Architecture.
We Must Include The FOR UPDATE Clause in The Cursor Query, Such That
The Rows Are LOCKED Upon Opening The Cursor.
Syntax
{UPDATE OR DELETE Statement}
WHERE CURRENT OF CursorName;
SQL> DECLARE
CURSOR SalCursor
IS
SELECT Sal
FROM Emp
WHERE Deptno = 30
FOR UPDATE OF Sal NOWAIT;
BEGIN
FOR EmpRec IN SalCursor
LOOP
UPDATE Emp
SET
Sal = Sal + (EmpRec.Sal * 1.10)
WHERE CURRENT OF SalCursor;
END LOOP;
COMMIT;
END;
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
/
SQL> DECLARE
V_FromSal Emp.Sal%TYPE;
V_ToSal Emp.Sal%TYPE;
V_CurrentRow ROWID;
CURSOR SalCursor
IS
SELECT ROWID, Ename, Sal
FROM Emp
WHERE Deptno = 30
FOR UPDATE OF Sal NOWAIT;
V_EmpRec SalCursor%ROWTYPE;
BEGIN
OPEN SalCursor;
LOOP
FETCH SalCursor INTO V_EmpRec;
EXIT WHEN SalCursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('The Salary for Update is '||V_EmpRec.Sal||'
of '||V_EmpRec.Ename||'.');
V_FromSal := V_EmpRec.Sal;
V_CurrentRow := V_EmpRec.ROWID;
UPDATE Emp
SET
Sal = Sal + (V_EmpRec.Sal * 1.10)
WHERE CURRENT OF SalCursor;
SELECT Sal INTO V_ToSal
FROM Emp WHERE ROWID = V_CurrentRow;
DBMS_OUTPUT.PUT_LINE('The Updated Salary Value is from
'||V_FromSal||' To '||V_ToSal ||' Confirm The Update Before it is
Committed.');
END LOOP;
END;
/
SQL> CREATE TABLE MyEmp
AS
SELECT * FROM Emp;
SQL> DECLARE
CURSOR SalCursor
IS
SELECT ROWID, Sal
FROM MyEmp
WHERE Deptno = 30
FOR UPDATE OF Sal NOWAIT;
BEGIN
FOR EmpRec IN SalCursor
LOOP
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The Sub Query When Evaluated Can Provide A Value On A Set of Values To
The Statement.
SQL> DECLARE
V_Deptno Dept.Deptno%TYPE;
V_Dname Dept.DnaME%TYPE;
V_Staff NUMBER(4);
CURSOR StaffCountCursor IS
SELECT T1.Deptno, T1.Dname, T2.Staff
FROM Dept T1, (SELECT Deptno, COUNT(*) Staff
FROM Emp
GROUP BY Deptno) T2
WHERE T1.Deptno = T2.Deptno AND T2.Staff >= 5;
BEGIN
OPEN StaffCountCursor;
LOOP
FETCH StaffCountCursor
INTO V_Deptno, V_Dname, V_Staff;
EXIT WHEN StaffCountCursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(V_Deptno||' '||V_Dname||' '||V_Staff);
END LOOP;
CLOSE StaffCountCursor;
END;
/
Cursor Variables
We Can Use Cursor Variables To More Easily Retrieve Rows in A Result Set
From Client And Server Programs.
Cursor Variables on A Strong REF CURSOR Can Associate With Queries With
Result Sets That Match The Number And Data Type of The Record Structure.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Cursor Variables Declared From Weak REF Cursors Can Be Associated With
Any Query At Runtime.
Example 1
TYPE EmpCursorType
IS REF CURSOR
RETURN Emp%ROWTYPE;
Employee_Cur
EmpCursorType;
Example 2
TYPE Any_CursorType
IS REF CURSOR;
FETCH And CLOSE of a Cursor Variable Uses The Same Syntax As For Explicit
Cursors.
We Cannot Use RPCS To Pass Cursor Variables From One Server To Another.
Cursor Variables Cannot Be Used With The Dynamic SQL Built-in Package
DBMS_SQL.
SQL> DECLARE
TYPE EmpRefCurso
IS REF CURSOR;
V_EmpRefCursor EmpRefCursor;
V_Ename Emp.Ename%TYPE;
BEGIN
OPEN V_EmpRefCursor
FOR
SELECT Ename FROM Emp;
LOOP
FETCH V_EmpRefCursor INTO V_Ename;
EXIT WHEN V_EmpRefCursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Employee Number
'||TO_CHAR(V_EmpRefCursor%ROWCOUNT, '09')||' : '||V_Ename);
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
END LOOP;
CLOSE V_EmpRefCursor;
END;
/
SQL> DECLARE
V_RowCount NUMBER(4);
TYPE GenericCursor
IS REF CURSOR;
V_GenericCursor GenericCursor;
TYPE TablesRecordType IS RECORD
(
EmpRecord Emp%ROWTYPE
);
V_EmpRecordType TablesRecordType;
BEGIN
DBMS_OUTPUT.ENABLE(1000000);
DBMS_OUTPUT.PUT_LINE(RPAD(LPAD('Employees Information', 49,
'*'), 80, '*'));
DBMS_OUTPUT.PUT_LINE(RPAD('-', 80,'-'));
DBMS_OUTPUT.PUT_LINE(RPAD('EmpNo', 8)|| RPAD('Ename',
12)||RPAD('Job', 12)||RPAD('Deptno', 8)||RPAD('Mgr',
10)||RPAD('Hiredate', 12)||RPAD('Sal', 12)||RPAD('Comm', 10));
DBMS_OUTPUT.PUT_LINE(RPAD('-', 80,'-'));
FOR LoopIndex IN (
SELECT Deptno, Dname
FROM Dept
)
LOOP
OPEN V_GenericCursor
FOR
SELECT *
FROM Emp
WHERE Deptno = LoopIndex.Deptno;
DBMS_OUTPUT.PUT_LINE('----------------------------------------------------------------------------');
DBMS_OUTPUT.PUT_LINE('Now Printing The Employees of
Department : '||LoopIndex.Dname);
DBMS_OUTPUT.PUT_LINE('----------------------------------------------------------------------------');
V_RoWCount := 0;
LOOP
FETCH V_GenericCursor
INTO V_EmpRecordType.EmpRecord;
EXIT WHEN V_GenericCursor%NOTFOUND;
V_RoWCount := V_GenericCursor%ROWCOUNT;
DBMS_OUTPUT.PUT_LINE(RPAD(V_EmpRecordType.EmpRec
ord.Empno, 8)
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
||RPAD(V_EmpRecordType.EmpRecord.Ename,
12)||RPAD(V_EmpRecordType.EmpRecord.Job,
12)||RPAD(V_EmpRecordType.EmpRecord.Deptno,
8)||NVL(TO_CHAR(RPAD(V_EmpRecordType.EmpRecord.MG
R, 10)),'No
Manager')||RPAD(V_EmpRecordType.EmpRecord.Hiredate,
12)||RPAD(V_EmpRecordType.EmpRecord.Sal,
12)||NVL(TO_CHAR(RPAD(V_EmpRecordType.EmpRecord.C
omm, 12)),'-NA-'));
END LOOP;
CLOSE V_GenericCursor;
DBMS_OUTPUT.PUT_LINE(V_RowCount||' Rows Processed So Far...');
END LOOP;
END;
BULK COLLECT Reduces The Number of I/O Cycles Between The PL/SQL And
SQL Engines And Reduces The Overhead of Retrieving Data.
SQL> DECLARE
TYPE EmpTableType
IS TABLE OF
Emp%ROWTYPE;
V_EmpTableType EmpTableType;
BEGIN
SELECT *
BULK COLLECT INTO V_EmpTableType
FROM Emp;
FOR IndexVariable IN V_EmpTableType.FIRST .. V_EmpTableType.LAST
LOOP
DBMS_OUTPUT.PUT_LINE(V_EmpTableType(IndexVariable).Ename || '
is Fixed With A Salary of ' || V_EmpTableType(IndexVariable).Sal);
END LOOP;
END;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Exception Handling
Exception Trapping
Exception Propagation
Exception Trapping
Exception Propagation
Exception Trapping
SQL> DECLARE
BEGIN
Exception Raised;
EXCEPTION
Exception Trapped;
END;
Exception Propagation
SQL> DECLARE
BEGIN
Exception Raised;
EXCEPTION
Exception Not Trapped
END;
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Specifications of Exceptions
1. Exception Type
Description
Handling Tip:
RAISE
2. Exception Type
Description
Handling Tip
User
Defined
3. Exception Type
Description
Handling Tip
Trapping Exceptions
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Syntax
EXCEPTION
WHEN Exception1[OR Exception2] THEN
Statement1;
Statement2;
WHEN OTHERS THEN
Statement1;
Statement2;
END;
The EXCEPTION Handling Section Taps Only Those Exceptions That Are
Specified By The Programmer Using Proper Exception Handler.
Any Other Exceptions Are Propagated Which Are Not Trapped, Unless The
OTHERS EXCEPTION Handle is Used.
Begin The EXCEPTION Handling Section of The Block With The Keywords
EXCEPTION.
Define Several EXCEPTION HANDLERS, Each With its Own Set of Action For
The Block.
Place The OTHERS Clause After All Other Exception Handling Clauses.
All Predefined
Packages.
As Soon As The Exception Occurs Oracle Implicitly Raises The Exception And
Jumps Into The EXCEPTION Handle Block, If Proper EXCEPTION Handle is
Found Manages The Specified Steps.
Exceptions
Are
Declared
By
PL/SQL
is
The
Standard
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> DECLARE
V_Empno Emp.Empno%TYPE := &Empno;
V_Ename Emp.Ename%TYPE;
V_Sal Emp.Sal%TYPE;
BEGIN
SELECT Ename, Sal INTO V_Ename, V_Sal
FROM Emp
WHERE Empno = V_Empno;
DBMS_OUTPUT.PUT_LINE('Name : '||V_Ename||' Salary : '||V_Sal);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Sorry, Data is Not Found.');
END;
/
SQL> DECLARE
V_Emp Emp%ROWTYPE;
V_Sal Emp.Sal%TYPE := &Sal;
BEGIN
SELECT * INTO V_Emp
FROM Emp
WHERE Sal = V_Sal;
DBMS_OUTPUT.PUT_LINE('Name : '||V_Emp.Ename||' Salary :
'||V_Emp.Sal);
EXCEPTION
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('More Than One Employee Having Same
Salary');
END ;
/
SQL> DECLARE
V_Empno VARCHAR2(4):='&Empno';
V_Ename VARCHAR2(20):='&Ename';
V_Deptno VARCHAR2(2):='&Deptno';
BEGIN
INSERT INTO Emp(Empno,Ename,Deptno)
VALUES (V_Empno,V_Ename,V_Deptno);
EXCEPTION
WHEN INVALID_NUMBER THEN
DBMS_OUTPUT.PUT_LINE('Given Employee Number or Department
Number is Invalid');
END ;
/
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> DECLARE
V_Num1 NUMBER;
BEGIN
V_Num1 := '&GiveNumber1' + '&GiveNumber2';
DBMS_OUTPUT.PUT_LINE ('The Result of the Operation is: ' ||
V_Num1);
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE ('Please Check - There is a Source of Invalid
Values in your input (OR) Operations.');
END ;
/
SQL> DECLARE
V_Empno Emp.Empno%TYPE := &Empno;
V_Ename Emp.Ename%TYPE := '&Ename';
V_Deptno Emp.Deptno%TYPE := &Deptno;
BEGIN
INSERT INTO Emp(Empno,Ename,Deptno)
VALUES (V_Empno,V_Ename,V_Deptno);
DBMS_OUTPUT.PUT_LINE('Employee Successfully Inserted');
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
DBMS_OUTPUT.PUT_LINE('Employee ID Already Exists');
END ;
/
SQL> DECLARE
V_Ename Emp.Ename% TYPE;
V_Sal Emp.Sal%TYPE;
V_RowCount PLS_INTEGER := 0;
CURSOR EmpRowCount IS
SELECT Ename, Sal
FROM Emp
ORDER BY Ename;
BEGIN
OPEN EMPROWCOUNT;
LOOP
FETCH EmpRowCount INTO V_Ename, V_Sal;
EXIT WHEN EmpRowCount%NOTFOUND;
V_RoWCount := EmpRoWCount%ROWCOUNT;
DBMS_OUTPUT.PUT_LINE('Employee Name is,'||V_Ename||' his Salary
is '||V_Sal);
END LOOP;
OPEN EMPROWCOUNT;
DBMS_OUTPUT.PUT_LINE(V_RowCount||' Rows Processed So Far...');
CLOSE EmpRowCount;
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
EXCEPTION
WHEN CURSOR_ALREADY_OPEN THEN
DBMS_OUTPUT.PUT_LINE('The Requested Cursor is already Open.');
END;
/
SQL> DECLARE
V_Ename Emp.Ename% TYPE;
V_Sal Emp.Sal%TYPE;
V_RowCount PLS_INTEGER := 0;
CURSOR EmpRowCount IS
SELECT Ename, Sal
FROM Emp
ORDER BY Ename;
BEGIN
OPEN EMPROWCOUNT;
LOOP
FETCH EmpRowCount INTO V_Ename, V_Sal;
EXIT WHEN EmpRowCount%NOTFOUND;
V_RoWCount := EmpRoWCount%ROWCOUNT;
DBMS_OUTPUT.PUT_LINE('Employee Name is,'||V_Ename||' his Salary
is '||V_Sal);
END LOOP;
DBMS_OUTPUT.PUT_LINE(V_RowCount||' Rows Processed So Far...');
CLOSE EmpRowCount;
CLOSE EmpRowCount;
EXCEPTION
WHEN INVALID_CURSOR THEN
DBMS_OUTPUT.PUT_LINE('The Requested Cursor is either not open or is
already closed.');
END;
/
SQL> DECLARE
V_Grade CHAR := UPPER('&EnterGrade');
BEGIN
CASE V_Grade
WHEN 'A' THEN
DBMS_OUTPUT.PUT_LINE('You are Awarded with Excellent
Grade');
WHEN 'B' THEN
DBMS_OUTPUT.PUT_LINE('You are Awarded with Very Good
Grade');
WHEN 'C' THEN
DBMS_OUTPUT.PUT_LINE('You are Awarded with Good
Grade');
WHEN 'D' THEN
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
EXCEPTION
WHEN VALUE_ERROR OR INVALID_NUMBER THEN
DBMS_OUTPUT.PUT_LINE('There is some Error in the Data
inputs (OR) Data outputs, Please Check, Debug the
Source.');
END;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('The Given Information is Missing in the
Database, Check for Proper Values.');
END;
/
The Statement is Not Processed When That PL/SQL Block is Executed Rather
The PRAGMA Directs The PL/SQL Compiler To Interpret All Occurrences of
The EXCEPTION Name Within The Block As The Associated Oracle Server
Error Number.
DECLARE
EXCEPTION Name
Associate
Reference
Declarative Section
Syntax
Declaring The Name For The EXCEPTION With in The Declarative Section.
ExceptionIdentifier EXCEPTION;
Illustration
SQL> DECLARE
E_EmpRemaining EXCEPTION;
PRAGMA EXCEPTION_INIT(E_EmpRemaining, -2292);
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> DECLARE
E_EmpRemaining EXCEPTION;
PRAGMA EXCEPTION_INIT(E_EmpRemaining, -2292);
V_Deptno Emp.Deptno%TYPE := &GiveDeptno;
BEGIN
DELETE FROM Dept
WHERE Deptno = V_Deptno;
IF SQL%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE('The Given Information is Missing in the
Database, Check for Proper Values.');
END IF;
ROLLBACK;
EXCEPTION
WHEN E_EmpRemaining THEN
DBMS_OUTPUT.PUT_LINE('Unable to Delete the Department Number
'||V_Deptno||' as the Employees are Existing. Validate Your Relations
and then Try Once Again.');
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('The Given Information is Missing in the
Database, Check for Proper Values.');
END;
/
SQL> DECLARE
E_EmpExists EXCEPTION;
V_Count NUMBER(2);
V_SalSum NUMBER(6);
PRAGMA EXCEPTION_INIT(E_EmpExists, -2292);
V_Empno Emp.Empno%TYPE := &GiveEmpno;
BEGIN
DELETE FROM Emp
WHERE Empno = V_Empno;
IF SQL%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE('The Given Employee Number '||V_Empno||'
is Missing in the Database, Check for Proper Values.');
ROLLBACK;
ELSE
COMMIT;
END IF;
EXCEPTION
WHEN E_EmpExists THEN
DBMS_OUTPUT.PUT_LINE('Unable to Delete the Employee Details
'||V_Empno||' as the Employees are Existing. Validate Your Relations
and then Try Once Again.');
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('The Given Information is Missing in the
Database, Check for Proper Values.');
END;
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> DECLARE
E_NotNULLViolation EXCEPTION;
PRAGMA EXCEPTION_INIT(E_NotNULLViolation, -1400);
BEGIN
INSERT INTO Emp(Empno, Ename, Job, Sal, Comm, Deptno)
VALUES(&Empno, 'SATISH', 'ANALYST', 25000, NULL, &Deptno);
COMMIT;
EXCEPTION
WHEN E_NotNULLViolation THEN
DBMS_OUTPUT.PUT_LINE('A Field which
attended, Please Check Properly...');
Cannot
be
NULL,
is
not
END;
/
SQL> ALTER TABLE Emp
ADD CONSTRAINT EmpEnameCHK CHECK(Ename = UPPER(Ename))
ADD CONSTRAINT EmpJobCHK CHECK(Job = UPPER(Job))
/
SQL> DECLARE
E_NotNULLViolation EXCEPTION;
PRAGMA EXCEPTION_INIT(E_NotNULLViolation, -1400);
E_CheckViolation EXCEPTION;
PRAGMA EXCEPTION_INIT(E_CheckViolation, -2290);
BEGIN
INSERT INTO Emp(Empno, Ename, Job, Sal, Comm, Deptno)
VALUES(&Empno, '&Ename', '&Job', 25000, NULL, &Deptno);
COMMIT;
EXCEPTION
WHEN E_CheckViolation THEN
DBMS_OUTPUT.PUT_LINE('A Field with Check Constraint is not Attended
Properly, Please Check Properly.');
WHEN E_NotNULLViolation THEN
DBMS_OUTPUT.PUT_LINE('A Field
attended, Please Check Properly.');
which
Cannot
be
NULL,
is
not
END;
/
SQLCODE Function
SQLERRM Function
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQLCODE Values
Pseudo Syntax
SQL> DECLARE
V_ErroeCode NUMBER;
V_ErrorMessage VARCHAR2(255);
BEGIN
/*Executional Code Here*/
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
V_ErrorCode := SQLCODE;
V_ErrorMessage := SQLERRM;
INSERT INTO Errors
VALUES(V_ErrorCode, V_ErrorMessage);
END;
/
SQL> DECLARE
V_ErrorCode NUMBER(6);
V_ErrorMessage VARCHAR2(200);
BEGIN
INSERT INTO Dept
VALUES(&DeptNumber, '&DeptName', '&DeptLocation');
EXCEPTION
WHEN OTHERS THEN
V_ErrorCode := SQLCODE;
V_ErrorMessage := SUBSTR(SQLERRM, 1, 200);
DBMS_OUTPUT.PUT_LINE('The Error Code Traced is : '||V_ErrorCode);
DBMS_OUTPUT.PUT_LINE('The Error Message Traced is :
'||V_ErrorMessage);
END;
/
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
SQL> DECLARE
V_Empno Emp.Empno%TYPE := &EmpNumber;
V_EName Emp.EName%TYPE;
V_Job Emp.Job%TYPE;
V_Sal Emp.Sal%TYPE;
V_ErrorCode NUMBER(6);
V_ErrorMessage VARCHAr2(200);
BEGIN
SELECT Ename, Job, Sal
INTO
V_EName, V_Job, V_Sal
FROM Emp
WHERE Empno = V_Empno;
DBMS_OUTPUT.PUT_LINE(V_Ename||'
'||V_Job||'
'||V_Sal);
EXCEPTION
WHEN OTHERS THEN
V_ErrorCode := SQLCODE;
V_ErrorMessage := SUBSTR(SQLERRM, 1, 200);
DBMS_OUTPUT.PUT_LINE('The Error Code Traced is : '||V_ErrorCode);
DBMS_OUTPUT.PUT_LINE('The Error Message Traced is :
'||V_ErrorMessage);
END;
/
RAISE
Reference
EXCEPTION Name
Declarative Section
Executable Section
EXCEPTION Handling
Section
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Syntax
RAISE ExceptionIdentifier;
3. Reference The Declared Exception Within The Corresponding
Exception Handling Runtime.
SQL> DECLARE
V_DeptNo Dept.Deptno%TYPE := &DeptNumber;
V_DeptName Dept.Dname%TYPE := '&DeptName';
V_DeptLoc Dept.Loc%TYPE := '&DeptLocation';
E_InvalidDept EXCEPTION;
BEGIN
UPDATE Dept
SET Dname = V_DeptName,
Loc = V_DeptLoc
WHERE Deptno = V_DeptNo;
IF SQL%NOTFOUND THEN
RAISE E_InvalidDept;
END IF;
COMMIT;
EXCEPTION
WHEN E_InvalidDept THEN
DBMS_OUTPUT.PUT_LINE('The Specific Department Number
'||V_DeptNo||' you wanted to Update is not Found. Please Confirm the
Data.');
INSERT INTO MyAudit(UserName, ModDate, Message)
VALUES(USER, SYSDATE, 'Tried Illegal Update.');
END;
/
SQL> DECLARE
V_Ename Emp.Ename%TYPE;
V_Job Emp.Job%TYPE;
E_ManyEmployees EXCEPTION;
CURSOR EmpCursor IS
SELECT MGR, COUNT(*) Tot_Emp
FROM Emp
WHERE MGR IS NOT NULL
GROUP BY MGR;
BEGIN
FOR MgrRecord IN EmpCursor
LOOP
BEGIN
SELECT Ename, Job INTO
V_Ename, V_Job
FROM Emp
WHERE Empno = MgrRecord.Mgr;
IF MgrRecord.Tot_Emp > 3 THEN
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
RAISE E_ManyEmployees;
ELSE
DBMS_OUTPUT.PUT_LINE('Employee, '||V_Ename||' Manages
'||MgrRecord.Tot_Emp||' Employees.');
END IF;
EXCEPTION
WHEN E_ManyEmployees THEN
DBMS_OUTPUT.PUT_LINE('Employee, '||V_EName||' Manages Many
Employees, Chance of decreasing his Performance, Recommend for
Extra Allowances or Emoluments.');
END;
END LOOP;
END;
/
Exception Propagation
Each Calling Environment Has Its Own Way of Displaying And Accessing
Errors.
If A PL/SQL RAISES An EXCEPTION And The Current Block Does Not Have A
Handle Then The EXCEPTION PROPAGATES into Successive Enclosing Blocks
Until It Finds A Corresponding Handle.
Illustration 1
SQL> DECLARE
V_TestVariable CHAR(5) := '&String';
BEGIN
DBMS_OUTPUT.PUT_LINE ('This is A Test Line.');
DBMS_OUTPUT.PUT_LINE(V_TestVariable);
EXCEPTION
WHEN INVALID_NUMBER OR VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('An Error Raised.');
END;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
END;
Re-Raising An Exception
Illustration
SQL> DECLARE
E_Exception EXCEPTION;
BEGIN
RAISE E_Exception;
EXCEPTION
WHEN E_Exception THEN
RAISE;
END;
EXCEPTION
WHEN E_Exception THEN
DBMS_OUTPUT.PUT_LINE(An Error Occurred);
END;
RAISE_APPLICATION_ERROR Procedure
Us
To
Issue
Syntax:
RAISE_APPLICATION_ERROR(ErrorNumber, Message
[,{TRUE|FALSE}]);
SQL> BEGIN
DECLARE
V_Deptno Dept.Deptno%TYPE := &Deptno;
V_TotEmp NUMBER;
E_InvalidDept EXCEPTION;
BEGIN
IF V_Deptno NOT IN (10, 20, 30, 40) THEN
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
RAISE E_InvalidDept;
ELSE
SELECT COUNT(*) INTO
V_TotEmp FROM Emp
WHERE Deptno = V_Deptno;
DBMS_OUTPUT.PUT_LINE('The Total Employees in '||V_Deptno||'
are '||V_TotEmp||'.');
END IF;
DBMS_OUTPUT.PUT_LINE('No Exception was Raised...');
EXCEPTION
WHEN E_InvalidDept THEN
RAISE_APPLICATION_ERROR(-20220, 'Sorry There is no Such
Department...as You requested.');
END;
EXCEPTION
WHEN OTHERS THEN
RAISE_APPLICATION_ERROR(-20220, 'Sorry Fatal Error.');
END;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Block Structure
Procedures in PL/SQL
Syntax
CREATE OR REPLACE PROCEDURE
ProcedureName(ParName1 [MODE] ParType,)
IS
Local Variable Declaration;
BEGIN
Executable Statements;
EXCEPTION
Exception Handlers;
END ProcedureName;
The Header
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The Body
SQL> Begin
MyBonus;
END;
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Illustrative Examples
SQL> CREATE OR REPLACE PROCEDURE
GetEnameSalJob00
(
PEmpno
Emp.Empno%TYPE
)
AS
V_Ename
Emp.Ename%TYPE;
V_Sal
Emp.Sal%TYPE;
V_Job
Emp.Job%TYPE;
BEGIN
SELECT
Ename, Sal, Job
INTO
V_Ename, V_Sal, V_Job
FROM Emp
WHERE Empno = PEmpno;
DBMS_OUTPUT.PUT_LINE('The Details of Employee '||PEmpno||'
Are...');
DBMS_OUTPUT.PUT_LINE('The Name of The Employee is : '||V_Ename);
DBMS_OUTPUT.PUT_LINE('The Salary of The Employee is : '||V_Sal);
DBMS_OUTPUT.PUT_LINE('The Job of The Employee is : '||V_Job);
END GetEnameSalJob00;
/
SQL> CREATE OR REPLACE PROCEDURE
EmpInsert
(
P_Empno Emp.Empno%TYPE,
P_Ename Emp.Ename%TYPE,
P_Sal Emp.Sal%TYPE,
P_Deptno Emp.Deptno%TYPE,
P_Job
Emp.Job%TYPE,
P_Comm
Emp.Comm%TYPE,
P_HireDate Emp.HireDate%TYPE,
P_MGR
Emp.MGR%TYPE
)
AS
BEGIN
INSERT INTO
Emp (Empno, Ename, Sal, Deptno, Job, Comm, HireDate, MGR)
VALUES(P_Empno, UPPER(P_Ename), P_Sal, P_Deptno, UPPER(P_Job),
P_Comm, P_HireDate, P_MGR);
COMMIT;
Exception
WHEN DUP_VAL_ON_INDEX THEN
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
BEGIN
FOR R_GroupBonus IN DeptCursor
LOOP
DECLARE
E_JobNotFound EXCEPTION;
CURSOR EmpCursor IS
SELECT *
FROM Emp
WHERE Deptno = R_GroupBonus.Deptno;
BEGIN
FOR R_EmpCursor IN EmpCursor
LOOP
IF R_EmpCursor.Job = 'PRESIDENT'
THEN
UPDATE Emp
SET Sal = Sal + (Sal * 0.40)
WHERE Empno = R_EmpCursor.Empno;
DBMS_OUTPUT.PUT_LINE('The Job For Updation is
'||R_EmpCursor.Job);
DBMS_OUTPUT.PUT_LINE('Old Sal : '||R_EmpCursor.Sal);
DBMS_OUTPUT.PUT_LINE('Increament Added : '||((R_EmpCursor.Sal +
(R_EmpCursor.Sal * 0.40)) - (R_EmpCursor.Sal)));
DBMS_OUTPUT.PUT_LINE('The Salary With Increment is :
'||(R_EmpCursor.Sal + (R_EmpCursor.Sal * 0.40)));
ELSE
IF R_EmpCursor.Job = 'MANAGER'
THEN
UPDATE Emp
SET Sal = Sal + (Sal * 0.35)
WHERE Empno = R_EmpCursor.Empno;
DBMS_OUTPUT.PUT_LINE('The Job For Updation is
'||R_EmpCursor.Job);
DBMS_OUTPUT.PUT_LINE('Old Sal : '||R_EmpCursor.Sal);
DBMS_OUTPUT.PUT_LINE('Increament Added : '||((R_EmpCursor.Sal +
(R_EmpCursor.Sal * 0.40)) - (R_EmpCursor.Sal)));
DBMS_OUTPUT.PUT_LINE('The Salary With Increment is :
'||(R_EmpCursor.Sal + (R_EmpCursor.Sal * 0.40)));
IF R_EmpCursor.Job = 'ANALYST'
THEN
UPDATE Emp
SET Sal = Sal + (Sal * 0.30)
WHERE Empno = R_EmpCursor.Empno;
DBMS_OUTPUT.PUT_LINE('The Job For Updation is
'||R_EmpCursor.Job);
DBMS_OUTPUT.PUT_LINE('Old Sal : '||R_EmpCursor.Sal);
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
PARAMETERS Are The Mean To Pass Values TO And FROM The Calling
Environments To The Oracle Server.
PARAMETERS Are The Values That Will Be Processed OR Returned Via The
EXECUTION of The PROCEDURE.
The Constraint Upon The Data is Made When The Procedure is Called At
Runtime From The Executable Environment.
Positional Notation.
Named Notation.
Positional Notation
The Order of The Parameters Used When Executing The Procedure Should
Match The Order in The PROCEDURES HEADER Exactly.
Named Notation
Syntax
FormalParameterName => ArgValue
If The Notation is Mixed Then Position Notation Should Be Used First Then
The Named Notation Should Be Used.
Mode: IN
Mode: Out
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Mode: INOUT
Passes Values IN But Also Sends Values Back To The Calling Environments.
Values Will Be READ From The Calling Environment And Then WRITTEN To
The Calling Environment .
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
END;
/
SQL> CREATE OR REPLACE PROCEDURE
EmpInfo(I_Deptno IN NUMBER)
AS
CURSOR EmpInfoCursor IS
SELECT Ename, Job, Sal, Comm
FROM Emp
WHERE Deptno = I_Deptno;
EmpRecord EmpInfoCursor%ROWTYPE;
NEmployees NUMBER := 0;
TSalary NUMBER := 0;
AVGSalary NUMBER(7,2) := 0;
MAXSalary NUMBER(7,2) := 0;
BEGIN
OPEN EmpInfoCursor;
LOOP
FETCH EmpInfoCursor INTO EmpRecord;
EXIT WHEN EmpInfoCursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Employee Name : '||EmpRecord.Ename);
DBMS_OUTPUT.PUT_LINE('Employee Job : '||EmpRecord.Job);
DBMS_OUTPUT.PUT_LINE('Employee Salary : '||EmpRecord.Sal);
DBMS_OUTPUT.PUT_LINE('Employee Comission : '||EmpRecord.Comm);
DBMS_OUTPUT.PUT_LINE('************************************
');
TSalary := TSalary + EmpRecord.Sal;
NEmployees := NEmployees + 1;
IF EmpRecord.Sal > MAXSalary THEN
MAXSalary := EmpRecord.Sal;
END IF;
END LOOP;
AVGSalary := TSalary / NEmployees;
DBMS_OUTPUT.PUT_LINE('Number of Employees : '||NEmployees);
DBMS_OUTPUT.PUT_LINE('Total Salary : '||TSalary);
DBMS_OUTPUT.PUT_LINE('Maximum Salary : '||MAXSalary);
DBMS_OUTPUT.PUT_LINE('Average Salary : '||AVGSalary);
CLOSE EmpInfoCursor;
END EmpInfo;
/
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The Data Type of The Return Values Must Be Declared in The Header of The
Function.
A FUNCTION Should RETURN Value For All The Varying Possible Execution
Streams.
The RETURN Statement Need Not Appear As The Last Line of The Main
Execution Section.
A FUNCTION Can Contain More Than One RETURN Statement, Each Exception
Should Have A RETURN Statement.
Syntax
CREATE OR REPLACE FUNCTION FuncName(Parameter List)
RETURN DataType
IS
Local Variables
BEGIN
<Body>
RETURN(Return Value);
EXCEPTION
<Defined Pragmas>
END;
SQL> CREATE OR REPLACE FUNCTION Factorial(Num NUMBER)
RETURN NUMBER
IS
Fact NUMBER(4) := 1;
BEGIN
FOR MyIndex IN REVERSE 1..Num
LOOP
Fact := Fact * MyIndex;
END LOOP;
RETURN Fact;
END;
/
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The First Call To The Package is Very Expensive But All Subsequent Calls Will
Result in An Improved Performance.
Package Specification
PACKAGE
Variables.
SPECIFICATION
Contains
Declarations
of
GLOBAL/PUBLIC
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The PACKAGE BODY Contains The Actual Executable Code For The OBJECTS
Described in The PACKAGE SPECIFICATION.
The PACKAGE BODY Contain Code For All Procedures And Function Described
in The Specification And May Additionally Contain Code For Object Not
Declared in The Specification.
When Creating Stored Package The Package Specification And Body Can Be
Compiled Separately.
MODULE
PackageName.Element
We Need Not Qualify Elements When Declared And Referenced Inside The
Body of The Package OR When Declared In A Specification And Referenced
Inside The Body of The Same Package.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
V_Num1 := V_Num1 + 1;
END LOOP;
DBMS_OUTPUT.PUT_LINE('The Odd Numbers in The Series are :
'||OddValue);
DBMS_OUTPUT.PUT_LINE('The Even Numbers in The Series are :
'||EvenValue);
END PrintEvenOdd;
PROCEDURE SquareArea(Side IN NUMBER)
IS
BEGIN
DBMS_OUTPUT.PUT_LINE('Area of The Square = ' || (Side * Side) );
END;
PROCEDURE CubeVolume(Radius IN NUMBER)
IS
BEGIN
DBMS_OUTPUT.PUT_LINE('Volume of The Cube = ' || (Radius * Radius *
Radius));
END;
END MathsBody;
/
SQL> CREATE OR REPLACE PACKAGE EmpPackage
IS
PROCEDURE MyBonus;
PROCEDURE FindEmp
(I_Empno IN NUMBER,
O_Ename OUT VARCHAR2,
O_Job OUT VARCHAR2);
PROCEDURE EmpInfo(I_Deptno IN NUMBER);
FUNCTION EmpExp(V_Empno NUMBER)
RETURN NUMBER;
FUNCTION EmpGrade(I_Grade NUMBER)
RETURN VARCHAR2;
END EmpPackage;
SQL> CREATE OR REPLACE PACKAGE BODY EmpPackage
IS
PROCEDURE MyBonus
AS
CURSOR DeptCursor IS
SELECT Deptno FROm Dept;
BEGIN
FOR R_GroupBonus IN DeptCursor LOOP
UPDATE Emp
SET Sal = Sal * 0.95
WHERE Deptno = R_GroupBonus.DeptNo;
DBMS_OUTPUT.PUT_LINe('The Bonus Information is
'||R_GroupBonus.Deptno);
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
END LOOP;
END MyBonus;
PROCEDURE FindEmp
(I_Empno IN NUMBER,
O_Ename OUT VARCHAR2,
O_Job OUT VARCHAR2)
AS
BEGIN
SELECT Ename, Job INTO O_Ename, O_Job
FROM Emp WHERE Empno = I_Empno;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Error in Finding the Details of Employee
Number : '|| I_Empno);
END FindEmp;
PROCEDURE EmpInfo(I_Deptno IN NUMBER)
AS
CURSOR EmpInfoCursor IS
SELECT Ename, Job, Sal, Comm
FROM Emp
WHERE Deptno = I_Deptno;
EmpRecord EmpInfoCursor%ROWTYPE;
NEmployees NUMBER := 0;
TSalary NUMBER := 0;
AVGSalary NUMBER(7,2) := 0;
MAXSalary NUMBER(7,2) := 0;
BEGIN
OPEN EmpInfoCursor;
LOOP
FETCH EmpInfoCursor INTO EmpRecord;
EXIT WHEN EmpInfoCursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Employee Name : '||EmpRecord.Ename);
DBMS_OUTPUT.PUT_LINE('Employee Job : '||EmpRecord.Job);
DBMS_OUTPUT.PUT_LINE('Employee Salary : '||EmpRecord.Sal);
DBMS_OUTPUT.PUT_LINE('Employee Comission : '||EmpRecord.Comm);
DBMS_OUTPUT.PUT_LINE('************************************
');
TSalary := TSalary + EmpRecord.Sal;
NEmployees := NEmployees + 1;
IF EmpRecord.Sal > MAXSalary THEN
MAXSalary := EmpRecord.Sal;
END IF;
END LOOP;
AVGSalary := TSalary / NEmployees;
DBMS_OUTPUT.PUT_LINE('Number of Employees : '||NEmployees);
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Syntax
CREATE OR REPLACE TRIGGER TriggerName
{BEFORE OR AFTER} EventType ON TableName
[FOR EACH ROW]
[WHEN Condition]
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
DECLARE
Declaration Statements;
BEGIN
Executable Statements;
EXCEPTION
Exception Handling;
END;
When A Database Table is Dropped Then The Associated Triggers Are Also
Dropped Automatically.
Advantages
Restrictions
Before Triggers
Usage
When A Trigger Provides Values For Derived Columns BEFORE The INSERT
OR UPDATE Statement is Completed.
After Triggers
Usage
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Instead of Triggers
The INSTEAD OF TRIGGERS Are Special Kind That Are Defined On DATABASE
Views.
Syntax
SQL> CREATE OR REPLACE TRIGGER TriggerName
INSTEAD OF TriggerEvent ON ViewName
FOR EACH ROW
BEGIN
Execution Statement;
END;
SQL> CREATE VIEW DeptView
AS
SELECT Deptno, Dname, Loc
FROM Dept
/
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Row Triggers
When The Statement FOR EACH ROW is Present in The CREATE TRIGGER
Clause, The Trigger is A ROW Trigger.
Illustration
SQL> CREATE OR REPLACE TRIGGER
DeptUpdate
AFTER UPDATE ON Dept
FOR EACH ROW
The ROW LEVEL TRIGGER Fires As Many Times As The Number of ROWS Are
Affected When The Transaction Takes Place.
Illustration
SQL> CREATE OR REPLACE TRIGGER
DeptDelete
AFTER DELETE ON Dept
As A ROW LEVEL TRIGGER Fires Once Per Row Inside The TRIGGER We Can
Access The Data In The ROW THAT IS CURRENTLYTY BEING PROCESSED.
The Two Correlation Identifiers Provided By PL/SQL Are :OLD And :NEW.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
The Specifications
Transaction
:OLD
:NEW
INSERT
Undefined:
All Fields Are NULL
UPDATE
DELETE
Undefined:
All Fields Are NULL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Q.2)
Q.3)
Q.4)
Q.5)
Q.6)
Display the employee name and annual salary for all employees.
Q.7)
Q.8)
Display the names of all the employees who are working as clerks and
drawing a salary more than 3000.
Q.9)
Display the employee number and name who are earning comm.
Q.10)
Display the employee number and name who do not earn any comm.
Q.11)
Q.12)
Display the names of the employees who are working in the company
for the past 5 years;
Q.13)
Display the list of employees who have joined the company before 30jun-90 or after 31-dec-90.
all
the
employees
who
are
working
Q.14)
Q.15)
in
Q.16)
Q.17)
Q.18)
Q.19)
Q.20)
Display the employee names for employees whose name ends with
alphabet s.
Q.21)
Q.22)
Q.23)
Display the names of the employee who are not working as managers.
Q.24)
Display the names of the employee who are not working as salesman
or clerk or analyst.
Q.25)
Display all rows from emp table. the system should wait after every
screen full of information.
Q.26)
Q.27)
Q.28)
Q.29)
Q.30)
Q.31)
Q.32)
Q.33)
Q.34)
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Q.35)
Q.36)
Display the names of the employee in order of salary i.e the name of
Q.37)
Q.38)
Q.39)
Q.40)
Q.41)
Q.42)
Q.43)
Q.44)
Q.45)
Display the various jobs and total number of employees within each
job group.
Q.46)
Display the depart numbers and total salary for each department.
Q.47)
Display the depart numbers and max salary for each department.
Q.48)
Display the various jobs and total salary for each job
Q.49)
Display the depart numbers with more than three employees in each
dept.
Q.50)
Display the various jobs along with total salary for each of the jobs
where total salary is greater than 40000.
Q.51)
Display the various jobs along with total number of employees in each
job. the output should contain only those jobs with more than three
employees.
Q.52)
Q.53)
Display the employee number and name for employee working as clerk
and earning highest salary among clerks.
Q.54)
Display the names of salesman who earns a salary more than the
highest salary of any clerk.
Q.55)
Display the names of clerks who earn a salary more than the lowest
salary of any salesman.
Q.56)
Display the names of employees who earn a salary more than that of
jones or that of salary greater than that of scott.
Q.57)
Display the names of the employees who earn highest salary in their
respective departments.
Q.58)
Display the names of the employees who earn highest salaries in their
respective job groups.
Q.59)
Display the
department.
Q.60)
Q.61)
Display the job groups having total salary greater than the maximum
salary for managers.
Q.62)
employee
names
who
are
working
in
accounting
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Q.63)
Q.64)
Q.65)
Q.66)
Q.67)
Q.68)
Q.69)
Q.70)
Q.71)
Find the first occurrence of character 'a' from the following string i.e
'computer maintenance corporation'.
Q.72)
Q.73)
Display the information from emp table. where job manager is found it
should be displayed as boos(use replace function).
Q.74)
Q.75)
Q.76)
Q.77)
Display the current date as 15th august Friday nineteen ninety seven.
Q.78)
Display the following output for each row from emp table.
Q.79)
Q.80)
Q.81)
Q.82)
Q.83)
Q.84)
Q.85)
Q.86)
Display the details of those who do not have any person working
under them.
Q.87)
Q.88)
Display those who are not managers and who are managers to any
one.
Q.89)
Q.90)
Q.91)
Q.92)
Display those department whose name start with "s" while the
location
Q.93)
Q.94)
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Q.95)
Display those employees whose salary is more than 3000 after giving
20% increment.
Q.96)
Q.97)
Q.98)
Q.99)
Display those employees whose salary greter than his manager salary.
Q.100)
Display those employees who are working in the same dept where his
manager is work.
Q.101)
Display those employees who are not working under any manager.
Q.102)
Display grade and employees name for the dept no 10 or 30 but grade
is not 4 while joined the company before 31-dec-82.
Q.103)
Update the salary of each employee by 10% increment who are not
eligible for commission.
Q.104)
Q.105)
Q.106)
Q.107)
Display name and salary of ford if his salary is equal to hisal of his
grade
Q.108)
Q.109)
Q.110)
One in the company except 'clerk. sort on salary display the highest
salary?
Q.111)
Q.112)
Q.113)
Display name of those employee who are getting the highest salary?
Q.114)
Q.115)
Q.116)
Q.117)
Q.118)
Q.119)
Q.120)
Whose net pay is greter than or equal to any other employee salary of
the company?
Q.121)
Display all employees names with total sal of company with each
employee name?
Q.122)
Q.123)
Find out the number of employees whose salary is greater than their
his
for
manager.
all
who
display
are
also
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Q.124)
Manager salary?
Q.125)
Q.126)
Q.127)
Q.128)
Q.129)
Q.130)
Q.131)
Q.132)
Q.133)
Q.134)
Q.135)
Q.136)
Display those employee who has joined before 15th of the month.
Q.137)
Q.138)
no
of
employees
in
particular
Q.139)
Q.140)
Q.141)
Print the details of all the employees who are sub-ordinate to Blake?
Q.142)
Display employee name and his salary whose salary is greater than
Q.143)
Q.144)
Q.145)
Q.146)
Display the 10th record of emp table without using group by and
rowid?
Q.147)
Q.148)
Q.149)
Q.150)
Q.151)
Q.152)
Q.153)
A allen
Q.154)
Q.155)
B blake
List out the employees ename,sal,pf(20% of sal) from emp;
Q.156)
Q.157)
Q.158)
Q.159)
Q.160)
Q.161)
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Q.162)
For the time being i have decided that i will not impose this validation.
my boss has agreed to pay more than 10,000.
Q.163)
My boss has changed his mind. Now he doesn't want to pay more than
10,000.so revoke that salary constraint.
Q.164)
Q.165)
Q.166)
Q.167)
Q.168)
Create table called as newemp. Using single command create this table
as well as get data into this table(use create table as);
Q.169)
Q.170)
Delete the rows of employees who are working in the company for
more than 2 years.
Q.171)
Q.172)
his
commission
should
be
Q.173)
Q.174)
Q.175)
Q.176)
Q.177)
Q.178)
Display the
department.
Q.179)
Q.180)
department
name
along
with
total
salary
in
each
Q.181)
Q.182)
Q.183)
Q.184)
Q.185)
Write a query to list all the employees who are working as clerk
Q.186)
Q.187)
Write a query o list the employees who are having experience more
than 4 years
Q.188)
Write a query to list the employees who hired in the last seven days
Q.189)
Write a query to list the employees whose salaries are within the
range of 5000 and 10000
Q.190)
Write a query to list the employees who have joined in the month of
march99
Q.191)
Write a query to list the employees whose salaries are not within the
range of 10000 and 13000
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Q.192)
Q.193)
Write a query to list all employees except who are joined on 11- sep2001, 31-mar-2001 and 30-jan-2001(it also compares time).
Q.194)
Write a query to list all the employees whose names are having o as
second character
Q.195)
Write a query to list all the employees whose names are having r as
last character
Q.196)
Write a query to list all the employees whose names are starting with
r and ending with o
Q.197)
Q.198)
Display the half of the ename's in upper case and the remaining in
lower case?
Q.199)
Use the variable in a statement which finds all employees who can
earn $30,000 a year of more?
Q.200)
Find out how many managers are there without listing them?
Q.201)
Find out the average salary and average total remuneration for each
job type remember salesman earn comm?
Q.202)
Find out the job that was filled in the first half of 1983 and same job
that was filled during the same period on 1984?
Q.203)
Findout all the employees who joined the company before their
manager?
Q.204)
List out all the employees by name and number along with their
managers name and number, also display king who has no manager?
Q.205)
Find out the employees who earn the highest salary in each job type.
sort in descending sal order?
Q.206)
Find out the most recently hired employees in each department. Order
by hiredate?
Q.207)
Display ename salary and deptno for each employee who earn a salary
greater than the average for their department order by deptno?
Q.208)
Q.209)
Display
deptno
compensation?
Q.210)
Q.211)
Display employees
department 30?
Q.212)
Find employees
department 30?
Q.213)
Q.214)
with
highest
who
who
can
can
annual
earn
earn
more
more
remuneration
than
than
bill
as
salary
in
employee
in
lowest
every
Q.215)
List lowest paid employees working for each manager? Exclude any
Q.216)
Groups where the minimum salary is less than 1000 sort the output by
salary?
Q.217)
Delete those records from emp table whose deptno not available in
dept table?
Q.218)
Display name of those emp who are going to retire 31-dec-1999. I the
maximum job period is 30 years?
Q.219)
Q.220)
Q.221)
Display those emp who join in the company in the month of DEC?
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Q.222)
Q.223)
Q.224)
Q.225)
Display those emp who joined the company before 15th of the month?
Q.226)
Delete those emp who joined company of 10years back from today?
Q.227)
Q.228)
Q.229)
Q.230)
Q.231)
Create a query to display all the data from emp table. Separate each
Column by a comma. Name the column the_output.
Q.232)
What is a database?
A dbms is a complex softwaresystem that is used to manage,store and
manipulate data and metadata used to describe the data.
Q.2)
Q.3)
Q.4)
Q.5)
Q.6)
Q.7)
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
With primary key if any other attribute is added then that combination is
called super key in other words,primary key is the minimum possible
super key.in the student table student_no+student_name is one the
super key.
Q.8)
Q.9)
What is a relation?
A relation consists of a homogeneous set of tuples.
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Taking encoded text and converting it into text that you are able to read.
Q.51) What is a distributed database?
A database in which the data is contained with in a number of separate
subsystems usually in different locations.
Q.52) What is an entity?
It represents a real world object.
Q.53) What is a conceptual data model?
A conceptual data model is concerned with the general description of
the data base without concern for how the data may be organised.
Q.54) What is two phase locking?
It is a most common mechanism that is used to control concurrency in
two phases for achieving the serializability. the two phases are growing
and shrinking.
1)a transaction acquires locks on data items it will need to complete the
transaction. this is called growing process. a transaction may obtain lock
but may not release any lock.
2)one lock is released no other lock may be acquired. this is called
shrinking process. a transaction may release locks but may not obtain
any new locks.
Q.55) What is projection?
The projection of a relation is defined as projection of all its tuples over
a set of attributes. it yields vertical subset of the relation. the projection
operation is used to View the number of attributes in the resultant
relation or to reorder attributes.
Q.56) What is encryption?
Encryption is the coding or scrambling of data so that humans can not
read them directly.
Q.57) What is cardinality?
The no of instances of each entity involved in an instance of a relation of
a relation ship describe how often an entity can participate in relation
ship.(1:1,1:many,many:many)
Q.2)
Q.3)
Q.4)
Q.5)
Q.6)
Which command displays the SQL command in the SQL buffer, and then
executes it?
Q.7)
Q.8)
Q.9)
State true or false. !=, <>, ^= all denote the same operation.
Q.10) What are the privileges that can be granted on a table by a user to
others?
Q.11) What command is used to get back the privileges offered by the GRANT
command?
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Table 2 : SOFTWARE
PNAME (VARCHAR), TITLE (VARCHAR), DEVIN (VARCHAR), SCOST
(NUMBER), DCOST (NUMBER), SOLD (NUMBER)
Table 3 : PROGRAMMER
PNAME (VARCHAR), DOB (DATE), DOJ (DATE), SEX (CHAR), PROF1
(VARCHAR), PROF2 (VARCHAR), SAL (NUMBER)
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
LEGEND
PNAME Programmer Name, SPLACE Study Place, CCOST Course Cost,
DEVIN Developed in, SCOST Software Cost, DCOST Development Cost,
PROF1 Proficiency 1
Find out the selling cost average for packages developed in Oracle.
Q.2)
Q.3)
Display the names of those who have done the PGDCA course.
Q.4)
Q.5)
Display the names and date of birth of all programmers born in April.
Q.6)
Q.7)
Q.8)
How much revenue has been earned through the sale of packages
developed in C.
Q.9)
Q.2)
Display the records where the job is either SALESMAN or DEPT NO =20.
Oracle By Sathish Yellanki
Database Consultant SkyEss Techno Solutions Pvt. Ltd.
For Online Training And Real Time Project Training Contact
+91-9290289904, +91-040-23710047, 64640047
Mail: [email protected] (OR) My Blog www.skyess.info
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Q.3)
Q.4)
Q.5)
Display the records whose ENAME begins with the letter in between K
to M.
Q.6)
Q.7)
Q.8)
Q.9)
Page 1 of 396
Material Prepared By Sathish Yellanki For SkyEss Techno Solutions Pvt. Ltd.
Oracle SQL*Plus And PL/SQL
Q.35) Display each employee name with hire date and salary review date
.assuming review date is first year after hire date
Q.36) Find out how many managers are there without listing them.
Q.37) Find the average salary and avg Total Remuneration for each job types.
Remember Salesman earn comm..
Q.38) Find the job that was filled in the first half of 1983 and the same job that
was filled during the same period of 1984.
Q.39) List all employees by NAME and NUMBER along with their managers
details.
Q.40) Write the query to display details for any employee who earns a salary
greater that the average for their department .Sort in Department
Number order.
Q.41) Find out the employee name , salary , dept no, who earns greater than
every employee in Department no 30.
Q.42) Find the Department having maximum employees.
Q.43) Find the employee who earns more than MILLER
Q.44) Find all the person who are not MANAGERS
Q.45) Find the name of person getting same salary in different department .
Q.46) Find the job whose average salary is equal to maximum average salary
of any job.
Q.47) Find out the details of all the person who have been assigned same job
in different DEPT NO.
Q.48) Find the department which has more than 3 employees.
Q.49) Write a query which will return the day of the week ,for any date
entered in format :DD:MM:YY.
Q.50) Check whether all employee number are indeed unique.
Q.51) List lowest paid employees working for each manager. Exclude any
group where the min salary is <1000.Sort the output by salary.
Q.52) Show the records of employees working in DALLAS location.
Q.53) List the following details for employees who earn $36,000 a year or who
are clerk.
Q.54) List all the employees by name, and number along with their managers
name and number.
Q.55) Find the employees who joined the company before their managers.
Q.56) Find the job with the highest average salary.
Q.57) Find the employees who have at least one person reporting to them.
Q.58) Find all employees whose department is not in DEPT table.
Q.59) Find Department which has no employees.
Q.60) Display the following information for the department with the highest
annual remuneration bill.
Q.61) In which year did most people join the company? Display the year and
number of employees.
Page 1 of 396