0% found this document useful (0 votes)
32 views18 pages

Group-By, Join, Logical Oprations, View

The document discusses grouping and summarizing data from database tables in Oracle. It provides examples of using the GROUP BY clause to group data by a column and aggregate functions like SUM to calculate totals. It also discusses using the HAVING clause to filter groups. Additional examples demonstrate joining multiple tables to display related data and formatting output values.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views18 pages

Group-By, Join, Logical Oprations, View

The document discusses grouping and summarizing data from database tables in Oracle. It provides examples of using the GROUP BY clause to group data by a column and aggregate functions like SUM to calculate totals. It also discusses using the HAVING clause to filter groups. Additional examples demonstrate joining multiple tables to display related data and formatting output values.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

I I VI I Ol'~11·N I I JSIN< • <>RA<.' 1.

E 7, Dh Vl :LOPFI~ 20()(J
42 Ci >MM! RC( J\I \Pl'I ll't\ I II lN )
I 1 TAHI ES IN SQL
GROlJPIN(; DATA FltOI\ ; .
·n' .
The conrr11t of group• ~ · ·,II c·rcatc n set contammg several sets of
·1 1·1hlc we w ' · ro
From ,ab ordl'r dctnr ~ . ' · Ws &ro~
together h;P,cd on o co11d111011 Pc.j

Tab!<' name : ~airs_ order- details


Qty Ordered Qtv Disp
S Order No Product No
10 10
019001 P0000l 3
3
019001 P03453
3 3
019001 P06734
4 4
046865 P06734
10 10
046865 P03453
2 2
046865 P0000I
2 2
073965 P03453
1 1
073965 P0000l
1 1
073965 P06734

Example:
1. Select product_no, total qty_ordered for each Prod uct;

SELECT product_no, sum( qty_ordered) "Total Qty Ordered"


FROM sales_order_details
GROUP BY product_no;

The following is the output displayed :

Product No Total Qty Ordered

P0000l 13
P03453 15
P06734 8

A condition can be imposed on the group by clause, using the having clause as done in the
following example :

1. Select product_no, total qty_ordered for products 'POOOOl', 'P03453';

SELECT product_no, sum(qty_ordered) "Total Qty Ordered"


FROM sales_order_details
GROUP BY product no
HAVINGproduct_n~ = 'PO0OOl' OR 'P03453';
The following output displayed :

Product No
Total Qty Ordered
P00O0l -----------------------
P03453 13
15
~IA ~IPrL.\Tf\G I'\ n R. \l' I\ I '-(I 43
. · DATES l~ SQL
D1spla~
l the order .
m1om1:uion hle s- order _no, client .
client in the 3S" ct· no. s -order date tor all the orders plal'c..-d l)\
'DD"'-' ~1 'Y'\ fonnal .cen m~.. cirder of <lat e Th e S_order date should be displa~• ed in

Table name sales_orde-r


I
S Orde-r ~o Client No S Ordrr Date
0 lQO0l COOOOl l ~-oct-Q.5
O1000~ C'003-H 25-no, _q5
01 ()()OJ C'~300 l 03-jul-Qo
040805 C'0000l l S-feh-96
0-fo8oo COOS,l ~0-mar-06
I 04080- , (00001 : 12-ian-Q~

l\ote srsdate
• . ste·11 date or toda, ·s date
"'· •~ ""'e ~~
repres.:>nT._.

Example SELECT s- .._vder ,1· t


.. - no .1..ten_no.to_char(_s_order date.'DD'\0.LYY')
FR0\t s.i.es order -
ORDER BY-to_ch:ms_order_date. DD ~0.L'Y'C).

The output will be as ~spla) ed belov. .

S Order ~o Client No S Order Date

O..i68b; (00001 12 01 q5
019001 COOOOI 1~1()95
019002 (00341 '.:!5 11 95
COOOOl 18 02 Q6
046865
046866 (00871 ~o 03 Q6
C2300l 03/07, 96
019003

JO~S
Joining ~lultiple Tables (Equi Joins):
Sometimes ,i,.e require to treat more than one table as though it \1.ere a single entity Then a single
SQL sentence can manipulate data from all the tables as though the tables \,ere not separate
objects. but one single entit)
To achie, e this, we have to join tables Tables are joined on columns that have the same data type
and data ~idth in the tables
~xaf!ll)Je 1 Displa) order information like s_order_ no. client name. s_order_date for all the orde~
p aced lry the client in the ascending order of date The s_order_date shou Id be displa; ed in
001:'.i)t) Y' format'
I !Ill di 11 l•l\'tl(tl 'MINIII\IN<d>RACll•7 l>l v'lllll'IK2<Xfl

\ i\ ' \ \\I\\ \ I \ 111 l\\l• Ulhlu, ,11/n "rJe, and c;/lt'III mo ,ler r hcsc table,. hal(
lh ,111 ' Ht., lll·tl' l'llu c11111 v e lob.

•,, tt.,, No No S Order Date


~
.._Client
\ l \ l ll)l) I
- ('0000 I 12-oct-95
C0034 l 25-nov-95
(l I llOIP
C23001 03-juJ-96
O I 11001
J 8-feb-96
0 lu865 C00002
C00871 20-mar-96
046806
C00003 12-ian-95
046867

\ nhlr name client master

Client No Name
C0000l Ivan Bayross
C00341 Pradeep Mathew
C23001 Mili Parikh
C00002 Norma Fernandes
C0087I Rahul Desai
C00003 Arjun Shettv

l'lote : Data from relevant fields are displayed in the above tables.

Example SELECT s_order_no, name, to_char(s_order_date,'DD/MM/YY')


FROM sales order , client master
WHERE clie-;t_master.cli;t_no == sales_order.client_no
ORDER BY to_char(s_order_date, 'DD/MMIYY'),

Note : Here we use the technique of specifying the tablenarne prior the columnname. se-~~eri ~ .:.
period in the WHERE condition because the colurnnnarne in both tables are idenrie:.l.

The output will be as displayed below .

S Order No Name S Order Date-

046867 Arjun Shetty l~ 01 05


019001 Ivan Bayross t: lO Q5
019002 Pradcep Mathew 25 l l 05
046865 Nonna Fernandes l80~0o
046866 Rahul Desai 2003 0c
019003 Mili Parikh o., o"? 0o
INTERJ\C'I IVE S()I. 45
Example:! Select product_no , product_descript1on and total qty_ordered for each product,

Table name: sales_order_details

S Order No Product No Qty Ordered Qty Disp


019001 P0000I 10 10
019001 P03453
019001 3 3
P06734 3 3
046865 P06734
046865 4 4
P03453 10 10
046865 P00001 2 2
073965 P03453 2 2
073965 P0000l 1 1
073965 P06734 1 1

Table name: product_master

Product No Description
P0000l 1.44 Floppies
P03453 Monitors
P06734 Mouse
P07865 1.22 Floppies
P07868 Keyboards
P07885 CD Drive
P07965 HDD
P07975 1.44 Drive
P08865 1.22 Drive

SELECT sales_order_details .product_no, description.,


sum(qty_ordered) "Total Qty Ordered"
FROM sales_order_details , product_master
WHERE product_master.product_no = sales_order_details .product_no
GROUP BY sales- order- details .product no, description ;
-

The output will be as displayed below :

Product No Description Total Qty Ordered


-------------- ---------
P0000l 1.44 Floppies 13
P03453 Monitors 15
P06734 Mouse 8
\\ \ ' ' '
ru ~ t Jo m, }:
.. n a tuh!l ' Ill ns.d f as thousft ,ou ~-ere
JO::
t l~~'- .:_I" \
In the self- n.. ,he oom ncd r~: s ~
lO , a , cl

clau se To d i s t ~
t••c nJ.mc appe.-trs tw1<1t.· m ,he FRO M
ft ll"fll porll 0 n.une, c:all ~ an ~
or a c o r r ~
i-.~ {'.'.f th<- ~me tn..., cnam e.
the FRO :\i ~
unc m the FRO \ I_ cl~u__-.c The torm of
' a~- nN t~~ ~t,~~ . lt v" uf the r h'en:
''-'' ' tab!, l-W ' t' [nlu1~lj. tah aum e [nltas.:]
1

es !:llon g wirh their man ag~ frorr.


~
l.'- to (''\ tnt-:-.t the rl3.J"..,.""' ,... f tht- emp,!oy-c

Tnh .... name t'mph.1) ~

,,., i:\l2112~e--r ~o
E.mu l o n•-t I "" :nul'
&L--u ',3.y: •i.,j~ E 00..""..:'2
EOOOOI EOO X5
EOOOO.: R1...,.-:~!
o ·s . . . ~ Eot.XX\.!
, Eoooo ; C.1"\. \'
-
I EOOC""~ ..! CY''.l th1J 83.Y"-'S.S
h.1."1 Ba~T OS.S
-
EOCll..' . .1 :-
t
SEL ECT er::p rt.lmc. Clllg T na.-::e ~~g er
The Que1y
FRO ~ 1 emp ~'-1~ ee em?. en1plo~ ~ mng
r
io~ ee_n o.
\\l-IE RE emp .e1.:.r.;1ge.:-_no = !!'_~gr emp

B.isu "\3y mdg i


RtL,:mini
Rt;.k:m.:n.; h-ar. Bay:-os.s
C.lr'-"'~ o·sou.zn Cym hi2 B;~~T Css
~ e .ab..o
g the a.!iJ.S tearu...'"C o:· SQL. :s rr-eareci as
:-'-\'C
In trus quef ). the emp lo: ee rabk usm
nam ed ernp J.nd mng r. as si:ow n he:-e
Tab~e :13.Il le mng r
Tabi e nam e ~mp
~am e ~1.alager
Xam l' M..a.112ger £.m ploy tt
E..m plo~ tt ~o
~o ~o
~o
~ 2.vin.c.gi
E OO::~ :
EOOOC: E OOOOI Bast.:
£000 0 1 Basu "\'"anndgi Eoo.::,::-,5
EOOC05 EOOOO: ~7. in:
EOOOO: Rukr mm E n.">" "- .

j
J_,.._,,..1
£00G()...; E 0000.3 Carol D" S~
£000 03 Caro l ffSou .z.a
C~mhia Ba)T oss E OOCO--! Cy.:rJ-.ia B-2.:-,oss
£000 04
£000 05 Ivan Ba)T oss Eooc :;5 ha.. Bay:--oss
IN I EfV\( IIVE \C.)1 47
The join operation is evaluated as follows .

