0 ratings0% found this document useful (0 votes) 42 views47 pagesDatabase Management System Chapter 3,4
Database Management System Chapter 3,4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, 
claim it here.
Available Formats
Download as PDF or read online on Scribd
CHAPTER
ve SQL and Advance
SQL : SQL Performance Tuning
Interacti
     
inbuilt Funetions: Sting, Arithmetic, Date and Time, Aggregate Functions, Group By, Having and Order By Clay
— Joins — Inner and Outer Joins, Sub Queries
Views : Concept of Views, The create view command, updating view
Dropping views
‘Sequences : Creating Sequences, Altering Sequences, Dropping Sequences:
Indexes : Index Types, Creating of Index, simple unique and composite Index, Dropping Indexes
;s, views and joins, views and  sub-quetc,
= Synonyms : Creating Synonyms, Dropping Synonyms
 
  
 
| GES SAA pee nae) fan ono
Syllabus Tople : Inbullt Functions - String,
‘Arithmetic INITCAP%string) + to convert fist leer of each wot i
capita eter.
3.1. Inbuilt Functions : String, Arithmetic SOUS Scleal intceplcoame) Bom capi lean
4. LPAD(chart,n,char2) : retums char, left-padded to leogh
a
3.1.1 String Functions
+m users werieng sae, Wenyere ven ‘withthe character specified in char2.
‘SQL> Select ipad(‘Phoenix’ 10," from du
 
 
‘Explain any four sting functions with examples.
(Refer section 3.1,1) ‘Output
CSERSSEASS AS OSSTAUSTALME || 5. RPAD(chart,n,char2) : retums charl, cight-padded to lenge
 
thoenix
 
 
  
 
Sting: reuse stingin overs ‘with the character specified in char2,
cleet lower(‘PHOENIX) from dual; SQLS Select iadPhoenixs.10;*") foal dual)
     
 
Output : phoenix Output : Phoenix:
If we want to display ename column from emp table in tower | & LTRIMstring, chars) + remove characters from tte Ht
case _ — Ctesoning ofthe suing
SQL> Select lower (ename) fom emp; gE
 
‘SQLS Sclet ism CPHOENIRP) from duals
pa UPPER(Sting: ns the singin epee. Output: HoENTX
TESOLS Seteet Upper phocnix) fom duals
      
    
0) 7. RTRIMGtring, chars) : remove characters from te #8
 
 
 
