Group-By, Join, Logical Oprations, View
Group-By, Join, Logical Oprations, View
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
Example:
1. Select product_no, total qty_ordered for each Prod uct;
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 :
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
l\ote srsdate
• . ste·11 date or toda, ·s date
"'· •~ ""'e ~~
repres.:>nT._.
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.
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.
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.
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
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
,,., 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
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 .
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 :
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.
Results In :
Order No Client No Salesman No
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 :
Whereas, if you can rename the whole string as, something like say, :
Orders Placed
Examples :
l . Creating client_master table from the oldc/ient_master table :
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.
Records records
Only i only in
I
Query query
One Two
The output of both the queries will be as displaye d above. The final output of th .
· e union
clause will be:
Example : select all the clients and the salesman in the city of ' Bombay ';
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.
The output of both the queries will be as displayed above. The final output of the Intersect
clause will be:
Example : select salesman name in 'Bombay' who has atleast one client located at 'Bombay' .
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 ,1 ,1
• c II,
C 1)1111qf l \hll 1111\111 Iii I , 11111 11,1
'-;11111111 I
\11111111 I ___ ,
~ l1111 iw l1
1t11 v1
/\11111~
I 111111l111 y
I J,11111
----
M111 Ii 1111
·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
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
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
Client No City
C0000I Bombay
C00002 Madras
C00003 Bombay
C00004 Bombay
C00005 Delhi
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
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
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
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
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.
' 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.
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. '
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
vw_ clientadmin, the view created from client master will look as follows :
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.
Destroying a view :
A view can be dropped by using the DROP VIEW command.