1. Using the compound condition : emp.managcr no mngr.employec_no

where, each managcr_no record (E00002 E0000S, E00004) from the emp table is joined wi th the
employee_no record (E0000I, E00002, E00003, E00004, E0000S) from the mngr table to form
the followmg intermediate result :

Table name emp Table name : mngr

Employee Name Manager Employee Name Manager


No No No No

E0000I Basu Navindgi E00002 E00001 Rukmini £00002


E00002 Rukmini E0000S £00002 Ivan Bayross £00005
£00003 Carol D ' Souza £00004 E00003 Cynthia Bayross E00004

Example 2 : Find the Order No, Client No and Salesman No where a client has been serviced by
more than one salesman.

Our task here is to extract the Order No, Client No and Salesman No from the Sales_order table.

Table name : sales_order

S O;d~r N~· - -Cli~;nt -N~ ~~-s;i~sm_?!_!_~o


O 1900 I- - C0000 I - S00002
046865 C0000I S00001
073965 C00003 S00004
046865 C00002 S00003
057575 C0000I S00003
046462 C0000 1 S00002
086723 C00002 _ _ S00003
---- _............--- -
The Query : SELECT DISTINCT c_order.order_no, c_order.client_no,
c order.salesman_no
FROM sales order c_order, sales_order s_order
WHERE c ~~der.client_no = s_order.client_no AND
~-order.salesman_no <> s_order.salesman _no