Output : PHOENIX _ tein oft ing
I we want to display ename column from emp able in upper "SQL> Sele sim (PHOENIX) Rom dal
casepaMs (MSBTE-Sem. 3-Comp)
‘output: PHOENT
fg, TRIMO + Removes all spaces from string (beginning and
ering
 
‘output: Phoenix
9, TRANSLATE(tring, from, 0) : Replace a sequence of
characters in a string with another set of characters. This is
the character to character replacement
  
© SQL>: Select translate(jack’¥'7b) from ‘dual;
Output : beck
430, REPLACE(tring, search string, replace string) : word to
‘word replacement
   
 
SOLS Seles replace( jack and jue 7H) fom dual
   
Output : Black and blue
11, LENGTH(string) : ets the length of sing
"Ti SQLS Select length (PHOENIX from dual
  
   
Output : 7
12. SUBSTR(sting, m,n) : to display n no of characters from
sh charter om given sig
SQLS Sete subst('PHOENIX INFOTECH) from
- dual; ee
Output : NIX INF
3.1.2 Arithmetic Functions
= Rater than the aggregate functions there are some more
numeric functions.
1. POWER(ms)
PESOS’ SA porer(A2) from duals
 
find nth power to the number m.
  
Output : 16
it returns the absolute valye
SOLE Select abs( 35) from duals ss
Output : 15
    
 
32
 
 
 
 
 
 
Intoractive SOL & Adv. SQL : SQL Performance Tunins
Output : 100.25
number.
  
 
4, SQRT : to find out square root of git
© SQL> Select sqr(25) from dual;
Output : 5
    
5. GREATEST(expl,exp2yexpn) returns the greatest value in
alist of expressions.
SOLS Satect greatest(.317) from dual:
  
Output :17
6. LEAST(expl,exp2,expn) : retums the lowest value in a list
of expressions.
SQL> Select least(4,5,17) from dual;
   
Output: 4
‘Syllabus Topic : Date and Time, Aggregate
Functions
3.2 Date and Time , Aggregate Functions
3.2.1 Date and Time Functions
> (usBTE- w-1s, w-16, $17)
     
 
@. 3.2.1 Explain any four date function with example.
‘(Refer section 3.2.1)
 
1. ADD_MONTHS(4.0) : Return date after adding the number
‘of months specified in the function.
   
‘SQL>Seleet add_months(eysdate,4) from dual;
2. LASTLDAY : Returns the last date of the month specified
with the function.
“SQL> Select syedate,last_day(eysdate) from dual,
 
3. MONTHS_BETWEEN(d1,d2) : Retums number of months
between dl and d2.
SOLS Seieat months. between(02.feb-06"02.jan07)
from doa
   
4. NEXT_DAY(date,weekday) : Retums the date of the first
‘weekday coming after the date
  
SOLD Select next. day(06.jl-02°/monday) fom duals.
Output : retum coming Monday after 06-jul-023.2.2 Aggregate Functions
> quspte-w-13, 544)
  
 
9.2.2 Explain any four Aggregate functions with
‘example. (Refer section 3.2.2)
  
 
set of values
— Aggregate functions perform a calculation on &
‘and retum a single value. Usually these functions ignore
[NULL values(except for COUNT).
‘© Types of aggregate functions
= There are different types of aggregate functions:
    
 
Fig. 3.2.1 : Aggregate functions
Consider the table emp
> @ Mind
‘This function returns smallest value from specified column of
the table.
Query
‘Select min(sal) from emp;
Output
800
> (2) Maxi
This function returns greatest value from specified column of
the table.
Query
Seleet max(cl) from emp;
Output
5000 7
 
 
{AL Performance Tun
 
Interactive SOL & Adv. SOL
> @ Sumo
srs funetion returns sum of all the values Of specify
column of the table.
Query
Select sum(sal) from emp;
 
Output
 
20025 gear Al
> @ Aw0
‘This function returns average of all the values of speciteg
column ofthe table.
Query ;
Select avg(eal) from emp;
Output
2078.21 ne
> Cound
This function returns total number of values of specified
column ofthe table
Query
SBeleo! count (ename) from eiaps
Output
4
 
Syllabus Topic :_ Group By Clause
3.3 GROUP BY Clause
> (MSBTE - W-13, W-14, S-15, S-16, $-17, W-17)
  
  
Q.3.3.1 Explain group by clause.
     
 
  
(Roter section 3.8) TEE
3.3.2 Explain group by clause with suitable example.
(Refer section 3.3)
CESS TMA
Q.3.3.3 Define group by clause,
 
   
 
 
(Refer section 3.3)
   
E
Group by clause is a clause which is used ®
I | output result by grouping similar data.DBMS (MSBTE-Sem. 3-Comp)
‘The GROUP BY clause is used in collaboration with the
pL8CT statement. Tt elps £0 arange similar data into groups, I
jz ao sed with SQL Functions to gr0Up the result from one of
more ables.
Table 3.3.1 : Empt
 
 
[fap exawe [Jos [war | wineDATE] SAL] coun |bemnio)
 
 
 
 
 
 
= [me |rresoowr] [ronment te
[ee Tae [naan [75 |escies[ asl Tp
Free [ocnn fuscia | otares | 20 a
 
 
 
 
 
 
 
 
 
3-4 __ Interactive SQL & Adv. SQL : SQL Performance Tuning
In general we use WHERE clause to give some condition 10
filter the data. But WHERE clause is not allowed in collaboration
with GROUP BY clause, HAVING clause is used with GROUP by
clause to specify condition.
———
Syllabus Topic : Having Clause
3.4 _ HAVING Clause
> (sere - w-13, $-16, $-17)
   
@.3.44 Explain having clause with example.
 
 
 
 
 
 
 
rao [unuen [ouerK [7782 ovreats82| 1200]
 
 
 
 
 
 
 
 
 
1, Display sum of salaries department wise.
Select depino,sum(sal) from emp group by deptno;
 
 
 
 
Output
DEPTNO | SUM(SAL)
30 9400
20 10875
10 8750
 
 
 
 
2 Display maximum salaries groping on the basis of job
‘Setter emp group by jl
    
 
 
 
 
 
 
Output
JOB MAXGAL),
CLERK 1300
SALESMAN, 1600
PRESIDENT 5000
‘MANAGER 2915
ANALYST 3000
 
 
 
 
7a [poves [uanacen | 7a36|ooconoer| ans 5
rr [soort [anacrst | 725] ranaree| son a (Reter section 2.4)
7am [Fond _|anaLvsT [7866] ronares|eoco a
‘69_{SMTH_JCLERK _| 7802] 1217/1980 600 2 || 1. Display sum of saares of department 10
7ae2 [alten [sauzswan [7020 | eazoneer| iso] soo | a0 Z
ext [ward _|SaLeswan [7696] aazaroei |izeo] smo | van] | wlect dePtnosumtsl) Femme uy by det hing g
rest [wantin | saLesman | 7636 | oavzeraa1 | 1250} 1400 | 20 ae . ~
rats [TuRNER| sALesmaN | 7608] oataitg61|1500| 0 | 0 || Output
rare [roan foun [7768 ovranaes| co = DErINGL Ena
ra [ues [oun [ree] rocaoe| on % 0 =
 
 
 
 
 
play sum of salaries of department 10 and 20
 
Select deptno,sum(sal) from emp soup by depine being
deptno in (10,20);
 
 
 
Output
DEPTNO | _SUM(GAL)
20 10875
10 8750
 
 
 
 
Syllabus Topic : Order By Clause
3.5 _ Order By Clause
 
> (MSBTE - W-13, W-14, S-15, W-17)
   
Q.3.54 Explain order by clause with suitable example.
(Refer section 3.5)
 
 
 
To arrange the displayed rows in ascending or descending
‘order on given field(column) , Onder By Clause is used.
© ‘Syntax
  
Select * from table name order by coll col2. [dese]SE} )DEMs (MSBTE-Som.3.Comp
 
 
 
 
  
 
 
 
 
 
 
 
 
 
 
 
 
 
 
nas
Example : We need to display the employee informatio tn
their sending oer, the query wile
is order by Eames
— ‘Manager_| 18000
Ontput
B < Salesman | 13000
Eno Job _ a
Clerk
102 | ajay _ | Manager | 18000 [101 |
104 | Bhat | Manager | 1700 . <= Joins - Inner and Outer Joine
103 | Dinesh | clerk _ | 10000 Sue —
- [nner and Outer Joins
105 | Prajakta | Salesman | 13000 3.6 Joins In
101 | susheet | crerk | 12000
 
— Now to display same information in descending order on job
the query will be
 
 
Clerk | 12000
 
13000
10000
Salesman
 
Clerk
 
Manager_| 17000
 
18000
 
 
 
 
 
102 | Ajay | Manager
 
— Sometimes same records may available in field given for
Sorting criteria. In such case we can give names of more than
‘one columns for sorting purpose.
If data in first column is same, in such case the data of second
‘column can be taken into consideration for sorting. Consider
following table
 
 
 
 
 
 
 
 
 
 
 
 
Eno | Ename || Job | Sal 6. SELF
101 | Susheet | Clerk | 12000 Fig. 3.6.1 : Types of joins
102 | Dinesh | Manager | 18000 ios
ge To understand joins consider following two tables.
103 | Dinesh | Clerk | 10000 Table 3.6.1: Emp
104 | Bharati | Manager | 17000 Baa awn eae
= FHPNO| NAME | Jos _|war | aneDATe| sa ale
105 | Prajakta | Salesman | 13000
7380 |kwa | PaESoeNT| | 17r1s01 [5000
~ Here names of wo employes is same "Dies. Now sont ihe | [To [2
data we can mention Sorting fields as ename and job, BLAKE [Manacen |7e09 | oso | 2850
from emp order by ename,joby 77 Jota |wanacer || csnaries | 2450 [)
 
 
 
 
    
   
  
  
Explain various types of joins with exampi,
(Refer sections 9.6 10 3.6.3)
 
   
‘A. JOIN is a means for combining columns from om
 
  
 
(ceiftable) or more tables by using values common to exch.
= There are following types of Joins.
4, RIGHT OUTER
5. FULL OUTER, ]Interactive SQL & Adv. SQL : SQL Performance Tuning
‘i Inner Join (Equi Join)
Fas luones_[wascen | r20| oscars |zers a The INNER JOIN is used to display records that have
2 ‘matching values in both tables.
ras [ovort [avast 755 rarese| sno 2
ee
rae (roo [aNALrST_ |7566 | 2ar684 | ooo 20
Dsl
es [ours [oven [7502] armse0 | aco 2
usa [ALLEN [SALESMAN | 7686 |ozeoress | 1e00] 300 | 99
rar [wand |SALESWAN |7688 fooearest | 1280] sco | ao
zest {wan | saLesuan |7598 lonzareet | 1250] 1400 | 20
rout |TuRNER| SALESMAN |7698]]oa08rse1 1500] 0 | 20
INNER TOWN ub 2
rere |aoaws [cer | 788 |oxnanoea| 1100 2 be : ies
ON table_1.column_name = table:2.column_name
eo [saves oven [7698 saa | oso #0
Example
est |muuen overx — [7782 lovzate8 | 1300 10
Table 3.6.2: Dept INNER JOIN dept
DEPINO| DNAME | LOC onempadepino = deptdepinos a
10 _ | ACCOUNTING | NEW YoRK Output
20 | RESEARCH | DALLAS ENAME | JOB __|SAL|DEPTNO| _DNAME
30 | SALES CHICAGO CLARK [MANAGER |2450] 10 [accouNTING
uaa l(orentncne dl coston MILLER |cLERK [1300/10 _|accountiNG
KING __|PRESIDENT|s000] 10 [AccoUNTING
~ Inthe database having large amount of data itis not possible
eine Ford _|anatyst [3000] 20 [RESEARCH
‘© store the entre data ina single table, The related data may
te stored indifferent tables. In above tables emp and deptihe | [SCOTT |ANALYST [3000] 20 {RESEARCH
ata of employees is stored. JONES [MANAGER |2975| 20 |RESEARCH
~The EMP ble contain te basic information of employee | Tru levee ao] a0 [restancn
‘ike employee number, name, job(post) salary, department allaerualc
; AD/ 20 __|RESEAI
umber etc, The DEPT table contains the information of RESEARCH
‘ame employees about their depart names and locations. WARD |SALESMAN|1250] 30. |saLes
~ I we want to display whole information means basic | |sarmin|SALESMAN|1250| 30 [Sates
infmaon with deparment names and Toews then we | eT eT aT
Veto combine these two tables in query using joins.
5 JaMes |cLERK | 950] 30 |sALes
For using joins, we required a common column between both
the tbls In this example the EMP and DEPT ables contains | [atten [sacesman|i6o0] 30 [saves
a
common column DEPTNO. BLAKE |MANAGER |2850] 30 |saLEs
—‘oth tables
urns.
ches in
‘The INNER JOIN keyword selects all rows {rom
-Emp and Dept as long as there is a match between the
there are records in the “Dept” table that do not have mH
Emp", then such records will not got daplayed In Devt ble
department OPERATIONS of number 40 is present, but it f 90
displayed as no matching record is available in table em
3.6.2 Outer Join
      
 
 
 
Cuter Join is based on both matched and unmatched dats.
(Outer Joins subdivide further into,
‘Types of Outer Join
(1) Left Outer Join
(2) Right Outer Join
 
     
 
     
Hl
(3) Full Outer Join
Fig. 3.6.3: Types of outer join
Consider following two tables Stud_datal and Stud_data2
 
 
 
 
 
 
 
 
+ Stud_datat Table 3.64 : Stud_data?
[Roll No.| NAME | Roll No | Address
1 | Rahul 1 | Mumbai
2 | Kunal 2 | Pune
3 [ty 3 | Nasik
4 | Vinay 7_| Bangalore
S_| Preeti 8 | Goa
 
 
 
 
 
 
> (1) Left Outer Join
‘The SQL LEFT JOIN retums all rows from the left table,
even if there are no matches in the right table, Null values are
shown atthe place of right table values,
 
Fig.3.6.4
 
 
 
 
ame = ble-2.columnname,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
pp uble-Leolum™
{OM Stud
[eFTOUTER JOIN Stwel_date2 ON
siad_Datal rollno = Stud_Data2.Rollno;
TD | Name | 1 | Address |
1 | Ramat [1 Mumbai
2 | Kunal [2 | Pune
3 Jay 3 Nasik
4 | Vinay | NULL | NULL
3_| Pree | Nute [ NULL
 
 
 
> 2 Right Outer Join
Returns all rows from the
right table even if there are m
‘matches in the let table. Null values are shown at the plcecl
left table values
   
 
‘on table-1 columnname =
SELECT * FROM Stud. Daw
RIGHT OUTER JOIN Siud_Daua2
table-2.column-name
 
  
Sa
 
 
  
 
> iS3
a)
 
 
 
 
 
 
Interactive SQL & Adv. SOI
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
‘Name Dadar 3.6.3 SELF Join
Rahul 1_| Mumbai
Kenal 2 | Pune (Refer section 3.6.3)
Tay 3_[ Nasik = Self join is used Af as if the table
join i used to join a table to itself as if the table were
NULL 7_| Bangalore
a =o ‘wo tables. Virtual copies of the table are considered
Consider the table Emp
4 @ FallOuter Join ‘Table 3.65: Emp
‘he full outer jin returns a result with the matching data of | [EMPNO| ENAME |JoB ~  |NGR| HIREDATE| SA
the tables and then remaining rows of both left table an
ca fableand | Tras xe Jeresoent| | si7teat
then the right table,
7256 |avace |yswacer | 7290 |osovost | 250 x
7722_|o.arK |wanacen |7200|osoares [ase 0
7365 [owes |awacen |res0 |oavareat | 275 2
r7e8_|soort_|anatyst_|756 | rare | o00 2
7e02 |For [aways |7e66| rama | 00 »
7360 [wri [cuenk [race | zr9e0 | 800 2
7499 |auen | saresuan |r| cazareet | 1600] 00 | 20
a 7521 _|wano | saLeswan |reee| caraness | 1280] 500 | 99
FULL OUTER JOIN table-name2 /7e54 | MARTIN | SALESMAN | 7698 | o2e/t981 | 1250| 1400 | 30
‘on ble-L.column-name = table-2.column-name; rosa |rorwen| sarzsamy |7ec0| onveroe: |s00| 0 | 20
= Example ere _|aoans [cer _ |77es owas 1100 2
SELECT * FROM Stud_Datal 7300 |unmes lover | | voostaet | so »
FULL OUTER JOIN Stud_Date2 eat [unter |cuerx — |77se ovesree | 1300 10
$n (Std_Datal ollno= Stud_Data2. rollno);
 
 
 
 
 
 
 
 
 
 
 
Output
ID [Name | m | Address
1 | Rabut [1 _|_Mumbai
2_[ Kunal Pune
3 [ty [3 | Nak
4 | Vinay [Nutt | NULL
S| Preeti [ NULL | NULL
nou | nuit [7 _[ Bangalore
nuu[ wut] s_| Gos
 
 
 
 
 
 
 
 
 
 
 
 
 
= Here the MGR number indicates the name of MANAGER of
particular employee. For Example MGR of MILLER is 7782
‘which is EMPNO of CLARK. That mean CLARK is manager
of MILLER.
— Now we want to display list of employees with their manager
names. In this case we have to join this emp table to itself,
‘We will consier two copies of emp table, emp A and emp B.
From emp A we will retieve employee names while from
emp B we will get manager names;
7 Query
‘coame “Employes” B.ename “Manage
 
‘elect
‘A,emp B where A.mgr = Buempno;formance Tuy,
Bhoous ) 3.9 __ Interactive SQL & Adv. SO!
el employees whore s
‘To display records of employees lism
 
Employes | Nawoeer
FORD _ [JONES
 
 
scott _| JONES
ALLEN _| BLAKE
 
 
JAMES _| BLAKE
‘TURNER | BLAKE
 
 
 
 
MARTIN | BLAKE.
WARD _| BLAKE
MILLER | CLARK
 
‘ADAMS _| SCOTT
 
 
 
BLAKE | KING
cuark_| KING
gones | KING
 
smrrx | FORD
Syllabus Topic : Sub-querles
3.7 Sub-queries
 
 
 
 
Explain sub-query concept wh exampl
 
 
(Refer section
Writing @ query inside another query is known as nested
‘query or subquery. The inner query gets executed first then
the output on inner query is given as input to outer query.
Consider the previous emp table
Example : To display records of employees working in
SMITH's department
Select * from emp where deptno =
(Gelect depino from emp where ename = ‘SMITH,
Output
 
[ia soa eS
 
 
77e8_| scoTr| anavyst | 755 | 1209/1982 | aco0|
 
7902_{ FoR | anaLyst |7585| r200/991 | so00|
 
 
 
 
 
 
 
 
 
 
 
2
760 | swith | cuenK | 7e02| ran7ne60| 600 2
776 |apams| cuERK | 7788 | ov121083| 1100 2
 
Example
than the salary of FORD
Select * from emp: ‘where sal me é
(tec al rom emp where enanie = ‘FORD:
Output
evewo|eNAwe| 08
7o09_| kn [PresioeN]
 
  
 
 
[MGR |HIREDATE| SAL |CoMM|
1711981 |5000|
 
 
 
 
 
 
 
 
 
Example : To display records of employees Who ae sero
JONES
‘Gicc* om emp were rcdate <
{Gelect hizedate from emp where ename
 
ONES);
Output
 
IEMPNO|ENAME| JOB _ |MGR|HIREDATE| SAL |COMM|pePryq
 
 
 
 
 
 
 
 
 
 
 
7aeq | sum | LEAK | 7602] 12/7/1980) 600 a |
199 | ALLEN [SALESMAN] 7698) 02!20"881|1600] 900 | 99
7521_| war |satesman| 7608 oaze/961]1250| sco | a9
 
3.7.4 Correlated Sub-queries
 
Explain Correlaied subquery concept! wa
example. (Refer section 3.7.1) (8 Mari)
Th a SQL database query, a correlated subguery (also lnown
8 8 synchronized subquery) is a subquery (a query sesed
inside another query) that uses values from the outer gu
Because the subquery may be evaluated once foreach rv
processed by the outer query, it can be inefficient
‘ete isan example for atypical correlated subquery. In hs
‘example, the objective isto find all employees whose ss?
is above average for their department.
SELECT employee number, name
FROM employees AS emp i
WHERE selary > ( (
SELECT AVG(ealary)
FROM employees
WHERE department
= emp.department);
= _Inthe above query the outer query is
SELECT employee number,
FROM employees AS emp
name
 
WHERE salary >pide above nested query the inner query has to be ree
geod foreach employee
onelated subqueries may appear elsewhere besides the
‘WHERE clause; for example, this query uses a correlated
cabquery in the SELECT clause to print the entice list of
cenployees alongside the average salary for each employee's
department.
‘Agtin, because the subquery is correlated with a column of
the outer query, it must be re-executed for each row of the
 
 
name,
(ELECT ‘AVGGalary) : | Emp_id | emp name |’ “Address
FROM employees aoe . E1__| Kunal ‘Camp
WHERE department = emp.department) AS ‘ E2 | dy Tilak Road,
depariment_average E3 | Radhika | Somwar Peth
FROM employees AS emp; BA _| Sagar Warje
ES__| Supriya | LS Roed
 
 
ive SQL & Adv. SQL : SQL Performance Tuni
  
‘The changes made in a table get automaticaly reflected in
original table and vice versa,
‘Purpose of View
‘View is very useful in maintaining the security of database,
Consider a base table employee having following data
 
    
 
 
 
 
 
 
 
 
 
 
Bip namie Address
Et | Kunal Camp
2 |i Tilak Road
53 | Radhika Somwar Peth
eA | _ sues Warje
ES_|_ Supriya | 6700 | LS Road
 
 
1. Now just consider we want fo give this table to any user but
 (MSBTE - W-13, 5-14, S-15, W-15, S-16, W-16)
 
 
  
   
   
  
 
3.8.1 What is view? Write the syntax of create view.
(Refer sections 3.8 and 3.8.1) ‘
TST
3.82 Explain viows with example. a
(Refer section 3.8)
“numer [Tn SQL, a view is @ virtual table containing]
| the records of one or more tables based on SQL}
[statement executed. ‘
 
 
  
 
     
 
 
‘and columns. You
st like a real table, view contains rows
£29 add SQL functions, WHERE, and JOIN statements [0 &
View and present the data as ifthe data were coming from one
Single table
 
 
‘Also in multiuser system, it may be possible that more than
cone user may want to update the data of same table, Consider
two users A and B want to update the employee table. In such
‘case we can give Views to both these users, These users will
‘make changes in their respective views, and the respective
changes are done in the base table automatically.
———
Syllabus Topic : The Create View Command
3.8.1 The Create View Command
Consider existing table student
‘Table 3.8.1 : Student
 
 
 
 
 
 
 
 
 
‘rollno | stud_name | bdate | marks
to1_[ Kunal 12-02-2000 | 90
102 | Jay 07-08-1999 | 68
103_| Radhika | 05-04-2000 | 85
tos | Sagar 13-02-2000 | 70
105 | Supriya | 11-08-1999 |_72
 
 
 
 
SEEDBMS (MSBTE-Ser
 
m
Creating view having all records and fields fro!
existing table
= Syntax:
“GREATE oe fplace VIEW view name AS
Sevecr
FROM table_ name
few :
WHERE condition;
> Example
 
 
  
 
 
 
Creating a view of base table student with same structure and
all the records,
 
 
 
 
   
creating new view having specific recorg,
the fields from existing table
syntax
Greate or replace view jew name
‘ag select * from ex ing table_name
 
  
‘where cond
& Example /
(Grater replace view su. L views
asedlect
where marks > BOs
 
 
from student
 
   
 
 
 
 
 
 
 
 
 
 
 
 
 
   
‘Output
Outpar Table 3.8.4 : stud_view3
‘Table 3.8.2: stud_view! Bl en
‘stud_name
roll_no | studname’| < bdate
1o1_[ Kunat 12.02.2000 [90 101 a
102_[ tay 07-08-1999 [68 103 | Radhika
103 | Radhika [05-04-2000 [ 85)
10s _[ Sagar 13.02-2000 [70 '@.3.8.3 Consider following schema,
105 | Supriya [11-08-1999 [72 EMPLOYEE-DETAILS (empname, empld, 008,
 
 
 
 
 
 
2. Creating view having specific fields but all the
records from existing table
= syntax
 
 
cea riew view name
 
 
7 Example
 
(Create or replace ‘Wiew stud,
4s select roll_no, name from student;
   
ied
 
Output : The newly created view will be
Table 3.8.3: stud_view2
 
 
 
 
 
 
 
 
 
 
Follsno [stud name
tor_| Kunal
102, Jay
103,
tos | Segar
105_| Supriya
   
 
   
  
   
salary, job)
Create a view on EMPLOYEE-DETAILS havrg
attribute
(empname, empld, DOB, salary, job) whes
‘salary is greater than 20,000
(Reter section 3.8.1)
Create of replace view v1 as select empname, empl, DO,
Salary, job from employee_details where salary > 20000,
    
  
   
Q.3.8.4 Consider following schema :
Depositor (Acc_no, Name, PAN, Balance) i
Create a view on depositor having atvbst
(Acs_no, PAN)
‘Where balance is greater than 100000.
(Refer section 3.8.2)
 
PAN ft
Create oF replace view v2. as select Ace_n0,
‘epositor where balance > 100000;
 
 
 
 
 
“aja as eens
4=
342
 
& us (wSBTE-Sem.3-Comp
2 syllabus Tople : Updating Views
je2 updating Views
upd ain i id 10 update the eons of view, Upton
antes oii ale also, Means th sae changes
we male in the original table also,
 
& Example:
We are updating marks to 73 of student having roll_no 102.
   
In this case marks of roll_no 102 will get updated in both
view view as well as table student.
 
 
 
 
 
 
 
 
 
 
 
 
 
Output
View - View!
Tolizpo|| stud.name | bdate | marks |
tor | Kunal 12-02-2000 | _ 90
102 | hy 07-08-1999 | _73
103 | Radhika | 05-04-2000 | _ 85
tos | Sagar 1302-2000 | 70
105 | Supriya | 11-08-1999 | 72
Output
Table 3.8.5 : Student
rollino | stud.name | tbdate | Marks
tor | Kunal 12-02-2000 | _90
102_| hay 07-08-1999 | _73
103 | Radhika | 05-04-2000 | _ 85
10s_| Sagar 13-02-2000 | _70
{105 | Supriya | 11-08-1999 | _72
 
 
 
 
 
 
‘There are some restrictions on the. modification with respect
view,
Interactive SOL & Adv. SQL : SOL Performance Tuning
In case of view containing joins between multiple tables, only
insertion and updation inthe view is allowed, deletion is not
allowed
Data modification is not allowed in the view which is based
‘on union queries.
Data modification is not allowed in the view where GROUP
BY or DISTINCT statements are used.
  
In view the text and image columns can't be modified.
Syllabus Topic : Views and Joins
3.8.3 Views and Joins
‘We can create views by joining two or more tables.
= Consider folowing two tables
‘Gate lable employee(
ID number(3), : |
‘name varchar (10). a
salary ntunber(6) ); a
create table job
ID muimber(5),
title nvarchar (10),
Wenesiarsauabeatal)
 
Now we will create view on these tables
CREATE VIEW myView Seer
  
 
 
SELECT eID,
Employee e , job j
    
Where elD =D
 
Syllabus Topic :_Views and Sub-queries
3.8.4 Views and Sub-queries
= We will create view having records of employees working in
SMITH’s department
 
‘Cieaie ore replace view vi as
 
Select * from emp where depino = a
  
\(celect deptno from emp where ename = ‘SMITH;v
 
 
     
  
 
 
 
 
 
 
 
 
 
Adv, SOL: SOL Petr
Outpt we [een ee
“" [TJ | astich neta to populate the rinary
EWPNO|ENAME| Joe - [waR|HineDATE| SAL | COWM| DEPINO incrementing and returning its value
7266 | zones | wanacen | 739 | oxcarast | 2075 2 sequences ae used in Database Decaise many py
7708 | scoTT| avaLvsr | 7286| 2081682 | 200] 2 pie ech row baving unis Yaluesinthe ty,
7902 20 jide an easy was
ono [naar [70] ene | = tre sequences provide 29 60 8Y € teens
7369 | swma | cueri | 7902] rarzt990 | 800 20 values forthe records inthe table, Sequences ae
7e76 |aoams| LEAK |7760| 01/12/1983 1100] a integer numbers like 1, 2, 3,4. ee fy
 
 
 
 
 
 
 
————————
Syllabus Topic : Dropping Views.
3.8.5 Dropping Views
 
> (wseTe -S-17)
  
 
 
Syllabus Topic :_ Sequences
3.9 Sequences
 
 (UsBTE ~$-13, W19, $14, Wed, We15, $16, W-17)
3.9.1 What is sequence ? What are the.
‘operations with respeot to sequences 2.
    
 
    
 
 
  
    
  
   
    
    
 
"(Refer sections 3.9 and 3.93.1)
2.9.2 What are sequences ? Why Its Used ? Create
"sequence for student table. coe i
|. (Refer sections 3.9 and 3.9.1)
  
39,3, Explain sequences with example,
(Refer sections 3.9 and 3.9.1)
@.3.9.4 Define sequences. Create sequence for student
table. (Refer sections 8.9 and 3.9.1)
 
  
 
  
= Primary key is used in a'sble to maintain unique value for
the records in the table. Primary key is applied on one column
co combination of columns in the table. Here sequences are
‘another concept which helps to maintain unique values for
various records inthe table
 
  
 
_ pecause of database sequences, there is ng
isolation occured ‘Tat means 0 OF MOE tana
not get the same value.
So database will not affecting when 0 oF mo i
accessing the same transaction at the same tne, Wig
database sequences, it is not possible to generat thing
incrementing numbers.
= Sequences are just ike counter which generates see
numbers".
—_———
Syllabus Topic :_Creating Sequences
3.9.1 Creating Sequences
 
9.9.5 How to create a sequence explain wi
 
example ? (Refer section 3.9.1) =
© Information required for generating numbers .
.
= The starting number. ‘
= The maximum number generated by a sequence
— For generating the next number need to increment ihe We
7 Create sequence ’
x
~ Te evento a sequence CREATE SEQUENCE suet |
used,
~ _ CREATE SEQUENCE statement creates sequence inet 1
~ Sequences automatically generate primary key value® :
~ Sequence number is generated by the sequence SH | (
Which just create unique values for records in anbsei!t |
‘increr i “re
ments its value automatically which is indere™ (
the transaction committing or rolling back. 1
is
One user can never get the sequence sumer Wt
fsenerated by another user. |
We can vib
acess values in SQL statements wing CU
AMS (MSBTE-Sem. 3-Com,
(Glosssseresom econ 1 Intoractive SOL & Adv. SOL: SOL Performance Tuning
  
‘once a sequence is created, itis used to returns the current
salu ofthe sequence.
‘To increment the sequence and retums the new value,
NEXTVAL clause is used,
or syntax
GAEATE SEQUENCE 
MAXVALUE  Pa
 
MMINVALUE  CYCLE CACHE]
7 Example
CREATE SEQUENCE student
MINVALUE 1
|“ MAXVALUE 100
START WITH 1
INCREMENT BY 1
“CACHE 20;
 
 
© Increment by
= Increment By clause specifies the time interval between the
sequence numbers. Sequence number can be any positive or
negative value but not zero. If this clause is omitted, by
default value is 1.
~  MAXVALUE and MINVALUE
‘Tis claus
values which are generated by sequences.
used to specify the maximum or minimum
 
~ Start with
This clause is used to specify the first sequence number
generated by using START WITH clause.
= Cycle :This clause is used to specify that the sequence
Continues to generate repeated values.
~ Cache
“This clause is used to specify how many values fo generat it
advance and those values are kept in memory for faster
access of data.
———— eo
Syllabus Topic ; Altering Sequences
3.9.2 Altering Sequences
 
  
Q.9.9.6 How to alter a sequence 7
(Refer section 3.9.2)
 
 
(5 Marks)
 
SEQUENCE
Sequenced can be altered using ALTER
statement. Start value of sequence cannot be altered.
> syntax
 
   
   
  
‘RUTER SEQUENCE Sequence Name>
{INCREMENT BY 
UMINVALUE  example
CREATE INDEX ind
onstudesttud_aame),
3.10.2 Composite index
Sometimes duplicate records may available in colnet *
Such case the composite indexing is better option to index
‘This inde is created ona multiple columns ofa table
© Syntax
 
 
 
 
 
3.10rr
pas (MSBTE-Ser
 
3-Comp)
7 Example
gee NDEX ind2 on student(hid_ name marke)
 
4103 unique Index
A unigue index does not alow any duplicate values to be
see it te able
syntax
§EATE UNIQUE INDEX index name
(N ublename (column column2,
 
Example
(GENTE UNIQUE INDEX ina
 
‘onatadent(uid_name}s
 
310.4 Implicit Index
Implicit indexes are indexes that are automatically created by
the database server when an object is created. Such indexes are
 
created for primary key and unique constraints
Displaying Index : To display index information regarding table
following query is used.
© syntax
(SevidSe fm abe name:
© Example
  
‘Show index rom suidents
310.5 Dropping Index
* Purpose of Dropping Index
= To remove an index or domain index from the database you
‘can use the DROP INDEX statement.
Database invalidates or cancel all objects that depend onthe
lable ie. packages, package bodies.
functions, and procedures, When you drop an inde.
Including. views,
‘The global partitioned index is partitioned by a range oF hash,
Patiioned index, if we drop this global partitioned index
then al he index partitions als drorPed-
All the inden partons and sub partitions are also dropped
When you drop a composite-parttioned index:
«
Example
DROPINDEX pr Gustomes
 
 
 
 
}6_Interactive SOL & Adv, SQL : SL Performance Tun
    
Syllabus Topic : Synonyms - Creating Synonyms,
Dropping Synonyms
3.11
 
Synonyms : Creating Synonyms,
Dropping Synonyms
> (MSBTE - S-14, W-14, W-17)
 
 
ATA Whal ae Synonyms 7 Write @ syntax for creating
| asynonym. eee
(Refer sections 3.11 and 3.11.1)
BIN
Q.3.11.2.What are synonyms ? How to create and drop
“ “synonym? oe, Wa ee
U atoroechone a /f;31 i and atte) =e
name for
    
  
 
 
= Asynonymis an alias or alternate
table, view, sequence, or other schema object,
= They are used mainly to make it easy for users to access
database objects owned by other users.
= ‘They hide the underlying object's identity and make it harder
for a malicious program or user to target the underlying
object.
= Because a synonym is just an alternate name for an object, it
requires no storage other than its definition.
= When an application uses a synonym, the DBMS forwards
the request to the synonyms underlying base object.
= There ae two major uses of synonyms:
Major uses of synonyms
1. Object invisibility
2, Location invisibility
Fig. 3.11.1 : Uses of synonyms
      
   
1. Object invisibility
synonyms can be created to keep the original objet hidden
from the user
2, Location invisibility
Synonyms can be created as aliases for tables and other
‘objects that are nat part ofthe local database.formance 7
DBMS (MSBTE-Sem. 3-Cor a-17 Interactive SQL & Adv. SOL : SOL Pe 162 Tunin,
3.11.1 Creating Synonyms 3.11.2 Dropping Synonyms
~ Tie following code shows how to create a synonym forthe | The fllowing code shows how drop 2 symonym:
‘employee table:
= syntax
    
 
aggto Vata
 
 
 
 
PL/SQL Programming
 
 
  
   
   
 
    
PUSAQL data Types, Variables, Constants.
- Cursors
Cursor for loops, Parameterized Cursors.
eating Trigger, Deleting Trigger.
Introduction of PLISQL, Advantages of PLISGL, The PUSQL Block Structure, PL/SQL execution environment,
Control Structure : Conditional Control, iterative Control, Sequential Control
Exception Handling : Predefined Exception, Usor defined Exception,
+ Implicit and Explicit Cursors, Declaring, Opening and closing a cursor, Fetching a Record from Cursor,
Procedures : Advantages, Creating, Executing and Deleting Stored Procedure,
Functions : Advantages, Creating, Executing and Deleting a Function,
Database Triggers : Use of Database Triggers, how to apply database Triggers, Types of Triggers, Syntax for
 
Syllabus Topic : Introduction of PUISQL
41
Introduction of PL/SQL
—  PLISQL stands for Procedure Language / Structure Query
Language. It is the combination of SQL along with the
procedural features of programming languages.
= PLISQL includes procedural language elements such as
conditions and loops. It allows declaration of constants and
variables, procedures and functions, types and variables of
those types, and triggers. It can handle exceptions (runtime
errors).
~ Arrays are supported involving the use of PLISQL
collections. It has included features associated with object
orientation. One can ereste PL/SQL units such as procedures,
functions, packages, types, and triggers, which are stored in
 
the database for reuse by applications.
 
Syllabus Tople : Advantages of PUSQL
  
4.1.1 Advantages of PLSQL
> (MSBTE - W-14, 5-15, W-15, 5-16)
 
Q.4.1.1 State two advantages of PUSOL and give its
block structure.
(Refer sections 4.1.1 and 4.1.2)
Ca
Q.4.1.2 Draw the block structure of PL/SQL. List’
advantages of PUSQL.
(Refer sections 4.1.1 and 4.1.2)
‘
4.1.3 What are advantages of PUSQL?
(Refer section 4.1.1)
TERRI
4 Give any four advantages of using PUSQL.
“(Refer section 4.1.1)7. Block Structure
  
 
  
Tight Integration with SQL
9, Procedural Language Capability
 
  
   
  
 
 
    
5. High Productivity
 
6. Portability
 
7, Scalabity
 
  
 
8, Manageability
 
9, Support for Object-Oriented Programming
  
70. Suppor for Developing Web Applications
PUSQLP,
    
ored subprograms of PLISQL ine
application processing on gy
 
scalability By ent
database server
 
anageablity: PLSOL sor SUPPERS hey
Many itned on the SAADASE SEE Which
oe Senge witout Raving 10 affect TE spicing
oe nether, thereby increasing the msninabiy,
support for Object-Oriented Programming;
PUSOL supports object-oriented programing andj
use of "Abstract Data Types"(ADTS).
Support for Developing Web Applications : PLisg
nitows creating applications hat generate Web pag,
that directly access the database
| Support for Developing Server Pages + PLS.
Server Pages (PSPS) allows developing web pages wit
dynamic content.
Error Handling : PLISQL handles exception
effectively during the execution of a PL/SQL program,
 
11. Suppo for Developing Server Pages
‘Syllabus Topic : PLISQL Block Structure
 
 
12, Eror Handling
 
 
 
Fig. 4 : Advantages of PLISQL
Block Structure : PL/ SQL consist of blocks of code,
which can be nested within each other, Each block
forms a unit of a logicel module and is stored in the
database so that it can be reuse.
‘Tight Integration with SQL: PLISQL is tightly
{integrated with SQL, which is popular and most widely
used database manipulation language,
 
Procedural Language Capability : PLISQL includes
procedural language constructs such as conditional
statements and looping constructs,
High Performance : PL/SQL allows sending the entire
block of statements to the database, thereby reducing
trafic between the application and the database
High Productivity : PLISQL allows writing compact
‘code for manipulating data, PLISQL can query, change,
‘nd automatically update data in a database,
Portability : PLISQL applicaions can run on any
operating system and platform where Oracle Database is
running.
 
4.1.2 PL/SQL Block Structure
> (MSBTE - W-13, S-14, W-15, S-16, W-16, $-17)
    
        
      
   
 
   
    
    
@.4:1.5 Give the biock structure of PUSQL and expla,
‘main components,
(Refer section 4.1.2)
Q. 4.1.6 Explain block structure of PL-SQL.
(Refer section 4.1.2) Ens
Q. 4.1.7 Explain PL/SQL block structure.
(Refer section 4.1.2)
  
    
Esa
 
 
   
 
 
Header
Is
Declaration Section
BEGIN
Execution Section ‘
EXCEPTION
Fe
: Exception Section ey
 
Fig. 4.1.2 : PUSQL Block Structure43 PUSQL Programming
 
   
   
    
   
 
 
  
    
  
  
  
    
  
  
  
    
   
   
     
  
  
  
 
   
 
 
‘The basic unit of PLISQL is called a block, which allows
grouping of related declarations and statements. Any PL/SQL
program is made up of blocks, which can be nested within each
other.
PL/SQL blocks categorization
PLISQL categorization
1, Subprogram
 
  
 
 
 
 
 
2, Anonymous block
 
Fig. 4.1.3: PL/SQL categorization
> 1. Subprogram
A subprogram is « PL/SQL block stored in the database and
called by name from any application. A subprogram could be
8 procedure ora function
2. Anonymous block
‘An anonymous block is a PL/SQL block that appears in the
application but is not named or stored in the database. An
anonymous block can appear wherever SQL statements can
appear.
Structure of PSL Block
It consists of the following sections
1. HEADER - Header section (optional)
<<< label >> (optional)
2. DECLARE - Decl
Declarations of local types, variables, & subprograms
section (optional)
 
3. BEGIN - Executable section (required)
Statements (which can use items declared in declarative
past)
4. [EXCEPTION - Exception-handling section (optional)
Exception handlers for exceptions (errors) raised in
executable part]
Header Section
= Header section is relevant only for subprograms. It includes
the name, parameter list and RETURN clause for functions. It
determines the way the subprogram must be called,
2. Declaration Section
Declaration section of a PL/SQL Block stars with the
Keyword DECLARE. Declare section is optional and is used
to declare temporary placeholders like variables, constants,
records and cursors, used to manipulate data in the execution
section,
3. Execution Section
[Execution section starts with the reserved keyword BEGIN
and ends with END. This section is a mandatory and is the
section where the program logic is written.
— Looping conditional statement and SQL
statements form a part of execution section.
statements,
4. Exception Section
 
— The Exception section starts with the reserved keyword
EXCEPTION, Enrors in the program can be handled in this
section, so that the PLISQL Blocks terminates gracefully and
not abruptly with errors.
 
Comments can be used to document code, Every statement
in the above three sections must end with a semicoton ()
———
Syllabus Topic : PLISQL Execution Environment
4.1.3 PL/SQL Execution Environment
~  PLISQL engine is a tool used to define, compile, and run
PLISQL program units.
‘The engine can be installed in an application development
tool, such as Oracle Forms,
~The PLISQL engine accepts any valid PLISQL block as
input
‘The engine runs procedural statements and sends SQL.
statements to the SQL engine.ip
i PUSQL Program
4 value wit
DEMS (MSBTE-Sem. 3-Comp) Tre asa Types SEE va hg °
a1 :
PLSQL Engine <
[Procedural + boolean, number, ete,
scam | Eero | pxamples  boolea
 
 
 
 
 
 
 
 
 
 
: vy 2, Composite Dats Types «oes wales Ct he gg
"component
‘Examples collections and records
ca a Reteence Dota Types - olds vale, cle pi,
sed to reference oer objects
   
LOB Data Types ~ holds values, called Log
‘pectving location of Tage obJE, SUCH as gp
images, motion pftures et
Fig. 4.14: PLISQL Execution Environment a4
= As shown in the Fig. 4.1.4 the database processes PLISQL
 
ons 4, Salar Data Type
~ When a aptiaon devetpment wl prseses PLSQL | aaigs a single vahe and Mas 0 ine
1 = Ifa PL/SQL unit contains no SQL statements, the local | poolean and datetime data :
‘engine processes the entire PLISQL unit. eres es
———
Syllabus Topic : PLISQL Data Types 5, Nemerlo,detstype,soces seal, nombers, floeig-yct
numbers, zero, and infinity.
4.1.4 PLISQL Data Types © NUMBER js the most commonly used numeric dit
> (usete-s-15) on
 
© Other umes dita types in PLSQL ince
BINARY_FLOAT, BINARY_INTEGER, DECIMAL
= very PLSQL varie, const o a parameter hs data FLOAT, INTEGER, NUMBER, REAL PLS_INTECER
 
 
 
type which determines its storage structure, the values that SMALLINT, NATURAL, ete
‘can be assigned to it and operations that can be performed on | (li) Character Data Type
it
© Character data type stores character and alphanumet
= Following are the Data types of PL/SQL data in strings. VARCHAR2 is the most comod)
Data types of PL/SQL
1, Scalar Data Types:
Used character data type,
     
   
   
   
Other character data types in PL/SQL include CHA®
NCHAR, VARCHAR2, NVARCHAR2, LONG. RAY’
STRING, ROWID ete,
 
2, Composite Data Types:
 
(iii) Bootean Data Type
 
‘3. Rotorence Data Types
 
© BOOLEAN data type stores logical values, whi?
4, LOB Data Types ‘TRUE, FALSE or NULL,
 
Fig, 4.1.5 : Data types of PLISQLtt,
 
ISBTE-Som. 3-Comy
Ioens Ms '
[NULL represents an unknown valve, since SQL has no
 
 
dat type equivalent t0 BOOLEAN, itis not possible to
sosign a BOOLEAN valle 10 database table column
4g Selest or fetch the vale ofa database table column ito
a BOOLEAN variable,
4 UseaBOOLEAN valve ina SQL statement
iy) DaeTine Data Type
4 DaeTime stores date and time values with fractional
precision of seconds.
fo The different DateTime data types used in PLISQL
programs include DATE, TIME, TIMESTAMP,
‘TIMESTAMP WITH TIME ZONE, INTERVAL DAY
TO SECOND, INTERVAL YEAR TO MONTH etc
2, Type Attribute
‘The variables of PLISQL often deal with tble columns and
therefore should have the same datatype as the column of the
sable
A special attribute known as ‘TYPE allows us to declare a
data item of the same data type as previously declared
variable or column of the table without having to remember
The item declared with %TYPE is called the referencing
litem, and the previously declared item is called the
referenced item.
= Referencing item does not inherit the initial vaiue of the
referenced item.
sm changes, then the
 
~ Ifthe declaration of the referenced
referencing item changes accordingly
——
- Syllabus Topic : Variable
41.5 Variable
~ Variables are placeholders that hold the values which Keep
changing throughout the execution of a PLISQL Block.
Before using any variable, it needs 10 be declared in the
PUSQL Programmi
© syntax
variable_name datotype {= value Js
Example
1 you want to store the current salary of an employee, you
can we avaible.
DECLARE
emp_sal mumber(®)
= “psa is avaible of datatype number and of length 8
= We can assign values to variables in the two ways given
below. Assigning values to variables directly
 
variable_name:= value
= Assigning values to variables from the database columns by
using a SELECT... INTO statement
SELECT column_name
INTO variable_name
FROM tbe sane
WHERE condition}:
= Example
To display he salary of specific employee using variable var_sal
 
SQL> DECLARE
var_sal number(6);,
3 var_emp_no number(6) := "E001";
4 BEGIN
 
SELECT salaryINTO vi
6 FROM employee
 
WHERE emp_no = var_emp_.
8 dbms_output.put_fine(var_salary);
9 END;
101
 
declaration section of the PL/SQL block.- —
 
© Scope of Variables
PLISQL allows the nesting of Blocks within Blocks and
based on their declaration, the variables can be classified into two
types.
  
 
(Local variables
 
( com) 46
iB) sTE-Sem. 3-Comp)
DBMS (MSE a
PUSQL Pro
  
SUSYGONSTANT NUMBER (6.2) = 3.14). 22
oi 2
‘Syllabus Topic : Control Structure
—_ Ow
4.2 Control Structure
42_ Contro! Sie
> (MSBTE - sip
 
 
(i) Global variables
 
 
 
 
Fig. 4.1.6: Variable types
> © Local variables = Variables declared in an inner block
Which cannot be referenced by outside blocks.
F i) Global variables - Variables declared in an outer block
Which can be referenced by itself and by its inner locks,
‘7 Handling Variables in PL/SQL,
~ Variables must be declared they are used
~The PL/SQL variables ean be a scalar type such as DATE,
NUMBER, VARCHAR2, BOOLEAN, LONG and CHAR, or
‘8 composite type, such as VARRAY.
~ Only TRUE, FALSE or NULL can be assigned to
BOOLEAN type of variables
~ _ S8TYPE attribute can be used to define a variable which is of
the same type as a database column's type.
‘Syllabus Topic : Constants
4.1.6 Constants
A constant is a named memory location which holds a value
to be used in a PLISQL block that remains unchanged
throughout the execution of the program, Just like the
variable a constant also needs to be declared in the
declaration section.
 
 
 
 
syaoseaeyamecarmmcerarmnameenentes
t_name CONSTANT data_type:= VALU
 
@.42.1 What are the various control stuctig
"statements used in PUSQL?
    
 
(Refer section 4.2)
 
  
‘The Control Structures decide the execution flow of the
program depending on the conditions defined by the programmer,
Following control structures can be used individually or i»
‘combination to deal with a given problem,
(1) Seleetion control structure is used t0 test a condition, aod
then executes one sequence of statements instead of anote,
4epending on which condition evaluates to true.
Condition can be any variable or expression and always
‘fetus 2 BOOLEAN value (TRUE ot FALSE). The selection
statements include IF and CASE Statements,
@
‘eration contro structure repeatedly executes a sequent
of statements ss long as a condition evaluates to ie
Counters ate used wt
‘ed which can be incremented or decremented
for getting desired numberof iteration,
@
the order in which they occur
Syllabus Topie? Conditional Contror
4.2.4 Conditional Controt
> MMSBTE- Wet, wis)
0/422 Bela conationalconiol staat ots SG
| (Refer section 4.2.1) pa
 
 
 
 
 
 
 
 
 
ae
ayy
We
 
LEO ng GEL ffa a a Sea
MSBTE-Sem.3-Cor
paws ER PUSAQL Programming
42.(A) IF Statements
     
 
1.1F statement
 
 
 
2. IF-THEN statement
 
 
3. IF-THEN-ELSE Statement|
ree
4. NESTEO IF-THEN- ELSE
statement
el]
Fig. 42.1: IF statements
 
 
 
 
 
> () Statement
= An “IF statement executes a sequence of statements,
‘depending on the value of a condition,
When the condition is satisfied, the necessary option will be
executed.
= There are three forms of IF statements: IF-THEN, IF-
‘THEN-ELSE, and IF-THEN-ELSIF.
‘Conditions ean be formed using relational operators given in
following table,
= These operators help us to define different kind of conditions
or combination of conditions using following operator
Symbols.
'* Relational Operators
 
  
Description!
Greater than Operator
(Greater than or equal t9 Operator
Less than Operator
Less than or equal to Operator
 
 
  
 
  
 
 
Exqual to Operator
‘Not equal to Operator
Returns tue if the character pattern
‘matches the given value
"Retums toe if the value is im the given
range
Returns tue if th
Retumns te ifthe value is NULL
 
 
7 value is i the list
 
 
> @ IF-THEN Statement
‘The simplest form of IF statement associates a condition with
8 sequence of statements enclosed by the Keywords THEN
and END IF (not ENDIF.
= "IE Then’ executes the statement or a block of statements if
the condition returns true.
 
Example
TsouS DECLARE ee
22 mom] NUMBER(O): :
'§ num? NUMBER(6);
4 BEGIN
‘5 mum] := 16;
 
fame i ci
1 1P mom) < nad THEN
|B-DBMS_OUTPUT-PUT_LINE(numl | | "is less than’ |
num2); :
 
   
 
PLISQL procedure successfully completed
© Example 2aii
& PUSQL Prostar,
xloens wsere 48 9
}| DBMS (MSBTE-Sem. 3-Comp) —
= BpBMS_OUTPUTPUT_LINEFAIL): ;
an VARCHAR(2):
4 BEGIN
  
S str] := 'TECHMA
6 str2 = TECHMAN,
 
TIF str] LIKE s2 THEN
‘8 DANS OUTPUTPUT_LINE(trt || same ike I]
su)
END IF;
OEND;
a
‘TECHMAX is same like TECHMAX
PLISQL procedure successfully completed
> (3) IF-THEN-ELSE Statement
In this type of IF statement there isa keyword ELSE followed
by an alternative sequence of statements which can execute when
the condition with if evaluates to false.
& syntax
IF condition THEN
te, statements;
ELSE
false_statements;
END IF;
= Example 1
1 SQL> DECLARE
2 percent NUMERIC;
SBEGIN
 
4 percent := '60
SIF percent>30 THEN
6 DBMS_OUTPUT-PUT_LINE(PASS),
7 ELSE
‘ENDIF;
10 ENDs
uy
FAIL
PLISQL procedure successfully completed
© Example 2
SQL> DECLARE
2 strl VARCHAR(12);
3 str2 VARCHAR(12);
4 BEGIN
5 str] := "TECHMAX':
 
sn?
7 IF ote] LIKE str2 THEN
8 DBMS_OUTPUT.PUT_LINE(etr1 | | 'is same as! || su,
ELSE
10 DBMS_OUTPUT.PUT_LINE(stel | | ‘is not same as' ||
ste);
END
 
12 END;
18/
TECHMAX is not Same as techmax
PUSQL procedure successfully complete.
> NESTED IF-THEN. ELSE statements
IF state
Statements can also be nested inside other IF state
wl
 
This allows us
: us to check more than one condition in 2 $
ecute the 5
he appropriate block of statements depending °
conditions,|| a
 
 
g aTE-Sem. 3-Comy
loam (St Bh PUSQL Programming
syntax
{-Zeiaditon >
‘HEN
ASIF 
‘THEN
ELSIF 
‘THEN
ENDIF,
© Example 1
{8OK> DECLARE
2percent NUMERICS
SBECIN
 
Apecent = '83',
SIF percent >= 75 THEN
GDBMS_OUTPUT.PUT_LINECDISINCTION):
TELSIF percent >= 60 AND percent <75 THEN
EDEMS_OUTPUT.PUT_LINECFIRST CLA‘
 
ELSIF percent >= 50 AND peroent'<60 THEN
1ODBMS_OUTPUT.PUT_LINE(SECOND CLASS"
  
TWELSIF percent >= "40! AND percent <50 THEN
12DBMS_OUTPUT.PUT_LINE(PASS CLASS);
ISELSE,
  
 
SEND IF,
IGEND,
Wy
DistINCTION
PUSQL procedure suscessfully complete.
 
‘F Example 2 : Greetings as per hour of the day
1 SQL> DECLARE
2 hour VARCHAR(10):= TO_CHAR(SYSDATE,HH24));
 
3 BEG
 
4IF hour > 16 THEN
5 DBMS_OUTPUT.PUT_LIN
 
{E(Good Evening);
GELSIF hour > 12 THEN
7 DBMS_OUTPUT.PUT_LINE( Good Afternoon’):
SELSE
9 DBMS_OUTPUT.PUT_LINE(Good Morning
JOEND IF:
TLEND;
12/
Good Morning
PLISQL procedure successfully completed
4.2.1(B) CASE Statement
= The CASE statement can be used when a single condition
may evaluate multiple results and therefore multiple actions,
Generally CASE is used when there ate more than three
altemativeastions to choose from.
= CASE Statements in PL/SQL has following forms:
CASE statement
1. Simple CASE
   
 
 
 
 
2, Searched CASE
 
> Simple CASE
 
Here, there is a ‘Selector’, which determines which
block would get executed. It executes the block of statements
where the match forthe selector is found. Default Mock is executed
if no match is found forthe «We >FUSE statements ni
END CASES
= Example
consider an example for student grades wsing the CASE”
WHEN Statement
SQL> DECLARE
2 grade CHAR()s
3 BEGIN
4 grade := 1A",
‘5 CASE grade
6 WHEN ‘0° THEN :
DBMS_OUTPUT.PUT_LINE(Outstending’)
7 WHEN’A' THEN
DBMS_OUTPUT.PUT_LINE(Excelent);
8 WHEN 'B'THEN
DBMS_OUTPUT.PUT_LINE(Good!);
9. WHEN'C THEN
DBMS_OUTPUT.PUT_LINE(‘Satisfactory));
10 WHEN 'F THEN DBMS_OUTPUT.PUT.LINE (Fai
11 ELSE DBMS_OUTPUT:PUT.LINE(Invalid grade),
12 END CASE;
 
13 END; UGhenas
My.
Excellent
PLISQL
 
 
 
 
 
  
  
 
 
    
  
   
case
re search conditions
sselecor’ but the search conditions
mine whieh group of actions wiy 4.
 
END GAS
© example
 
GWHEN day = 1 THEN ‘Monday’
 
TWHEN day = 2 THEN Tuesday’
‘SWHEN day
 
THEN 'Wednesday’
WHEN day = 4 THEN "Thursday'
 
JOWHEN day = 5 THEN ‘Fria y
 
TAWHEN day = 6 THEN ‘Saturday’
AR WHEN day = 6 THEN ‘Sunday!
 
 
 
ASELSE No such grade!
 
AWEND;pUSQL procedure successfully completed.
———
ee
‘Syllabus Topic : Iterative Control
Iterative Control
42.2
> (MSBTE - We13, W-14, W-16, W-17)
Joop ih examp
 
 
() Loop Statement
Loop is the simplest form of looping control structure which
is used to repeatedly execute a set of statements until the exit
‘codition is reached.
 
‘Ad EXIT STATEMENT
Et stement is used to exit out of a Loop. EXIT isthe oy
‘ay of terminating the LOOP so that it does not become an Infinite
Loop,
© Syntax
STN
  
co)
EXrT statements can occur anywhere ise 81000
EXIT is used alone, it will terminate the curent 109P
 
‘whenever it is encountered.
    
 
  
TEEXIT is used with WHEN clause, then the current loop is
terminated only when the condition given after WHEN is
satisfied.
‘© Example : Printing table of 11
 
PLISQL procedure successfully completed.(B) While Statement
While statement executes series of statements repeatedly #
¢ condition
Tong as the given condition remains true. When th
evaluates to false, the loop terminates automatically.
© syntax
WHILE condition LOOP
Statements;
END LOOP;
Example
1 SQL> DECLARE
2 num NUMBER:
BS BEGIN +
 
‘4num := 13;
5 WHILE num<= 110
6 LOOP
7 DBMS_OUTPUT;PUT_LINE(aum):
Bum := num + Vy
 
9 END LOOP;
10 END;
ay
Output
a
PLISOL procedure successfully completed.
PUSOL Progan
<=
 
  
  
(c) For Statement M4
nero op eres erases ES TM ('
a |
vsed ed when the FOR loop sg, 1
‘The range is evaluat
executed. ae
tered and the statements a7 executed until Upper bound i
. hed. Here operator is used to specify range,
read se
@& syntax
FOR counter IN [REVERSE] lower_bound..
‘upper_bound LOOP
Statements
END LOOP;
“The sequence in which FOR wil be executed i given below :
Step 1: Counter is set to lower bound.
Step2: If counter is less than or equal to upper bound then
statements are executed otherwise loop is terminated.
Step 3: Counter is incremented by one. It is not possible ©
increment counter by more than one.
Step4: Repeat Step 2.
© Example
1 SQL> DECLARE
2 ans NUMBER (4):
3 BEGIN
ans
 
5 FOR num IN 1..10 LOOP.
6 DBMS_OUTPUT.PUT_LINE('S x° || num {|'="11 9"
 
8 END Loop;
END;
10/de
rina,
stb
 
PLISQL procedure successfully completed
IFREVERSE option then, the FOR Statement is executed as
follows:
 
     
Outputs Reversed
a oo
5
a
z
PLISQL procedure successfully completed,
 
|. 4.26 Write a PL-SOL program to print numbers from:
1 to 18 using fo loop.
(Refer section 42.2)
 
 
EROS
 
BEGIN
Step: Counter is set to upper bound.
= ee FOR num IN 1..10
Siep2:  Ireounter ie greater than or equal to lower boend hen |
statements are executed otherwise loop is terminated.
DBMS_OUTPUT.PUT_LINE(aum);
Step3: Counter is decremented by one.
END LOOP;
Step4: Go to sep 2
END;
7 Example
Output
1SQL> DECLARE i
2num NUMBER = 10; 2
SBEGIN 3
"5 4
‘$DBMS_OUTPUT.PUT_LINE(Outpat is Reversed’;
5
SFOR n IN REVERSE 1..num LOOP F
© DBMS_OUTPUT.PUT_LINE(a): 7
TEND Loop; 8
BEND; é
10
9PL/SQL Prox
Bhoswersasey $a
DBMS (MSBTE-Sem. 3-Co FL CONTINUE Stateen
   
  
  
  
  
  
 
PLISQL procedure successfully completed.
(0) Continue Statement
Continue statement is used to exit the current iteration of a
oop. PLISQL provides following forms of Continue statement:
1. CONTINUE }
2. Continue-When(Condiion)
 
Fig. 4.23 : Forms of continue statement
tement is supported only i Onde 1,
ments canbe used anywher inside a fop, yp”
a is encountered in the PLSQL bie,
o execute immediately and theca
continve
CONTINUE state
‘a CONTINUE stateme!
current iteration ceases
passes othe next iteration
& example
‘To print od numbers from 1 t0 10
PLISQL procedure sucessfully completed.
F % Continue-Wnen(Condition)
ete the condition inthe When clause is evaluated ail?
‘ound tue, then the current iteration of the loop cease a!
SSeS tothe nex iterationDBMS (MSBTE-Sem. 3-Comy
     
 
Q. 4.3.2 Explain ‘exception handling’ in'PL-SQLs
  
  
 
 
| (Rote secton 4.3).
.44 Describe Exception handling. Explain with
example. (Refersoction 4s)
  
 
jon which may interrupt
Exception is a warning or error conditi
the program execution.
 Trean be defined as an error situation, arising during program
execution,
= An exception is raised when an error occurs, the normal
execution is stopped and control transfers to exception
handler code
= Exceptions are predefined or can be user defined.
B.g. ZERO_DIVIDE and STORAGE_ERROR are predefined
exceptions
User defined Exceptions can be written in the declare section
‘of any PLISQL block, subprogram, or package.
Exception Handlers isa block of code written to handle the
raised exception. After an exception handler is executed the
control passes back to the next statement after the statement
‘where exception was raised.
— Handling the exceptions ensures that PL/SQL blocks do not
exit unexpectedly
= Internal exceptions are raised automatically by the run-time
system.
= User defined exceptions must be raised explicitly using
RAISE statements
= Predefined exceptions may also be explicitly raised using
RAISE statements.
Exception’ improve readability and reliability of code as it
thas a separate Error Handling block.
 
PUSQL
 
gray
PLISQL Exception message consists of following thee pany
co Type of Exception
© An Error Code
co Amessage
& structure for Exception Handling
“The coding of Exception handling section in PLSQL is que
simple and easy. understand.
‘syntax
DECLARE :
Declaration section -.
BEGIN :
Begin section.
 
EXCEPTION
WHEN Exception_one THEN
‘Exception handler code to handle the errors
WHEN Exception_two THEN
Exception handler code to handle the errors
WHEN Others THEN
Exception handler code to handle the errors
END;
5
~ When an Exception is raised in a PL/SQL block, Onl
searches for an appropriate exception handler in the exceptt
section, E.g. in the above example, if the emor bed #
"Exception_one', then the error is handled according (0
satements under it, WHEN Others’ exception is use ©
‘manage the exceptions that are not explicitly handled.
~ When an exception is raised in inner PL/SQL block it sb!
bbe handled in the exception block of the inner PLISQL b“*
otherwise the control moves to the Exception block of
next upper PLISQL block. If none of the blocks handle
exception the program ends abruptly with an eroMS (MSBTE-Sem. 3-Comy
DBMS ( ) 4t7 PUSQL Programming
‘7 pLISQL Exception Handling block
= _ Following is a standard set of Oracle exception
> EXCEPTION =a
SQL: Oracle Exception Name Description
‘3 WHEN NO_DATA_FOUND THEN Error i
a: ORA-00001 | DUP_VAL_ON_IND | Duplicate value created
"error found EX in a field restricted by
SQLCODE; unique index
‘ ORA-00051 | TIMEOUT_ON_RES | Waiting for a resource
ixdebr's OURCE ‘which is timed out
INSERT INTO errlog VALUES (v_err, y_msg, v_prog ORA-00061 | TRANSACTION.BA | Portion of transaction
SYSDATE, USER); Ce pales te
ORA-o1001 | INVALID_CURSOR | Referencing cursor
‘7 WHEN OTHERS THEN which did not exist
By ex:= SQLCODE; ORA-01012 | NOT_LOGGED_ON | Executing calls to
Oracle before logging
‘9_msg = SQLERRM; in
eee naan, oRA.01017 | LOGINDENIED | Logging in with invalid
= - username or password
ILINSERT INTO erlog VALUES (v_err, v_meg, ¥_prog, ‘0RA.01403 | NO_DATA_FOUND | No rows returned as
result of query
SYSDATE, USER);
‘ORA.01422 | TOO_MANY_ROWS | More than one row
12 RAISE; retuned
|| ona -00476 | 220 DIVIDE Executing Divide by
Syllabus Topic : Predefined Exception zer0
(ORA.01722 | INVALID_NUMBER | Trying to convert
4.3.1 Predefined Exception string to number
> (msste-s-16) || ORA-06s00 | STORAGE ERROR | Memory insufficient or
comupted
: defined
9.4235 What are predefined exception and user ‘ORA-06501 | PROGRAM_ERROR | Internal program error
exceptions ?
ona.o6s02 | VALUELERROR — | Invalid character or
(Refer sections 4.3.1 and 4.3.2) numeric value
(1) Named system exception ‘oRA-06511 | CURSOR_ALREAD | Opening a cursor that
¥_OPEN is already open
~ The Named system exceptions are exceptions that have Been
already given names in the STANDARD package in PLISOL- carer
~ Named system exceptions need not be declared exis Catching Named System Exception called
error | DUP_VAL_ON_INDEX
they are raised implicily when a predefined Onecle eon J DUP
cccurs, also they are caught by referencing the standard namé | SQ].>CREATE OR REPLACE, PROCEDURE new dent
‘Within an exception handling routine. (dnolN
2. CHAR, d_name IN VARCHAR2) eslBloons (MSBTE-Sem. 3-Comp) —————— 23
e (2) Unnamed System Exceptions
3 i /
‘4 BEGIN
Bee
'S INSERT INTO department (dept_no, dept_name)
 
 
 
‘7 WHEN DUP_VAL_ON_INDEX THEN
'B rise_application_error (25001,Department No, alread
| existing);
‘9. WHEN OTHERS THEN
‘AO raice_applieation_error -25002,Eror
epartnent.); gees
Dividing by Zero Error
PLISQL procedure successfully competed
 
PUSOL Progen,
    
  
 
    
  
 
 
  
system exceptions for which oracle do not provide
known as unnamed system exception. These Exc
or
a code and an associated message,
8
“There are two ways to handle unnamed system exceptions
Using the WHEN OTHERS exception handler, o¢
Associating the exception code to a name and using
u
named exception.
= This possible to assign a name to unnamed system exons,
using a Pragma called EXCEPTION py
EXCEPTION_INIT will associate a predefined Orie,
number to a user_defined exception name.
& Example
 
Declaring an unnamed system exception using EXCEPTION {7
A
2
en
    
 
Here, ‘exception_name isthe name of &
xcepton and the number isa negative valve o7F
ORA- error number. The pragina must apes sm!
*xcepton declaration inthe same declarative set
the following example:yr
3MS (MSBTE-Sem. 3-Comy
Ghoovse 2 ae
 
 
 
 
   
+ found EXCEPTION;
 
}RAGMA EXCEPTION_INIT(error_found, -45);
nai
“cif cove hat causes an ORA00045 error
EXCEPTION
 
(WHEN error_found THEN
-exde to handle the error
END;
  
f
7 Example
‘When we try to delete a record from parent table while a
bid recond still exist, an exception will be thrown with oracle
cade number -1517. User can provide a name to this exception and
‘andl it in the exception as shown below:
 
SQL>DECLARE: pie
2 aa soud_ exception EXCEPIION:
3 PRAGMA
AEXCEPTION_INIT (Child_record_exception, -1517);
‘SBEGIN
‘Delete FROM department where deptne = "DOW'S |
TEXCEPTION
WHEN chitd_secord_exeeption
OTHEN dbms_output.put_ine(Child records for this
$epartnent exit in employee table"
Wee :
eae : ook
 
 
PUSQL Programming
Syllabus Topic : User defined Exception
4.3.2 User defined Exception
Due tothe complex structure of relational databases i is not
always possible to handle all the unwanted exceptions using
Named and Un-named exceptions. Therefore there is a need
to.name and catch exceptions that arent defined by PLISQL.
‘These are called Named Programmer defined exceptions or
user defined exception
~ Named Programmer-defined exceptions should be explicitly
declared in the declaration section.
= They should be explicitly raised in the execution section,
= They should be handled by referencing the user-defined
exception name in the exception section
© syntax
function
 
[Named programmer-dfined exception i
 
   
 
alse excep names
ExoET nN
   
 
temvents]
|END (funetion_oame]:Ee mp
‘Syllabus Tople : Cursor
4.4 Cursor
D> (MSBTE - W-13, S-15, W-15, S-16, W-16, S17, w-17)
  
   
  
 
 
  
   
‘@AlaA Define cursor ? List the twa types of cursor.
(Refer section 44) TEERTREATTS
(0.4.4.2 What is cursor? (Rater section 44)
. 4.43 Explain mle and expiict cursors. e
(Refer sections 4.4.1 10 4.4.2) :
Q.4.44 List types ‘of cursor and explain each with
‘example, (Feter sections 44 to 4.4.2)
pas
Cursor is @ pointer to the private area in SQL
 
 
 
 
 
that stores information about procesing. a]
specific DML statement. S
 
= The drawback with select statement is that it returns only one
row ata time in a PLISQL block.
‘Cursors are capable of holding more than one row. It sed for
‘grouping a set of rows and implementing a similar logic to all
the records ofthat group.
‘Sot of rows retrieved in such an area is called the active set
and its size depends on the number of rows retrieved by the
search condition ofthe query
Oracle reserves an area in memory called cursor, populates
this azea with appropriate data and frees the memory area
‘when the task is completed.
 
Cursors can be classified as
4 Implict Cursor
    
    
2. Explicit Cursor }
 
Fig. 44.1 : Cursor types
>
>
 
 
1. Implicit Cursor
called as internal COrOTS and ag,
-rese cursors ae 80
managed by Oracle itself
2, Explicit Cursor
_mhes are User-defined Cursor used for ‘external Processing
syl
"Tabus Topic : Implicit Cursor =
4 Implicit Cursor
 
Implicit cursor i a session cursor which is opened every
time you run « SELECT or DML statement in the PLISQL
block,
‘An implicit cursor closes after its associated statement ron bt
its attributes values remain available until another SELECT
or DML statement is executed.
Cursor attributes return information about the state of the
cursor.
‘The attribute
‘SQLattribure(e.g. SQL%EFOUND).
‘cursor is
syntax for an
implicit
SQLattribute will always refer to the recently run DML ot
SELECT INTO statement.
Implicit cursor attributes
Impllett cursor attributes
4. SOL%ISOPEN
   
  
  
 
 
 
 
2. SQL%FOUND
 
8. SQL%NOTFOUND
 
4, SQL%ROWCOUNT
Fig. 434.2 Impl
 
1. SQL%&ISOPEN
Oracle autor
matically opens and closes implicit exe
associated to ar
ed to any DML or Select statement, Therefore
Yale for this atribute is always false
es —pans (MSBTE-Sem.3-Comp)
% 2 SOLSFOUND
pany DML of Select into statement returned any row then
ihe value ofthis atibute iS tre, if no rows were returned
  
shen te value i flse otherwise when no recent statement i
executed then this valve is null
9 3. SQLSNOTFOUND
works like the SQL%FOUND but contrary results are
cbtained with SQL&%SNOTFOUND that is false if rows are
retumed, true if no rows are returned and null if no recent
statement is executed.
4 4. SQL%YROWCOUNT
It stores mull if no recent DML statements are executed and
stores the count ofthe rows affected by the DML statement of
Select into statement.
 
Sr.No. Carsor Attributes,
   
 
Retums true if the cursor is
open otherwise false
1. | SQL%ISOPEN
 
2. | SQL%FOUND If any row is retumed by
DML or select into then true
otherwise false
 
Returns true when no row is
returned by DML or select
Into statement
3. | SQL%NOTFOUND
 
Retums the number of rows
affected by DML statements
4. | SQLROWCOUNT
 
 
 
 
 
 
PUSQL Programming
SEND IF,
    
  
Hove ee uindata
12 END IF;
ASELSE
14 DBMS_OUTPUT.PUT_LINE (No records to be
updated’);
 
15 END IF;
16 ENI
  
lie
 
i
 
3 rows are updated
PLISQL procedure successfully completed
= Drawbacks of Implicit Cursors
‘The implicit cursor has the following drawbacks :
1, Implicit cursors are less efficient than an explicit cursor.
2. Implicit cursors are more vulnerable to data errors.
3, Implicit cursors provide less flexibility to implement
programming control.
 
 
 
 
 
L
© example Syllabus Topic : Explicit Cursor - Declaring,
Opening and closing a cursor, Fetching a Record
Using CURSOR attributes on cance
en!
Sassers SERVEROUTPUT ON
Peay 4.4.2 Explicit Cursor
  
po = 'D0OY';
AP SQuerounp THEN
ps S_OUTPUT.PUT_LINE (‘Salary Updated:
 
 
4s oreo PUT_LINE (Meson nt fon
 
 
 
> (usere-we14)
4.4.5 Wiite step by step syntax to create
close cursor in PLISOL block.
 
_ (Refer section 4.4.2)
‘The Cursor which is declared by user is called as Explicit
Cursor.
Following are the steps of using an explicit Cursor :
=‘Stepl : DECLARE Cursor in the declaration section
© Example
(CURSOR ¢_emp IS SELECT emp_no, emp_name,
femp_odde FROM emp; 5
 
 
aa
In above example we created a cursor with name ¢-2mP
‘which sasocated with mp table
Step 2: OPEN the cursor in he Execution Section
General Syntas to open a crsoris
(OPEN cursor names
‘Step 3: FETCH the data from cursor into PLISQL variables oF
records in the Execution Section
'% General Syntax to fetch records from a cursor is
 
FETCH cursor_name INTO record_nai
oR
  
FETCH cursor_name INTO vatiable list:
Step 4: CLOSE the cursor in the Execution Section before we
end the PL/SQL Block.
‘= General Syntax to close a cursor is
 
CLOSE cursor_name;
 
Following are the statements used and corresponding actions
performed:
 
Statements Action performed
 
OPEN c_emp: Opens the cursor
 
FETCH — cemp INTO | Rows fetched from table into
vvar_emo_no, var_emp_name, | variables
var_emp_sal,var_emp_addr,
 
CIOSEc_emp; Closes the eursor
 
 
‘© Explicit cursor variables
 
 
Cursor variable Description
 
c%ISOPEN Retwms tue if the cunor is open
otherwise false
 
 
 
L
 
a
 
 
if any row is returned by Dyyy
into then true otherwise fase "8
   
 
   
  
Returns true when 0 row a
DML orselect into statement 5)
Retums the number of ows
DML statements ‘tec
 
  
c%ROWCOUNT
 
= example
Using cursor variables
{SQL> Declare
2 var_emp_no char(4)s
4 var_emp_namevarchar(10);
4 var_emp_sal number(8.2);
5 var_emp_addrvarcher(10}:
6 cursor ¢_emp is
 
“Tselect emp_no, emp_name, emp_sal, emp_addr fom ea
Begin
‘open c_emp;
loop
11 fetch ¢_emp into
Aexit when e_empeénotfounds
33 var_new. sal
 
var_emp_sal +5000;
14 insert into emp
15.
ddr);
16 end loop;
A close ¢_emp;
Bend;
a9)
 
PUSQL procedure successfully completed.