Results In :
Order No Client No Salesman No

046865 CO0O0l S00O0J


019001 C00OOl S00002
046462 C0O0Ol S00002
OC:7C:'7';;; S00003
48 ~t )MMI IH ' l1\1 t\Pl'I I( '/\ I 1r >N I )I Vl•,I cH'MENJ' I JS INO c>l{ACI I 7 I )h VEJ ,( >l 'hR 2000

CONSTRUCTING AN ENGLISH SENTENCE WIT H DATA FROM TA 8tf:


COl..l lMNS

Example SELECT INITCAP(name) II ' has placed o_rders worth Rs. ' I!
sum(qty ordered * sellynce) .
FROM sales order_details , product master, client _mast~r. sales_order
WHERE product_master,product_no - sales order d~tails product_no
and client master.client_no = sales order client no
and sales: order_details .s_order_no = sales _order order_no
GROUP BY name;

Since the above SELECT column is taken as a single string, the column title of the above resuh will
appear as follows :

INITCAP(NAME)ll'HASPLACEDORDERSWORTHRS .'IISUM{QTY ORDERED*SELL_PRICE)

Mili Parikh has placed orders worth Rs. 1600


----------------
Pradeep Mathew has placed orders worth Rs. 1600
Rahul Desai has placed orders worth Rs. 400

Whereas, if you can rename the whole string as, something like say, :

SELECT INITCAP(name) II' has placed orders worth Rs. ' II


sum(qty_ordered * sell_price) "Orders Placed"
FROM sales_order details, product master client master
WHERE d - - , _ , sa1es order
pro u~t_master.pro~uct_no = sales_order_details prod~ct no
and chent_master.chent_no = sales order client d -
sales- order -details .s order no =~les d _dno an.
GROUP BY name· - - _or er .or er_no
'
The output will appear as follows :

Orders Placed

Mili Parikh has l-- d --------------------------------------


Pradeep Mathe! ~ce orders worth Rs. 1600 ----------------------------------
Rahul Desai h as placed orders worth Rs. 1600
as placed orders worth Rs 400
IN n RAC flYI S<JL 4?
Sl BQl 1ERIES
te a fonn o r an .SQL
. e<l . " . is· •d
.\ subquerv . statement that appears inside another SQL statement It is also
ml as k,\tt: qut.?~V. The statement containinll. a subquef)' 1·s called
ro,\ · r t db h .. a parem statement ·1 he
s e umc ) t e subquery are used by the parem statement.

It can be us~ b~ the follov.ing commands


• To msen records in the target table.
• To create tables and insert records in this table.
• To update records in the target table.
• To create ,iews
• To provide values for the conditions in the WHERE, HAVD:G IN SELECT LPDATE d
DELETE statements. · ' an

Examples :
l . Creating client_master table from the oldc/ient_master table :

CREATE TABLE client master


AS SELECT * FROM oldclientmaster,

2. select orders placed by ·RahuJ Desai'.

SELECT * from sales order


where client no=
(SELECT client_no FROM client_master
WHERE name= 'Rahul Desai')

3. Io determine the non IDO\•ing products in the product_master table :

SELECT product_po. description


FROi\ 1 product_master
WHERE product__no :\"OT 1:\
( SELECT product_no FRO:M sales_order_details ):

The aboYe examples show two le\·els of nesting. If the user wants the infonnation from a table
depending upon the information from another table, which in turn is also dependent. then the user
\\ill have to go in for the next level of query.

Example · To select the names of persons who are in Mr Pra.deep's department and who have also
worked on an in,·emory control system.

SELECT ename, depmo


FR0~1 emp
\\1fERE deptno ~ (SELECT dept.rm FROYI emp
~'HERE ename = 'Pradeep' )
,...\.'.TI ename IX (SELECT ename
FR0\1 im_sysf
50 COMMER CIAL APPUCAT lON Dl·'VELOPMI"Nf USING ORACLE 7, DEVFLO PFR 200()
USI NG THE UNION , INTER SECT AND MINUS CLAU SE
U oion Clause : . .
The user can put together multiple queries and co~b•~e thetr .output using the union cl
ause l'l
Union clause merges the output of two or more quenes mto a single set of rows and columns •ne

Records records
Only i only in
I

Query query
One Two

Diagram 2.5 : Output of the Union Clause

The output of both the queries will be as displaye d above. The final output of th .
· e union
clause will be:

Output = Records only in query one + records only in query one +


A single set of records which is common in both queries .

Example : select all the clients and the salesman in the city of ' Bombay ';

SELECT salesman- no "ID" ' name


FROM salesman_master
WHERE city = 'Bombay '
UNION
SELECT client_no "ID", name
FROM client_master
WHERE city = 'Bombay' ;

The output of the query will be as follows :

ID Name
--------------------
SOOOOl Arjun Shetty
s00002 Rahul Desai
S00003 Rahul Rao
COOOOl I van Bayross
coooo2 Pradeep Mathew
The Rest· · on using
nct1ons .
• No. of column . J a uruon are as follows :
s ma I the q · h
• The datatype of th I ue~es s ould be the same.
U . e co umns tn each
• ruons cannot be used . . query must be same.
• You cannot use a m subquen es.
fNTf~l{AC. TIVE ~QL 51

Intersect Clause:
The user can put together multiple queries and combine their output using the intersect clause The
Intersect clause outputs only rows produced by both the queries intersected i.e. the output in an
Intersect clause will include only those rows that are retrieved by both the queries.

Diagram 2.6 : Output of the Intersect Clause

The output of both the queries will be as displayed above. The final output of the Intersect
clause will be:

Output = A single set of records which are common in both queries.

Example : select salesman name in 'Bombay' who has atleast one client located at 'Bombay' .

SELECT name FROM salesman master


WHERE city = 'Bombay'
INTERSECT
SELECT name FROM salesman master
WHERE 'Bombay' IN
(SELECT city FROM client_master
· WHERE client- master.client- no IN
(SELECT client_no FROM sal~s_ order
WHERE salesman_no = salesman_master.salesman_no)) ;

The diagram shown below shows the columns from different tables required in the intersect
example. It shows all the tables and the relation between each of these tables.
~l I I It·~ II I I I I i\ I 11 ,. " I Ii ,r, I 11 VI I I II , if I JI 11 lfll l 1 A • I I
ll ln ' I ,, VI I I II I II IN h I

I Ii, I} II' Ill r u Ii ill tli1 !It 1nl1l1 I t 111ll,H\t •

I ,1 ,1

• c II,
C 1)1111qf l \hll 1111\111 Iii I , 11111 11,1

C !lllllll 1 \ 111 ,.iri,111 1rn11 wn l I\ 111, I, 11.t


C I ti )!It l 1 1'111111 11,111 I 1JOtt1lt 1111111111,;
C (JI II HJ 1 1111 1i11 Nn, 111d.,1 111 11111,w
f Ill I( It I tj lt11, I ', 11I,111111 1111 I 1, 1111
( 1)111111(, ll11 I I I Ill II 11111 111 ,nj'.

t uhln '-111 1, 11111t111_1\·f1•~f• 1


t~. 1111,

S11lr, muu No N111u, ( 'lly


<111111111 I I- 11 1111 ll,11,tl111 y
\()(1()1) I

'-;11111111 I
\11111111 I ___ ,
~ l1111 iw l1
1t11 v1
/\11111~
I 111111l111 y
I J,11111

----
M111 Ii 1111

I 11hk N11 1110 Siilnt 01cli·1


S Oacl,~1 No s o ....... u.. ,,. ( 'llc•u• No Sn lc•1011nu No
01')()()1 l:lj11114'<, ( '0000 I SOO<Hl I
() 1'100.' i ·,-1111 I I)<, ( '()()()() /4 soooo~
(),l<,H<,'i I H foh '><, < '0000 I SOOOO I
0 I 'JOO I () I llfll .,, , < '()0()0 I SOOOOI
Od<,H<1<1 ?() 11111 y ,,,, ( '()()()()ti SOOOO l
<) I CJOOH J1 I 11111 ')<, ( '()()()()~ S0000'1

'Jfo: Nd<:cl :-1l11lc111011I 11,

snu~c..,. 1111111 (. FIH>M ~111c1-1111a11 111ns1l~,


WI 11-'.l(E 'Bomhuy' IN
(SULhC'T ciry r•ROM dicnl inns1cr
WI IERE clion1 muster clicn1 no IN
(SEU ~<'T clicnl no flH)M sulcs 01 dl'r

WIJERE salc:mrnn no salesman master salesman no)) ;


Note:

·1he 11bovc !l<:foc1 olalemcnt is u subqucry of the select statement that references e
th
•11lc.
,m1111 masic, lnhlc lhc
where clause is as follows; select statement thu1 rclhcnces the salesman master table without '15

SELJ.:,C'T name FROM sulcsrnan_mastcr

If aoy table is included in lhe from clause of a sck-ct statement at a level above the ctlrrent select
nd
stalcmcnl
al lhcn lhal lahle •
lower levels. the columns Ii-om tha1 table can be referenced in the select statemenl
INTI· RJ\cTI VT SQI 5J

Thus,'\ rdonot ncedto


'f h , •~t ti 1c sn 1c~"'"" 1n,,~tc1 lnble m the I•rom clnusc of the subque,1
'in Id
c" en 1 1 (' columns 1s referenced m the \\ here clnusc ar. shown 111 the query below

SEl ECT cltcnt no l·RO~l snlcs order


\\ In~Rr:. snlc.sman no salesman
-=--- salesman
master---=- no ___ ___ __ _j
..::,_

How dot..11 a subquc ry work?


The- tOp•lt•vc ·
l select .!)(atcmem re t neves Names from the salesman master table as seen m part of
, ~.
t hc :-c 1\.:d statement 1 c. SELECT name FROM sa1esman_master-

b salesma
The no fromE the salesman_ma st er tabl e .1s used .m the where clause for the lo\\est le~el of
• nWHER
,u quef) i.e. salesman_no = salesman_master.salesman_no

required
Oraclewill
table be as follows:
s
two fields j .e. aIesman_Nio and Name from the salesman_master table This target

Salesman No Name
SOOOOl Kiran
S00002 Manish
S00003 Ravi
S00004 Ashish

The seco~d level query retrieves city from the client_master table as seen m part of the select
statement 1.e. SELECT city FROM client_master.

The client_ no from the client_master table is used in the where clause for the same query
ie
WHERE client_master.client_no in.

Thus Oracle requires two fields i.e. client_No and City from the Client_Master table. This target
table will be as follows :

Client No Citv
COOOOI Bombay
C00002 Madras
C00003 Bombay
C00004 Bombay
coooos Delhi
C00006 Bombay

select
The lowest level subquery retrieves client_no from the sales_order table as seen in part of the
statemeht i.e. SELECT client_no FROM sales_order.
i.e. the
The salesman no from the Sales Order table is used in the where clause for the same query
salesman_no Gcompared with the salesman_no in the Salesman_Master table as in WHER
E
salesman_no = salesman_master.salesman_no.
Note
Thus Oracle requires two fields i.e. client_No and salesman_no from the Sales_Order table.
that both these fields form a part of the where clause for the higher level queries. These values
will
only be used to supply values for the WHERE clause. This target table will be as follows ·
54 COM MIRC l/\1. /\PPL IC/\ll <>Nl >l·Vl ·I.OPMl ,N I · · I /\( 11 7 fJFVl·I <>f'l•,I< 2f)(){J
IJSIN<,<>< •· · "

Client No Salesman No
C0000I S0000I
(000 02 S00003
(000 03 S00003
(00001 S00001
C00004 S00003
coooos S00004

Once the tables and the required columns fonn


the target table, Orac le elirrunates records, not
required after the application of the where clause.

Oracle applies the where clause in reve


rse orde r i.e. WH ERE salesman_no
salesman_m:ister.salesman_ no will be first applied ==
to the data set to eliminate reco rds. As per thls
clause, Since all the salesman_no are present in
the salesman_ master tabl e the targ et sales_orde
table remains the same when the where clause is r
applied to the last subquery segm ent i.e.

SELECT client no FROM sales order


- -
WHERE salesman no= salesman master.salesman
- - - no
The query must pick up client's from the client_ma
ster who have placed an order. The client no for
each cliept who has placed an order is recorded in
the sales_orde r table. Thu s the client no ~ust
present in both the client_master and the sales_ord be
er tables. -
Record with client_no 'C00 006' will be eliminate
d from the targ et table of client mas ter because
client 'C00006' has not placed any orders.
-
Thus the result will be:

Client No City
C0000I Bombay
C00002 Madras
C00003 Bombay
C00004 Bombay
C00005 Delhi

The client numbers from the resulting data set will


only those records where city = 'Bom bay' _1 b . .
e applied to the chen t_m aste r tabl e to pickup

Thus the target client_master table will be

Client No City
C0000I
Bombay
C00003
Bombay
C00004
Bombay
IN IJ 11 1 1 II /l 'IJt ~

Finally we need the names of salesman who h:i vr ,;1•rv 1t:.c <I < lw t,t iri Bt,rnbay I c ( J)(J()01
' C00003 ', 'C0000 4' Salesma n No 'SOOOUl' (trul •sor,0,1'1 ' huvt •.ctvicxd th1..".C 1_.. hc-ntr;
'fhus the
final output for the salesman master table will be

Salesman No Name
S00001 Kiran
S00003 Ravi

The first query in the intersect example is as follows.


SELECT name FROM salesman master
WHERE city = 'Bombay'

The T arget Tablewill be as follows:


Salesman No Name City
S00001 Kiran Bombay
S00002 Manish Bombay

the
We need all the salesman who are in 'Bombay' i.e. the target table of the first query and
serviced client's must be in 'Bombay' i.e. the output of the second query.

Intersect clause picks up records that are common in both the queries. Thus the output after
applying the intersect clause will be

Salesman No Name City


S00001 Kiran Bombay

the
Salesman no and city were used in the where clause for comparison with data from
client_m~ter and the sales_order table. Thus the final output will be
\
Name

Kiran ·
56 COM MFRC lAL /\PPU C ATI< )N DEVELOPMENT USING
ORAC LE 7, DEVE LOPE R 2000
l\lin us C lause :
The user can put toget her multiple queries and comb ine their
outp ut using the rninu
t e quen es mter secte d i.e. the s clause. the
/nt<?rsecl claus e outpu ts only rows prod uced by both h . .
·
intersect clause will include only those rows that are retne ve d b Y b oth t h e quen·es. output .1
nan

Reco rds
Only in
Quer y
One

Diagram 2.7: Outp ut of the Minu s Clau se

The outp ut of both the queries will be as displ ayed abov


e. The final outp ut of the minus
claus e will be:

Outp ut = Reco rds only in quer y one

Exam ple l : select a11 the produ ct_no of non-moving items in


the prod uct_m aster table .

SELE CT prod uct_no FRO M prod uct mast er


MIN US -
SELECT prod uct_no FRO M orde r_details~

Example 2 : select the product_no, description., qty on hand


the product_master table . cost_ price of non-moving items in
- - '

SELECT prod uct_no, description FRO M prod uct mast er


MlNUS -
SELECT order _details.prod uct- no, descr iptio n
FRO M order- details, prod uct mast er
WHE RE produ ct_m aster .prod uct_n o = orae r_details.produc
t_no;
INll•Ri\ l''l l\' I· S(..)I 57

INDEX ES
An Index is an ordered list of contents of a column or group of columns in n tnblc An
index- ere.lied
on the single column of the table 1s called S11111ile /11dn. . When mult1plc table colu rnns nrc incllHkd
in the index it is called compO\ llt! Indf!x

Creati ng nn Index for a table:


S1mnlc lndrx · CREAT E INDEX indcxtilcnamc
ON tablcname (columnname),

~ Create an index on the table client - master, field client - no

CREA TE INDEX client ndx


ON client_mast~r(client_no)

Composite Index : CREATE INDEX indexfilename


ON tablename (columnname, column name);
_no
Example : Create a composite index on the sales order details table for the column s s_ordcr
and product_no. - -

CREATE INDEX sales_order_details _ntx


ON sales_order_details (s_order_no, product _no):

index
The indexes in the above examples do not enforce uniqueness i.e. the column included in the
in
can have duplicate values. To create a unique index, the keyword UNlQUE should be included
the Create Index command.

Syntax : CREATE UNIQUE INDEX indexfilename


. ON tablename( columnname);

Example : Create a unique index on the table client_master, field client_no

CREATE UNIQUE INDEX client_ndx


ON client_master(client_no);

' When the user defines a primary key or a unique key contraint, Oracle automatically creates unique
indexes on the primary key column or unique key.

Dropping Indexes :
An index can be dropped by using the DROP INDEX command.

Syntax : DROP INDEX index:filename ;

Example : Drop index client_ndx on table client_master~

DROP INDEX client_ndx;


. • h bl oracle automatically
Wbeo the •is:er: .
drans the primary key, uruque key constraint or t .e ta e,
)MFN r osrN(1 ( Jl\f-YC'-U,Jo- - , , - - . , - - - - - - - - - --
. 110N Dl VI I 01 •
58 coMMl RCl \L ,\PPI ll A
VIE\\ s h rrcnl data in our database Physical data is ho .
l to sec l c cu wthis n..
I g,cal data 1, how we wan ""l
0
,s actual\\ placed tn our database. . !lows the programmer to develop a method .
\ icws are mas~s Pace
l ~
d pon tables. Th1s a
rs according to our
.
desire.
vta W'·
•!It!
"c can display predetermined data to use
where several people are querying a database different peo 1
~
.
In a concurrent enviro~ent, . ch group of people will want to see different fiel/ e
"ant 10 look at data dtuerent1Y, 1.e. ea s of I:;
same table
· f the table easier Oracle provides for the generation of views A VJ.
o ma e the querymg o , · ew i
createdk unique,
T according to the needs of each user, where the us~r can t~en, only access t~
fields of the database allowed by the view. This goes a long way m proVJdtng security for data

within a table.
The OBA treats a view just as it would treat a base table. Hence you can query a view exactly~
though 11 were a base table. The query fired on a view would naturally run faster than if it "ere
fired on the base table, as the view will be a subset of the total number of columns in the table

It is a programming convention that a view name begins with vw_ to allow one to distinguish
view from a table when the name is used in the FROM clause of the SQL sentence. '

Views may be created for the following reasons:


• The OBA stor~s the view as a definition only. Hence, there is no duplication of data.
• Simplifies quenes.
• Can be queried as a base table itself.
• Provides data security.
• Avoids data redundancy.

Creation of views :
Syntax·. .
CREATE VIEW vtewname AS
SELECT columnname, columname
FROM tablename
WHERE columnname = expression list .
faamnle .· Crea1e VIew mm epartment. .
· on client_master for the ad . d

.
CREATE VIEW vw_chentadmin AS
SELECT name, address 1 addre . .
FROM client master . , ss2, city, pmcode, state

This creates a view b h - '


Yt e name of',w c1·,entadmin based
Renaming the column on the table client master.
Example : CREA~of a view :
VTEW vw r
SELECT - c ientadmin AS
FROM _name, addrl, addr2 ci .
chent_master . , ty, pmcode, state

Here the columns of the tab! ,


0
the view can take on differen: n:e related to the view on a one-t
mes from th e table colum .
·r o-o_ne relationship. The coturnns f
ns, 1 reauirerl
fNll ·IV\CI IVh S<)L 59
Using Views: (visual concept)
Table name : Client_Master(This is the base table from which the view is created)

client no name address 1 address2 city pi ncode state

Example : CREATE VIEW vw_clientadmin AS


SELECT name, address 1, address2, city, pincode, state
FROM client- master ,·

vw_ clientadmin, the view created from client master will look as follows :

name address I address2 city pincod state

Selecting a data set from a view :


Example : SELECT name, address I, address2, city, pincode, state
FROM vw clientadmin
WHERE city IN ('BOMBAY', 'DELlll');

Updateable Views:
Views can also be used for data manipulation i.e. the user can perform the Insert, Update and the
Delete operations on the view. The views on which data manipualtion can be done are called
Updateable Views. Views that donot allow data manipuation are called Reasonly views. When you
give a view name in the Update, Insert or Delete statement, the modifications to the data will be
passed to the underlying table.

For the view to be updateable, it should meet the following criteria :


• The view must be created on a single table.
• The Primary key column of the table should be included in the view.
• Aggregate functions cannot be used in the select statement.
• The select statement used for creating a View should not include DISTINCT , GROUP BY or
HAVING clause.
• The select statement used for creating a View should not include use subqueries for the
creation of views.
• if a view is defined from another view, the second view should be updateable .
• It must not use constants, strings or value expressions like sell_price * 1.05.
• For insert , it should include all the NOT NULL fields .

Destroying a view :
A view can be dropped by using the DROP VIEW command.

Syntax : DROP VIEW viewname;

Example: DROP VIEW vw_ clientadmin;

You might also like