21.1 lntroduction
Visual Basic provides you a set of standard controls. Previously,
we used number of controls like TextBox,
Label' Command button, PictureBox, Frame, CheckBox, option button
ListBox, ComboBox, Timer, DrivelistBox,
DirlistBox, FilelistBox, Line, Shape control, etc. Other than these controls,
in the professional and in the
Enterprise edition, you will find Custom controls, Custom controls
are interactive object mainly added in the
form to increase the user interaction with the application. These controls
area added to get extra functionality,
which is not pcssible from the standard controti.
Some controls are useful for working with la
Other
controls can be used to access the Windows file s
caled
custom or OLE controls,.in a Visual Basic application ir
s. The
Professional and Enterprise editions of visual Basic include
several ActiveX controls as well as the capability
to build your own controls. Additionar ActiveX contrors
for just about any purpose imaginable are availabre for
purchase from numerous vendors.
In this chapter, we will discuss some of advanced controls as
:
(4341
Common Dialog Box Controls 435
.i
; 11{
;:.. I
:..):,;. -
f'e 't G
En-
l=H l=rjl
rl
lllj ;
B,
F.ull EqE
IKdI E
'......\i:r'--
. i.
Cmtroh lnre,rabte 0bieits I
I Designas I
j Kodak Image Scan control
'Kodek Ima6e Thumbnar Control
:LayoutDTc L0 Type Library
14iEroeolt ActivEF4ovie (Entrol
l,licrosof I Ar:tiYeX Plugin
ll l,licrosoft A0O Oata Contrsl 6,0 (OLEDB)
hlicrosoft Agent Csntrol 2,0
i
E':
Ebl'
J..:
From the above Fig. 21.3, select the Controls tab and click the vertical scroll bar. Then,
O Select N,licrosoft Rich Textbox Controls 6.0.
O ClickonApplyorOK.
You will notice that the Rich rextBox control ( j,Hi ) will be appear in theToolBox.
The Showopen method displays the open dialog box and the syntax is as :
object.ShowOpen
The obiect placeholder represents an object expression that evaluates to an object
in the Applies To list.
Before writing the code lets add some controls on the form :
l. Click on the CommonDialog control.
2. Add the CommonDialog control on the form as shown in Fig.2l.5. You can also the set filters for the
Commonl)ialog f,rles to view the specific types of file. For eaxmple. *.txt will open only rext fiies" If you
want to set multiple filters you have to separate them wifh semicolon (;).
(onrmonDialngl
False
! moooooocoe*
I
+,trl
n
I
Fal<e
fextBort RichText&t:
,ebr,*u*t'1 ,':;,.
dbirdex 0
nbrtoF Trae
RiehTExtRoxl
oelTipTExt
B
F,ire
FichTeatBor',
Looklt .l
gp wins8 tOl :J
Hptonto :-J FEat
"IJ Detlos
Hpsetup.t iJ SrhoolHaure li]] rnrnins
(pcms fJ script*
flr*,lle Jwhdorr* "Il GH
Los
I Proqram Filas * hli' lar:unenls i] ri*ilrq
:::1 Eootlog :1 SEtuploq
You will notice that the selected file is opened in the RichTextBox as shown in Fig. 21 . 10.
440 Saraswati lnformatics Practices (Xl)
was e Eeat plaaslre to welcome our tiny tots in the se$$sn 2002-2ffi3. Now &ley ere
adiutted to ttrefu class loutire urd enioyiryg thei learning through a variety ol
,itia* in *reh clascroom snd oqtside,
we sll know patefits fley a key mle in the process o[ teaching and haning. so tinre.
iiteraclion and communieation with lhe teachets is r,ery essentid tor the overafi
object ShowSave
T\e obiect placeholder represents an object expression that evaluates to an object in the Applies To list.
When you have finished designing for Save command button. Open the code window or double click the
Save button for writing the code. Here code is added for cmdSave command control in the Click( ) events as :
' Steps to olien a .txt file
Private Sub cmdSave_Click0
ftffextBox.Visible : True
' Set fi lters.
CommonDialog I .Fi lter : "Text Files (*.txt)l*.txt"
CommonDialog LShowSave
rtfTextBox.SaveFi le (CommonDialog I . FileNarne)
End Sub
After writing codes for Save command button, press F5 or click start button to run the CommonDialog
controlapplication.BeforeclickontheSavebutton,openthepreviousLetter.Txtfileandaddaline,
(ABC Public School)
after last line as shown inFig.2l.l2.
was n gred{ pleasure to oelcome our ling lots in lhe session efil2-200? Noo,r they ere
adiusted to their rless tqttrine and enioying their learninq thraugh a variety al
,tities in their classroum and ortside.
Aa we all know parents play a key role in lhe proce*s of taoching and leaminq. so lin-re.
todinre interaction ard connnwrication with the ieachers is very essenlid for the overell
object,Flags [= valuef
The Flags property syntax has these parts : object and value. The object is an object cxpression that
evaluates to an object in the Applies To list. Whereas the vlaue specify the options for a font dialog box, as
listed in listing2l.3.
CcmrrnonDialogl.Flags : cdlCFBoth ' Flags properly nrust be set before using ShowFont method.
Or
Comrnon Dialogl. Flags : &l-13&
You can also define selected flags. Use the Const keyword in the Declarations section of the staftup form
to define the flags you want to use. F-or example,
Const ReadOnly - &H00000001&
Const Eflecrs : &H00000100&
You can set more than one f'lag for a dialog box using the or operator. Iror exarnplc.
CornmonDialog LFlags: &ll I0& Or &H200&
Adding the desired constant values produces the same resu lts. The following is equivalent to the preceding
example,
2t.t4.
End Sub
After writing codes for print
comrnand button, press F5 or click start
button to run the CommonDialog
control application. Before click on the
Print button, open the previous
Letter.Txt file and click the Print button.
Like other application, a Print dialog box
will appear as shown in Fig. 21.18.
Similarly the ShowLlelp rnethod is used to display help file. The syntax of ShowFont method is as :
object.ShowHelp
Before you Llse the ShowHclp rrrethod. you nlust set the HelpFile and HelpCommand properties of the
CommonDialog control to one of their appropriate constants or values. Otherwise, Winhlp32.exe doesn't
display the Help file.
The HelpCommand property of ShowHelp method returns or sets the type of online Help requested. The
syntax is as :
o bj e c t.l1 elpCom ma n d l: v a I u e]
Thq HelpCommand property syntax has these parts.,: object and value. The object is an object expression
that evaluates to an object in the Applies To list. Whereas the vlaue specifo the options for a font dialog box,
as listed in Iisting2l.4.
Forexample,
CommonDialogl.HelpCommand = cdlHelpConents
Or
CommonDialog l.HelpCommand = &H3&
To illustrate the ShowHelp methods, open the previous NotePad application and add a command button
Help. Set the Name properties as cmdHelp and Caption as Help. You will see the form as shown in Fig . 2l .19.
End Sub
control may be n
nee , or when you nee
Load and Unload
example, paste the code into the Declarations section o
Form object.
Private Sub Form_Click 0
Dim Answer, Msg as String , Declare variable.
Unload Forml , Unload form.
Msg: "po.rrtl has been unloaded. Choose yes to load and .,
Msg : Msg & ,,display
the fonn. Choose No to load the form ,,
We now consider the relationship between the primary and secondary forms (Forml and Form2). The
secondary form will appear when we click on one of the menu items listed in the primary form under
Continents.
The link is the event procedure associated with the continent selection in the primary form. Thus, each event
procedure must generate the appropriate label and text box message in the secondary form and then cause the
secondary fonn to become visible.
When you have f,rnished designing, you have to add code for each menu options in the primary form
(Forml). Open the code window or double click the menu options of Forml for writing the code as :
Private Sub mnuContAfr-Click0
Form2.Label I.Caption = "Area of Africa"
Form2.Textl.Text = " I 1,700,000"
Form2.Show
End Sub
Private Sub mnuContAnt-Click0
Form2.Labell.Caption = "Area of Antarctica"
Form2.Textl.Text = "6,200,000"
Form2.Show
452 Saraswati lnformatics practices (Xl)
End Sub
Private S ub mnuContAsia_ClickQ
Form2.Labell.Caption = ,'Area of Asia,,
Form2.Text l.Text = " 1
g,400,000"
Form2.Show
End Sub
Privare Sub mnuConrAus_Click0
Form2.Labell.Caption = "Area of Australia"
Form2.Textl.Text = "2,900,000"
Form2.Show
End Sub
Private Sub mnuContEur_ClickQ
Form2.Label l.Caption =',Area of Europe"
Form2.Text1.Text = "4,700,000"
Form2.Show
End Sub
Private S ub mnuContNor_Click0
Form2.Labell.Caption = "Area of North America,,
Form2.Textl.Text = " g,900,000"
Form2.Show
End Sub
Private Sub mnuContSou_Click0
Form2.Labell.Caption = ,'Area of South America,,
Form2.Textl.Text =',7, I 00,000"
Form2.Show
End Sub
Private Sub cmdeuit_Clicko
End
End Sub
open the code window or double click Close button of Form2
for writing the code as :
Private Sub cmdClose_Click0
Form2.Hide
End Sub
.t"!,i,
''lir
m 6-G' m h
q>
Fornt VE Data Forrn About Dielsq
Vt'irsld
Wab Brorq
ffi.ffi
h m h
LrginDialoq 5plashScreen Ipnf theDay ODB(l-o4In QpIion Din oq
il - r'i: :
Fig. 21.26 Add Form dialog box to add a new dialog box.
From the above figure, click on the Dialog icon and click Open butron. A
new Dialog Caption dialog box
will be appear
as shown in Fig.2l.27 . This seiection resuits in a new form which
already .ontuln two command
buttons, labetled OK and Cancel.
454 Saraswati lnf ormatics Practices (Xl)
In all other respects, this form is the same as that resulting from the Form selection. Change the Caption as
Colors and add two frames with Text Color and Background Color. Add three option buttons each in the frames
as shown inFig. 2l .28 and object properties listing 21 .6.
Similarly, add another dialog box for Fonts selection as shown nFig.2l.29 and object properties listing
21.7.
Fig. 21.29 Form design window for Text Displays Fonts... options.
Listing 21.7 Object properties.
Object Icon Property Property setting Property description
form Name Dialog2 Identifies the form.
Caption Fonts Size Form title bar display.
Fhame Name Framel Identifies the frame.
Caption Font Size Frame title bar display.
Finaily, the primary form includes the fcrllowing additional event procedures to activate the forns
and
dialog boxes as :
Private Sub Form_Load0
LoadForm2
Load Dialogl
LoadDialog2
End Sub
Note. Before selecting the Text Displal' options, it is necessary to choose the Continents options first ftrr
affecting the Colors... and Fonts... options in Form2 dialog window.
tr lmagelistControl.
D ImageCombo Control.
O Toolbar Control. l'lioosqFt Syslnfo Contrnl 6.0
D Status bar control. I ; lvliolsnfl -Iabhed Dialog CrntrDl 6.0
'i ttl
To rvork with these controls in the
v.: r- oOc
Form, we have to add them in the , il[']ris,:Fl Wird6?"5 Cama,lu. Controh-Z 5.U {5pi F;- :0-
Toolbox. To add,
D ClickProjectmenu.
, ivlirrLrsnf l: 'r/,lindrr^t (antmnn f rrnlrot:-Z 6,tl
,'I4i*66i3ft
.i i:'
'drindorvs rarnnxrri'i*r*ioti n,r: .",
\ffi r
Affii
I
Microsoft windows
common controls
Fig. 21.33 lrnageList Property Pages dialog displays the lmages tab.
In General tab you have to sper:ify the image size. In the Lnages tab, you have to insert the picture for the
control. To inserl pictures.
I Click on Insert Picture button. The Select picture rlialcg box wi]l he appear as shown in Fig. 21 .34.
Common Dialog Box Controls 459
Fig. 21.34 Select picture dialog displayed when lnseft picture.." is pressed.
Here, navigate the directory structure,
which provides proper image files (here we
take the pictures from H: drive) and press *s,*,j rma*t+
fgoy*
Open. After pressing Open the Select picture 'f,urrxntlm*ga - --
dialog box cleses and the image is then loaded ' lnde* i1** {*y
into the Imagelist control.
l"s
Figure 21.35 shows the resuits of adding
one image to the Imagelist control. The
image is assigned an index of 1.
tr Ycu can speciflz a string value for the Key Iieid to lefer to an image in an Imagelist control. Instea<l of
Index properly you can use the value of the Key field also.
tr Image Count fieid displays rhe rotai
number of images.
After inserting, you can reriove i1. To
renlove an image seiect ihe image and click on
Remove Picture button. lbu can also ser the
BackColor ancl MaskColor property of the
lmagei-ist control. To set the color,
al Click the Colt-rr tab in Property Pages
dialog box, the tbllowing Fig. 21.37 will
displayeci. There are two color sets :
Standar Colors and Windou,s Svstem
Colors.
6enau rnnr
I i Ccdc,, I F,rr,re j
obj ect .Add(Index As Variant, Kel' As Variant, Iexr As Yariamt, *mage As Variant,
Selhn.age As Variant, Irtdentation As Variant) hs Cornboltern.
The Add method syntax has these parts which is iisted in Listing 21.8.
EndIf
Enci Sub
Note. The Customize dialog box also includes a Help button. Use the HelpFile and HelpContextlD properties to
detemine which (if any) help file is displayed u,hen the end user clicks the Help button.
To add a Toolbar control.
tr Open your previous project file TextPrint.vbp file of ShowPrint method.
D Save the project file as : frmToolbar.frm
tr Remove the commandbuttons like:
Open, Save, Pint, etc. Make sure
that your form has CommonDialog
control, RichTextBox control and
Imagelist Control as shown in
Fig.21.43.
X Add an Imagelist control by
double-clicking on it from the
Toolbox.
tr Click on Insert Picture button. The Select pictnre dialog box will he appear as shown inFig.21.45.
StatusBar can be divided up into a maximurn of sixteen Panel olrjects that are contained in a Panels
collection.
A StatusBar control consists of Panel objects, each of which can contain lext andlor a picl-ure. Properties
to control the appearance of individual panels include Width, Alignment (of text and pictures), and Bevel.
Additionally, you can use one of seven values of the Style propefiy to automatically display common data
such as date, time, and keyboard states.
StatusBar control is added to the project when Microsoft Windows Corrrnon Controls 6.0 is selected in
the Cornponents dialog.
To create a statusBar :
StatusBar.
D As you see there are four tabs in the Property
Pages Dialog. From the General tab you can the
style, MousePointer etc.
tr Panel tab is used to add panels and to set its
properties and other tabs are used to set the
Font and properties of Mouselcon (see Fig.
2t.s4).
Fi1.21.54 Panel tab in Propefty Pages dialog box.
E To add panel click on the Panel tab. Click on the Style propefty of the Panel tab you will find the
following properties value listed in listing 21.9.
47A $araswati lmforrmatics Practices (X!)
Listing 21.9 Style property values in parael tab.
{ionstant Yalues Description
sbrText 0 Displays text or tritmap picture
sbrCaps 1 Dispiays the status cf Caps Lock key
sbr|ium 2 Displays fhe status of Num i,ock key
sbrtrns 3 Displays the stalus of Insert L:ey
sbrScrl 4 Displays the status of ScrclJ l-ock key
sbrTime 5 Displays the cufl-ent tirne in the systenl format
sbrDate 6 Displays the curxent date in the system fonnaL
tr Click on the Insefi butoon and set the Styie Properry as sbrText. Set the Text property as F1 for Help.
Change the rvidth properry to 1600 as shown in F'ig. 21.55.
BrrronGotFocus Called when a button becomes the active button on the MCI control (i.e.. gains
input focus). Button is one oi'Open, Close, Play, Fause, Stop, Back, Frev, Next,
Seek, Record, Eject, Sound and Save.
ButtonLostFocas Catled when a previously active button trecornes inactive on the MCI controi (i.e",
loses the input focus). Buttonis one of Open, Close, Play, Fause, Str-rp, tsack, Frev,
Next, Seek, Reeord, Eject, Sound and Save.
Done Called rvhen the current command cornpietes.
-w.n,r*3
-.il4icrosq,Ft HTleil Qbie(l Library
j,,licrasoft Ifi le.rnBt Contr6ls
ilficrosaft Internet Transf+r (ontrol 6.8
t4irr,:scfl l,lAFI Cor':trrls 6,U
-il*icrosoff l',1as[."":d Edil CEntro! 6,0
LKi
Private S ub Updateinformation0
Dimminl As Integer, min2 As Integer
Dim secl As Integer, sec2 As Integer
txtCurrentTrack, Text = Form atg (MMContrgl i .Track,,, 00,' )
txtTracklength.Text = _
Format$(MMControll.Tracklength And &HFF, "00,') &,' : " & _
Format$((MMControl 1 . Tracklength And &HFF00) \ &H I 0000, "00 ")
End Sub
From the above program code, procedure Form_load executes and the line,
MMControl l.Notify = False
property disable the Done event procedure from executing after each MCI command
complete. The line,
MMControll.Wf,it= Thue
property indicate that an MCI command should compiete before returniug control to
the program. The line,
MMControll.Shareabtre = False
property indicate that only one application at a time can use the specified MCI device (in this case
the CD-ROM
drive). The line.
MMControll.DeviceTlpe = "CDAudio"
indicate that this control is used to manage a CD-ROM drive containing an audio CD in this program.
The 1ine,
MlVlControll. Comrnand = " Ope11 "
indicate that the device shoulJ be opened (for a CD this means prepare the CD for playing by opening
a
connection between the prograrn and the device). The line,
brtTotalTfacks.Text = Format$(MMControl1.Tracks, "00")
determine the number of tracks on the CD and displays that .;alue in the txtTotalTiacs TextBox.
Event procedtlre Forrn-Unload lines executes rvhen the application terminates. ltre lines,
MMControlLCommand - "Stop"
MMControll.Command = "Close"
uses to stop playing the cD and to close the connection to the device, respecrively.
After writing codes fbr Form._Load event procedure, save the file
(frmcD.F'RM) and press F5 or click starr butron to run rhe CD player applica-
tion. When you run the application, the output screen will display the CD
Player dialog box as shown in Fig. 2l .60. Here, inserl a audio CD player and
click the Play button. You will notice that your audio cD plays with songs.
Review Questions
l. what is the purpose of each of the following common dialog control methods :
(a) Fitter
(b) ShowOpen
(c) ShowSave
(@ ShowPrint
2. I{ow is a secondary form added to an active project ?
3. How is secondary form made visible once it has been roaded ? How is it hidden ?
4. When writiirg Visual Basic code, how do y'ou rettr to the label property of the that resides within a
different fornt ?
5. Create an application that will open a tert file in a RichTextBox.
6. Create a Visual Basic project that will help the user to select the name of a country from a list and then
display the corresponding capital in the second forur. Create the Menu with trvo option Countries and
Change for the following countries only :
Continents Change
Canada Ottawa Color...
England London Font...
France Paris
Germany Berlin
India New Delhi
Itaiy Rome
Japan Tokyo
Russia t\zloscow
US Washington
478 Saraswati lnforrnatics practices (Xl)
Where Change is having two dialog boxes Color and Font. Color dialog box will provide the facility to
change the color of the Capitat to Red or Blue. While the Font Dialog box will privide you the facility to
change the font size ofthe capital to 8 and l0 pornts.
7. Create an application that initially display a grey colour circle, The program will include a dialog box
allowing the user to change box colour to Red, Blue, Green and yeilow.
8. Create a menu containing internationa[ currencies and print its Indian values within a label box of text box
and changing the font style and nrake it Bold using the dialog box..
9. Create a prograrn to Cisplay the name of the Birds. Add five images of birds in the ImageControl. ln the
ImageCombo add the Images. In the Click event of each item display the name ofthe birds in the Label.
10" N{odifu the above prograrx by adding the toolbar. The toolbar contains the images of the bird and when
you click on the button of the toolbar it witl display the lmage of the birds in the Image Control and its
name in the Label. Also add a status bar ir. the application.
ll. Createanapplicationwhichwill provideatoolbarwithfivebuttonoftouringplaces.Wheneveryouclick
any of the Image it wili dispiay the information about that place in the RichTextBox.
72" Create an applicalion which will provide a menu of different States of India. Whenever you click any of
the state it will display the Chief Minister of that state in the second form which will contain one Label
with the caption "Chief Minister " and the TextRox which will display the name ofthe Chief Minister. Also
provide the two dialog boxes to change the Font and Color of the Label and the Text Box.
13. Cleate an application to run a CD through the Muttimedia MCI Control.
-
Chapter - 22
22.1 lntroduction
When one hears the word "Data Base" one thinks it is a collection of lelated infbrmation stored or a storc of
mtrtually related data. The coutent of a database is obtained by combining data from allthe different sources i1
an organization. Horvever, this tem is rnostly used in connection with computerized database. So that data are
available to all users and gives us some electronic filing systen-r, whieh has a large number of, says of cross-
refereneing and this allorvs the user to access and rranipulate the computerized databases.
So, a database is a collection of relatcd inforrnation. whicli is available to many users. A database can
handle business application such as inventor;-, accounting and preparing notes. The rvell-known example of
database is MEDILINE, which is database service providing rnedical information for doctors.
T'he database is managed by a software package known as database management system. Some commonly
used DBMS are ORACLE, Sybase etc. So, a database managernent system is a cornbination of hardware ancl
software that can be used to set up and monitor a database.
(47eI
480 Saraswati lnf ormatics Practices (X!)
afile system. It is also a very slow process. lt may even involve modification of application programs.
O What is worse, modification in one program rnay require modifications in otherprograms which interface
with this program. This process l.nay set off a chain reaction of rnodification.
The above prcblems give rise to fur-ther difficulties detailed below :
tr The management information system (NllS) organization finds it difficult to control data, especially
rvhen the actual r"rsers cievelop applications on their own.
D Major changes required in thc sl,stern rvhile modifl,ing files increase the maintenance load on Data
Processing (DP) professiorials substantiallv, thus rnaking them unavailable for de..,elopment of new
system.
tr High-level data redundancy entails repetitjve data enlry and redundant storage with the accompanying
costs.
0 As has been already stated, Data Base Systems provide an effective solution to the above problems.
22.3 Advantages of Database Management Systern
As we have seen there are lot of difficulties in the file - oriented system. To overcome these difficuities the
DBMS approach is introduced. The main advantage of database system is centralized control. The centralized
controls have many advantages. These are :
(a) Data redundancy is reduced. Redundanc,v means duplication of data. Some time it is possible that the
same piece of information rnay be stored in two or more files. For example. the particulars of an
individual who may be a cnstonrer or an employee may be stored in t'uvo or nrore files. Some of this
information rna1, be changing, such as tfie address, the pay dratvn, etc. It is therefore quite possible
that while the address in the rnaster file lor one application lias beeri updated the address in the master
file for another application 111n., have not been. It may not also be easy for the computer-based system
to even find out as to in horv many files the repeating items such as the address is occurring. The
solution therefore is to avoid this data redundancy and the keeping of multiple copies of the same
infomation and replace it by a system where the address stored at just one place physically, and is
accessible to all applications frorn this itsetf.
(D) Sharing of data. As we knorv a single database is available to many users. So, a database allows the
sharing of data, which is controlled by DBA to any nurnber of application programmer.
(c) Inconsistency is controlled. When there is a redundancy in the database then there is a chance that
the two entries with same data do not match. When this situation arises in the database the database
is called inconsistent.
So, if we control the redundancy the inconsistency is automatically controlted. It is necessary to control
the inconsistency because inconsistent database always provide wrong information.
(rI) Data integrity. The data integrity means that the data contained in the database is both accurate and
consistent. Tl.re centralized control ofthe database provides data value integrity. Therefore, before
Cata value being entered in the database the DBA checked to ensure the validity ofthe data that is the
data should be full in specific
range and in correct format. For example, if we have to create a database
ofvoter then ra,e have to check that the age ofthe voter should be greater than 1 8 vears and ifwe have
to enter the date then we have to check month do not exceed 12 and depending on month days are
checked.
(e) Data security. Some data present in the database may be confidential ofthe organization. Unauthorized
persons must not access such confidential data. The DBA who is controlling the database can ensure
that the proper access procedures are followed. The DBA performs some checks before pennitting
access to sensitive data. Different leveis of security could be implemented for various types of data.
The enforcement of security could be data value dependent as weil as data type dependent. For
example, a manager in the company can access salary structure of employees in his / her department
only Su1 cannot access the medical history of any einployee.
Database Concepts and ADO eontrols 481
Query/Prograrr
Process
Storage Access
Application
Database User
(c) Internal view. 'rhis is the lowest lel'el of abstraction. It is closest to hardware. lnternal view
describes
hor'v the data are physicalll'stored. It also describes rhe data
structure and access rnethod to be used by the
database. Internal view is closest to the physical storage.
So, there are three levels of abstraction in the database. A database
management system that provides
three iel'els ofdata is said to follow three - Ievel- archiiecture ;
Extemal Level
IMapping Supplied by
Conceptual I-evel
Teacher Studellt
Tno# Tneme Course Title Sno# Sname AEe
T01 Ramaya Clomputer s0l R"onny 17
Couse
T01 s01 l0
T0l s03 l5
TA s04 9
TA s05 t2
TA s03 14
r03 s02 15
IUJ SC-? l7
T04 s0l 8
m5 s03 n
T05 s0s 20
O Relation or Table
tr Columns
O Rows
J Field
O Degree
O Cardinality
Relation
A relation is a two dinrensional table. 11 has following properlies :
(l) Each coiumn contains vaiues about the sarne attribute and saclr tabie value must be single.
(ll) Eachrowofatablernustbeuirique.thatisnotworowshaveidenticaidatavaiues.
(iii) The order in atable is irrelevanr.
(lv) Each column is given an arbitrary,name.
Colurnns
The columns qf a fable arQ also called altribur.es. The column rs the verticai part ofthg relation" For exarnple, from
Fig.22.3,the TNo# is a Qolumn which is also the prirnary key. The teachernumber identifies a unique teacher in
|EACHER table. A primary key must contain a value.
Rows
This is the horizontal part of the relation. One rorv represents one record of the relation. The rows of a relation
are also called tuples. Each rorv in a table should be identified by a primary key, which allows no duplicate
row.
The order of rorv is insignificant, specifl, the row in or der when the data is retrieved.
Field
A field can be found at the intersection of a row and a column. Thee can be only one value in it.
Degree
The number of attributes (column) in a relation is called the clegree of the relation. So, iftable have 5 columns
then relation is said to have a degree -s
Cardinality
The number of rows (tuples) in the relation is called its cardinality. Suppose, there are I 0 records in the table. So,
the cardinality ofthe relation is 10.
Advantages of Relational Data Model :
(r) This model is easy to use. It is a very natural and attractive model.
(ii) This model is flexible. It is very easy to link two or nrore tables.
(iii) Securify control and authorization can also be implemented more easily.
(lv) Data independence is achieved mor.e easily with normalization
Disadvantages of RelationalData Model :
The rnain disadvantage of relational data model is machine performance. If the numbqr of tables between
which relationships to be established is larger than the performanqe in responding to querigs is definitely
degraded.
22.9 Keys
First, let's discuss the concept of keys. A primary key is acolumn or set of columns that uniquely identifies the
rest of the data in any given ro1v. For example, in the Teacher table, the Tno# cqlumn uniquely identifies
that
row. This means two things: no two rows can have the same Tno#, and, even ifhvo teachershave thp same
first
and last names, the Tno# column ensures that the two teacher willnot be confusecl with each other, beeause the
unique Tno# column will be used throughout the database to track the teachers, rather than lhe narnes.
Aforeign key is acolrtmn in a table r.vhere that column is a primary key of a;rother table. which means that
any data in a foreign key column must have corresponding data in the other table wltere that column is
the
primary key. A foreign key refers to a primary key or a unique key in another table.
In DBMS-speak, this
correspondence is knou'n as referential integrily. For example, in the Course table, the Sno# is the foreign
keys, which is the prirnary key of the Student table.
Database Concepts and ADO Controls 485
A table can tiave more than one possible primary key, Either one, alone. is sufficient to identifl, each record.
only one can be the primary key; tlre other is the alternate key or candidate key.
22.10lntegrity Rules
The relational model include two integrity rules
22,10.1lntegrity Rule 1 (Entity tntegrity)
As we discussed the primary key of the tabie rnust have the unique values, which iclentifi the each row. So, if
any row is having the value NULL for the primary key. The rule of primary key violate that is the prirnary key
must be unique. This the reason to follow the entity integrity rule according to which primary key will not
accept the null value.
This rule state that if attribute A of relation R is a prime attribute of R, then A cannot accept NULL values
22.10.2 Integrity Rule 2 (Referentiat lntegrity)
This rule state that Given two relations R and S, suppose R refers to the relation S via a set of attributes that
froms the primary key of S and this set of attributes forms a foreign key in R. Then the value of the foreign key
in a tuple in R must either be equal to the primary key of a tuple of S or be entirely null.
22.11 Normalization
We can develop conceptual data model into any database model. But while representing the conceptual data
model into well-designed data management, we face many difficulties like data storage, access time etc. So, a
systematic technique is required to implement the data model.
If a table has particular set of well-defined chalacteristics, it is said to be in a specific normal form. The
process of converting a table from one form to another form is called Normalizatior-.
The basic objective of normalization is to reduce redundancy, which means that data is to be stored only
once. Because storing data many times lead to wastage of storage space and increase the access time. So,
relations are to be normalized so that we can alter them at any time without doing many changes.
Insertion. 'Ihe above relation is in 1NF but in above relation lve cannot insert a teacher until he/she does not
have any topic, So, we have to wait till a teacher assigns some topic.
Deletion. In above relation if rve delete the topic then the teacher name and its other detail also get deleted.
'Ihus, lve may lose the infonnation about tire teacher and its students.
[Jpdation. Noui as you see in the above table a teacher is teaching more than one student the detail of the
teache; is repeated every tinte.
The solution for the above table is to reduce the table into second normal form.
Student(Sno#, Sname)
Teacher(Tno#, Tname, CNo#, CTopic, CSubject)
Result(Sno#, Tno#, Grade, CNo#)
The nonkel' attributes of these relations are fully dependent or the primary keys. So, the above
table is in
the 2 normal tbrm. But if you see the Teachel table carefully, it still suffers from anomalies :
Insertion.we cannot insert a new teacher untill he/she is not assigned a subject.
Deletion. Deletion of any course may result in loss of teacher data.
update. If a teacher teaches more than one course his,&er data occur many times.
The third normal form solve the problerns of second nonnal form.
22.11.AThird Normal Form
A table is said to be in ThirC Normal Form if :
tr [t is in second normal form
tr Every nonkey attribute is non-transitively dependent upon the primary ke1,.
That means every nonkey attribute is only depend on the primary key. So, we can reduce the table as
follows :
Student(Sno#, Sname)
Teacher(Tno#, Tname)
Course(CNo#, CTopic, CSubj ect, Tno#)
Result(Sno#,Tno#, Grade, CNo#)
For most practical purposes relations in third normal form are surficient. However there are further normal
forms like BCNF, Fourth Normal form and Fifth Normal Form etc., to remoye any further anolamies.
22.11.5 BCNF
consider the course table given above. It still sufler from some anomaries :
Insertion.We cannot inseft any new course untill a teacher is there to teach that course.
Deletion. If we delete the information about any teacher the.r the course record also get deleted.
Ifthere are more than one teacher teaches the same course, the course detail will be repeated again and
agaln.
To overcome these problem we fur1her divide the table into two tables these are :
INF relations
2NF relations
3NF relations
22.14 Middleware
A database is used to store the data. It is completely different from the fonl (Front End application). The
database can intetact with many ianguages as compared to the front end application. Hence, there is some
middleware is required to make the transaction between the user form and the database. The most common form
of middleware is suppiled by the Windows Operating System itself. This is 32-bit ODBC. (Open DataBase
Connectivity).
AOO
!qv
l- L:):1,t1
il
F$frdss[LOnt6€rid Cr'niro]6.ndCL€$S) 1:
-,
to,:1,o0:. {:ir1,iN*o\,s;\IysT::r:rdsflRD.sfi(
-
the Usc Connection String first. So, click on $deel-1he .{aia3ou r.+drt ls tq6r Bt to:
tr When you will click on the Connection tab, it will ask you to solect or enter the databa-se name as
shown in Fig. 22.10.
{v *Btankms*rxd
:. i
.l
'r
Lool.in trl
. oper r as lead-only
t"
I
I
lesl l)ortrrecii6': )
D Now to view the data fronl the table through ADo Control, add three
TextBoxes on the fonn and the
three Labels to specify the field name. The form will look
like as shown in F is22.l5.
,lsjshf*
Alph&iir
lCur*so*os I
&H8L-r000a05s
5ttle 1 - Fixed Sirrgie
True
iNcnE)
, [ - l'l;nudl
True
,!ll 5;n( 59tiI
I *xaooootonr:'
.ia '-
a'cmao'iq
Ad*dcl
After setting all the properties, save the file (frrnGrid.FRM) and press F5 or click start button to run the
DataGrid application using ADOCDI. When you run the application, the output screen will display the first
record from Author's table as shown in Fig. 22.19.
Datalist
The Datalist contr-ol is code-compatible with the DBList control. However the Datalist control is optimized
to work with ActiveX Data Objecm (ADO).
Whereas the DataCombo control is a data-bound combo box that is automatically populated from a field in
an attached data source, and optionally updates a field in a related table of another data source. The general
syntax as :
DataCombo
The DataCombo control is code-compatible with the DBCombo control. However the DaCaCombo control
is optimized to work with ActiveX Data Objects (ADO).
496
Saraswati lnformatics practices
Each of these controls is capable of being populated automatically
using the data from one field of a
Recordset' The controls look and operate like the standarcl
ComboBox and List intrinsic controls. but they,
provide several properlies that make them more flexible
than the intrinsic controls for database applicarions.
Listing 22.1 rmportant properties of the Datacombo and
Datar,ist controls.
Property Description
BoundColumn Tlie field in one Recordset that is supplied to another Recordset.
BoundText The value of the BoundColumn field.
DataField A field name in the Recordset produced by the DataSource.
DaiaSource The name of the data control to which the control is bound.
IntegralHeight Specifies whether the control maintains a height that causes
only complete rows to
be displal,ed or allows partial rows to be displayed.
ListField The narne of the field in the Recordset produced by the Datasource
that is used to
populate the list"
MatchEntry specifies how to search the entries in an active Datal-ist or Datacombo
as the user I
t1,pes characters.
RowSource The ira,ie of the data contror that provides the data to populate
the iist.
Selectedltem Retu.rs a Bookmark for selected item's ror.v in the Recordset.
This can be used to
keep t.ack of a location in the Recordset and retum to
that location at a later tirne.
VisibleCount The number of r,,isibie items in a list.
To add the Datalist and DataCombo controls to the toolbox,
t-r<etir,m f r[4,1t1*]Wf{5lSrypaiy61Ey3.*,
'l: Crrcal
i[::::"l:i",:,ii-
tr From Fig. 22.23, clic,k nn rhi) Finish button. The ODBC b{icrosoft Acsess Settip elialog appears as
n,gJ$oiinqp $ar,rs,
0e;al#iira
i-..
I "'.._J)
1 ,. ' 'l ,
.1 .",,. . i:r
il*tzaer. Fhilip',*.
0 otidie. John
St,dt,rl- Dan Parho
Llogd. John
Thiel. Jamar P
Irrghanr. Kerrneih
J
} llr
Fig.22.29 Authors in Datalist and DataCombo control.
Database Concepts and ADO Controls
501
-
Solved Exercises
l eacher Topic
Suman LAN
Ajav DBMS
S. Ray Thennal
P. Lal Organics
M. Singh Algebra
For each teachet the address ofthe teacher is also present in the database and for each topic to which
subject it belong. The database also contains which teacher takes how many classes on their topic. Draw
a relational view for above data.
Ans. The Relational view of above data is :
502 Saraswati lnformatics Practices (Xl)
Q8. What is the need fol normalisation ? Define first, second and third normal forms.
Ans. Normalizationisaplocessofdataanalysisusedforgroupingdataelementsinarecord.Whiledealing
with databases there may be uilnecessary repetition of data, which can pose problcms in storing, and
retrievi6g of data. The unnecessary repetition of data is called redundancy, Normalization is the process
ofanaiyzing data. So, the reciundancy gets reduced"
First Normal Form : A table is said to be in first normal form if no two rows are identical and each entry
is single value.
Second normal form : A table is said to be in 2NF if it is in t'irst normal form and each non-key atlribute
depends on the entire key.
Third Normal Form : .r\ table is said to be in third normal fbrm if it is in second normal form and every
non-key attribute depends non-transitively on the primary key.
Q9. What is norma!isation ? L)efine first uormal forrn
Ans. Norrralization is a process of data analysis used for grcuping data elements in arecord. While dealing
with databases there may be unnecessary repetition of data, which can pose problems in storing, and
retrieving of data. The unnecessary repetition of data is called redundancy. Normalization is the process
ofanalyzing data. So, the redundancy gets reduced.
First Normai Form : A table is said to be in first norrnal form if no two rows are identical and each entry is
single value.
Q10. What is normalisation ? Define second normal form.
Ans. Normalization definition frcrn previous arlswer.
See the
Second normal form : A table is said to be in 2NF if it is in t-rrst noimal form and each non-key attribute
depends on the entire key.
Ql1. Give an example of arelation vrhich is not in second normal iorm alongwith justitication.
Ans. The table gil'e below, the relation, wfrich is not in second normal form :
TNo# TName TTopic TDept
T01 Mr. Nayak DBMS Comp. Science
T0r Itlr. Nayak LAN Comp. Science
T0i Mr. Nayak Multimedia Comp. Science
T02 Mr. Go.iind Algebra Mathematics
m2 Mr. Govind 3-D I\4athematics
m2 Mr. Govind Calculus Mathematics
T04 Ms. Meeta Physical Chemistr.v
T04 Ms. Meeta Organic Chemistry
Relational data model, In this model data is stored in conceptual tables in rvhich rows are instances and
columns are fields. E.F.Codd ofthe IBM proposed the relational model.
Ql4. What is referential integrity ?
Ans. ThisrulestatethatGivcntworelationsRandS,sulrposeRreferstotherelationSviaasetofattributes
that froms the primary key of S and this set of attributes fonns a foreign key in R. Then the value of the
foreign key in a tuple in R must either be equal to the primary key of a tuple of S or be entirely null.
Ql5. What is foreign key ?
Ans. A/oreign key is acolumn in a table where that co lumn is a primary key of another table, which means that
any data in a foreign key colurnn rnust have corresponding data in tne other table where that column is
the primary key.
Ql6. Nonnalize the table rvith the follwoing specification :
Employee(Empno, Name, Address, Salary DOJ, Dept-no, Dept-name)
Ans. To normalize the given relation we willbreak the relation into two relations :
Employee(Empno, Empname, Address, Salary, DOJ, Dept-no)
Department(Dept_no, Dept name)
Q17. What is the difference between Front End and Back End '7
Ans. Front End. A front end is traditionally forms based. A form being used to capture and validate user data.
But it will not provide the rrethod to store the data entered by the user. Visual Basic is one of the
commericia[ application's front end.
Back End. As you know that the database is managed by a software package known as database
management system. l'he database tnanagement system is generally used to store the data which are
provided by the user through the front End.
Q18. What is MiddleWare ?
Ans. A database is used to store the data. It is cornpeletely different ftom the form (Front End application). The
database can interact with many languages as compared to the front end application. Hence, there is
some middleware is required to make the transaction beflveen the user form and the database. The most
common form of middleware is suppiled by the Windorvs Operating System itself. This is 32-bit ODBC.
(Open DataBase Connectiv ity).
Ql9. What is Datalist Conrrol ?
Ans. The Datalist control is a data-bound list box that is automaticaily populated flom a t'ield in an attached
data source, and optionally updates a field in a relaled table ofanother data source,
Q20. What is DataCombo Control ?
Ans. The DataCombo control is a flata-bound cornbo box that is automaticalll'populated {tom a field in an
attached data source, and optionally r-rpdates a field in a related tab[e of another data source.
Q2l. What is DataGrid Control ?
Ans. The DataGrid display the fields value in the tabular lorm. Each row in the table represents the record and
each column represents the field.
Review Questions
l. Define database.
2. Explain the difference between :
(a) database and file (b) data and file
3. Explain three level abstraction of the database system'
4, Describe the components of the database system.
5. What are the advantages and disadvantages of DBMS ?
Employee Manager
Emp# Ename $lary Emp# Ename Salary
0l x 5000 m
y " 3500
05 4_s00 0,1 b 2500
06 z 3000 05 y 4500
a w 3500
Perform the following operations on the above table and show the resultani
relations :
(a) nBmp#,Ename(Ernployee) (b) 6Emp#>O5(Employee)
(c) emplol,ee \J manager (d) enrploye. rr",ut,ug!.
(e) ernployee-manager
ffi employee ^* ,rurru!..
12. What is data redundancy ? How it will control ?
13. \Vhat is data independence ?
14. Suppose that all the customers of a particular business live in states for
which city name is unique. Given
the following description for customer data :
CUSTOMER (NAME , STREET, CITY, STATE, PI]ONE, ID
)
(t) List the most likely
key for the primary key . (li) List the functi.onai dependencies of each field.
(iil) what is the normal form of the table ? (lr') convert the table into 3 NF.
15. Let there be three relation
Relation (M, N, R, e, p)',vith M N is the key. Letthe following istrue
:
MN
N->Q
->R
N_-> P
Convert RELATION into 3NF.
16. Deflne the following :
(i) Tuple(ii) Attributes (iii) BCNF
17. Normalize ihe table as per the given specification:
Book( Oredr_no, Customer name, Order_date, ISBN, Title, author, price
r8. State the Entity Integrity rule.
19. What is BCNF ?
20. List some Front End and Back end tool.
21. How will you add ADo controi, DataGrid control ancl DataCombo
control on the toolbox.
fi What is the purpose of the ADO Control ?
23. Connect some tables of MS-Access using the ADO Control
and view the data in Datalist, DataCombo
and DataGrid.
Chapter - 23 -
lntroduction to Orqcle
23.1 lntroduction
Oracle is the most widely used database in the world. It runs on virtually every kind of computer. It functions
on all these machines, so v;hen you learrr it on one, you can use it one any other. This fact makes knowledgeable
Oracle users and developers very much in demand and makes your Oracle knowledge and skills very pofiable.
Oracle provides a flexible RDBMS called OracleT. Using its features, you can store and manage data with
all the advantages of a relatronal structure plus PLISQL, an engine that provides you with the ability to store
and execute program units. The server offers the options of retrieving data based on optimization techniques.
It includes security features that control ho*' a database is accessed and used. Other features include consistency
and protection of data through loeking mechanisms.
t
Fig" 23.1 Client-server architecture.
Most of the application svstems will involve modules with functions for a front-end GUI, business ru1es
processing, and data access through a DBMS. In lact, major systems such as online reservation, banking and
brokerage, and utility billing involve thousands of business rules; heterogeneous databases spanning the
(505)
--____,,
506 Saraswati Infornnatics Practices (Xl)
globe, and hundreds of GUI systems. The development, administration, maintenance, and enhancement of
these sYstems invoh,e handling millions of lines of code, multiple depa{ments, and coordinating the work of
hundreds if not thousands of personnel aci'oss the globe. The muititier s,vstem design and development
concepts are applied to a range of systems from departmentai systems to such global information systems.
In the two and three-tier systems, an application is logicaliv diviCed into three parts ;
e GUI. Consists of the screen, i.vindows, truttons. list boxes. and rlore.
D Business logic. The part of the prograrn that deals with the various data element interactions. All
processing is done based on values of data elements, such as the logic for determining the credit limit
depending on annual income, the calculation of income tax based on tax tables, or a reorder point
calculation logic based on the material usage belonging to this category.
tr DBh{S. Deals with the actual storage and retrieval of data.
23.2.1 Two-Tier Systems
On the basic levei, a two-tier system involves the GUI and business logic directly accessing the database. The
GUI can be on a client system, aitd the database can be on the client system or on a server. Usually, the GUI is
written in languages such as C++, Visual Basic, PowerBuildel Access Basic, and LotusScript. The database
systems typically are \{icrosoft Access, Lotus Approach, Sybase SQL Anywhere, or Watcom DB Engine and
Personal Oracle.
+-->
(S;l.{{:ffi,'di
Fig. 23.2 Three-tier arch itecture.
The three-tier architecture signilicantly increirse's )our oppoiluniteis for distributing an application's
workloaci over multiple servers. However. it also increases thc nulrher ol points of failure in the architecture ancl
complicates the configuration of a preproduction test environment, Oracle suppots many different ways of
implementing a three-tier architucture and you rvill need to seiect the architecture that best suits the needs of
youl application.
Most of the organizational and many of the departmental clienl/server applications today follow the three-
tier strategy in which the GUI, business logic, and DBMS ire logically in three la1,ers. Here rhe GIII development
tools are Visual tsasic, C++, and PowelBuilder. The middletier development tools also tend to be C++ or Visual
Basic, and the back-end databases are Oracle. Microsoft SQL Server, or Sybase SQL Server. The three-tier
concept gave rise to ail era of database servers. application servers, and GUI client machines. Operating
systems such as LTNIX, Windows NT, and Solaris rule the appliczition server and database server world. Client
operating svstems such a-q Windows are popular for the GUI frorrt-end.
lntroduction to Oracle
5Ut
23.3 OracleS and Oraclegi
oracleS is the first object-capable database developed by oracle. It
extends the data rnodelling capabilities of
Oracle7 to suppott a new object relational database model. oracleS provides
a new engine that brings object-
oriented programming, complex datatypes, complex business ob.iects
and fuli compatibility with the relational
world.
Oracle8 extends OracleT in many lvays. It includes s improved perfbrmance and
functionality of online transaction processing (OLTp) appl
fter sharing of runtime data
structures, Iarger buffer caches and deferrable constraints.
pri."ii"rrf*i1 benefit llom
enhancements such as parailel execution of insert, update and clelete
operations; partitioning and parailel-
aware query optimization. operating within the Network Computing
Architecture (lical llame-work. oracleg
supports client-server and Web-based applications that are distributed and
multitired.
Oracle8 can scale tens ofthousands ofconcurent users, support up to 5 l2 petabytes
and can handle any
type of data, including text. spatial, image, sound, video and time series
as well as traditional structured data.
Oracle8i, the database for Intenret computing, provides advanced tools to
manage all types of data in Web
sites' It is much more than a simple relational data store. The lnternet File
System (rFS) combines the porver of
oracleSi with the case of use of a file system. It allows users to move all of their
data into the oraclegi database,
where it can be stored and manages more efficiently. End users can easily
access files and folders in oracle iFS
via a variety of protocols, such as HTML, FTP and IMAP4, giving
them universal access to their data.
with the nervly introduced resource management, the DBA can choose the best
method to fit an application,s
profile and workload. The extended features of paraliel server and
networking improves ease of system
administration. The extended functionalitl'of advanced replication results
in better performance and improved
administration. The extended functionality of advanced replication results
in better performance and improved
security. Significant new functionalities have been added to languages.
Oracle8i provides full, native integration with Microsoft Transaction Server (M
IS) in the Windows NT
environment. Application development is simplified by the oracle Application
Wizard (iAppWizard) for Visual
Studio, which provides developers i.l'ith a GUI tool for creating a visual e++,
Visual Interdev or Visual Basic
application accessing data in an Oracle database.
Oracle offers a wide variet-v of the most advanced graphical user interface (GUI) drive
development tools
tobuild business applications, as well as a large suite of soliwale applicati<.rns for many areas
of business and
industry. Stored procedures. functions and packages can be written ty using SeL, pLlSeL
or Java.
23.5 Why SQL Fit in ?
SQL is the standard language for accessing oracle data. The database world is becoming increasingly
integrated, and this has led to a clamor for a standard language that can be used to
operate in iany different
kinds of cornputer environments. The advantage of the learning standard language ii that
users leanr it once
and use it to create, retrieve and rncdif,i inforrnation regardleis of whether ttl"y ur"
working on a personal
computer, a node or a mainframe cornputer. Because of the machine intlependence
feature of Sqf. and its
suppoft to relational database, it has become the standarcl language for the RDBMS. The
SeL standard is
deflu:red by the ANSI' Intially SQL is the product of IBM ..r.u..h. But other
companies picked up SeL. In fact,
at least one company oracle beat IBM to the punch with a marketable sel product.
*
23.6 Role of SQL and SQL Plus in RDBMS
SeL is a standrad language for communicating with the RDBMS from any tool. SQL can be used by a range of
users. It is non-procedu.ul lungrug" which look like an English ianguage. When you enter a SQL statement, it
is stored in a pa-r1 of memory, called SQL buffer and remain ttrere until you enter a new statement. SQL allows
you to communicate with the server and has the following advantages :
O Itisefflcient.
D It is easy to learn.
tr It is functionally complete having the features like creating, retrieveing and maniuplating the data
in the tables.
SeL*pLUS is an Oracle tool that recognizes and submit SQL statements to the Oracle server for execution
* It
and contains its own command language. SQL PLUS provides a line editor for modifiing SQL statements'
is also used to format query results into a basic repoft. Also , helpful in accessing local and remote databases.
But SeL*PLUS does not allow manipulation of values in the database. The SQL*PLUS statemenst are entered
in line at a time and not stored in the SQL buffer. So, we can say that the SQL is a langauge but SQL*PLUS is
an environment. So, SQL
*PLUS is an environment which provide you the following facilities :
23.7What is User ?
SQL is mostly used on the computers that have more than one user. When rrumber of user are working on a one
computer there is a need to differentiate behveen them. So, it is necessary that there should be some authorization
code be there to identifu the user. When the user start working on the SQL*PLUS, he or she must logs on,
which tells the computer which user, idetified by its authorization ID is working on the computer. Any number
of people with sarne authorization ID is treated as one user. On the other hand, a person can be many users by
using different authorization ID.
A table or other objects which is created by one user is owned by that user only. A user may or may not
have the privilege to perfonl an action on an object he or she does not owl; i. e., cretaed by the other user untill
that user give the privilege. Hor,v one user can give privilege to otherwill be disscused later on'
Solved Exercises
Ans. Oracie applications may run on the sarne computer as the Oracle Server. Aiternatively. you can run
applications on a system local to the user and run the Oracle Server on another system . This technique
is called client-server architecture'
Q2. What is the difference between two-tier system and three tier system ?
Ans. On the basic ievel, a two-tier system involves the GUI and business logic directly accessing the database.
The GUI can be on a client system, and the database can be on the client system or on a server'
lntroduction to Oracle 509
in three-tier architecture there are three separate components : a client, an application server and a
database server are there.
Q3. What is the Oracle8 ?
Ans. OracleS is the first object-capable database developed by Oracle. It extends the data modelling capabilities
of OracleT to suppoft a new object relational database model. Oracle8 provides a new engine that brings
object-oriented prograrnming, complex datatypes. complex business objects and fuIl compatibility with
the relational wor'ld.
Q4. What are the advantages of using SQL ?
Ans. SQL allows you to communicate rvith the server and has the foilowing advantages :
- tt is efficient.
'- It is easy to learn.
- Itisfunctionallycompletehavingthefeatureslikecreating.retrieveingandmaniupluatingthedatain
the tables.
Q5. What is SQL*PLUS ?
Ans" SQL*PLUS is an Oracle tool that reeognizes and submit SQL statements to the Oracle server for execution
and contains its own command language. SQL * PLUS provides a line editor formodif,ing SQL statements.
It is also used to format query results into a basic reporl. Also , helpful in accessing local and remote
databases. But SQL*PLUS does not allow manipulation of values in the database. The SQL*PLUS
statements are entered in line at a time and not stored in the SQL buffer. So, we can say that the SQL is
a langauge but SQLxPLUS is an environment.
Q6. 'il/hy authorization ID is required ?
Ans. SQL is mostly used on the computers that have more than one user. When number of user are working
on a one computer there is a need to differentiate between them. So, it is necessary that there should be
some authorization code be there to identity the user. When the user start working on the SQL*PLUS, he
or she must logs on, which tells the computer which user, identified by its authorization ID is working on
the computer.
Review Questions
1. What is a RDBMS ?
2. Describe the parts of two or three tier architecture.
3. Write the name of some front end tools.
4. Write short note on Oracle *i.
5. What is Oracle Internet platform ?
6. Why SQL is used as a standard langauge for RDBMS ?
7. Differentitate between SQL anci SQL*PLUS.
8. Write shorl note on Users, Roles and Privileges.
Chapter - Ztl
24.1 lntroduction
The chapter introduces Structur"ed Query Language (SQL) and gives an overview of its clifferent capabilities.
SQL commands have their orvn syntar-, keywords, and rules of order. it takes some practice to master the SQL
SELECTcommand.
24.2Averview of SQL
A database management system requires a query language to enabie users to access data. Structure
Query
Language (SQI- - pronounced 'sequel') is the language used by most relational database sysrems. SQL was
developed in a prototype reiational database management, System R, by IBM iir the mid-1970's. System R was
developed by E.F.Codd in Ncrvernber I 976 Joumal of R and D. ln 1979 Oracle Corporation introduced the first
commerciallv available implementation of SQI-. The American Nationai Standards Institute (ANSI) adopted
SQL as the standard language for RDBMSs in 1986. The Internationai Standards Organization (ISO) has also
adopted SQL as the standard lan_euage for RDB[,lSs.
SQL is a set-oriented language. A query against one or more data tables produces a result data table. Because
Xbase language and other host languages, such as COBOL, or PLII, are record-oriented, the ANSI standard
specifies the cursor as a mechanism to provide record-at-a-time access to result tables.
SQL manages one or more data tables in the context of a database, a concept that is foreign to the
traditional Xbase. SQL directly'supports the relationships between data tables, called scherna, with inforniation
in the data dictionary. A separate data dictionary is gr<lupecl u;ith each database in the subdirectory.
SQL allows you to comtnunicate with the database and has the following advantages :
tr Efficient
tr Easy to learn and use
tr Functionallycomplete
tr Recovery and concurrency : Concurrency is concerned with the manner in which multiple users
operate upon the database. Each user can either reflect the updates ofa transaction or can cancel all
the updates of a transaction.
tr Security : The security can be maintained by view rnechanism. A view is used to hide sensitile
information and defines onll,part of a table which should be visible.
il lntegritv constraints : Integrity constraints are enforced by the system. For example , one can specify
that an attribute of a relation wiil not take on null values.
24.4 Glassification of SQL Statements
SQL statements are divided, into three sub-languages:
U Data definition lanp;uage (DDL) - Useci to define the objects in realtional databases. e.g. CREATE.
ALTERandDROP.
(s10)
A Dara tnanipulation language (DML) - Used fbr query, addition, deietion and updation of data stored
in the database.e.g SELEC! UPD.ATE, and DELETE.
tr Data conirol language (DCI-) lJseci for controlling data storecl in the clatabases.e g. GRAN1,
REVOKE(TCL)"
i! lrc-*re,ies
i$
-;r
AD[, s-ort"n,.
",-r -
t$ ,*v*.ce S*rld ti*-re1rr
i HPi-:.er.iBi
-! [1rc,D:]ll Ullr:t
ij i',iiri;:rrl [rlrira icoi:
:^. SteirUn
-:ii \r/Birl,
1,15'OflS ltrr*n:pt
i$ Metrcap,- tl:mmrnihucr B
l:
fl+el' I
Adoh*,Acr,:b*t 4 [ i
i '.iY pra*siPr*,ioi-D P[.8a0
G,ii$s10
- i-j ldErosolr Oeve I
t.
i3 l"linssDltvisua ;.
9etiLqs
tNIYPE FibAssista*
Imd ElinnS 5*mpl.:: 5utiot Fonts I B atsbase Atininistr,:lion '(i,
l. "^e SlNaviggts
!$ Sdrxlllou:a Fonts r'.i{ hiigration Utilitiqs >
Belp
$ r:ore0B{!13 It.s N eti+crirlAdri$nist", atic-n I
Eun i-|. ioi."oo'r,"dia Rrth : r6i Fehas*Notee -.
.:* .. -* - *- I
!a lp La+-p.Jat iir60
loq Olt Ga!,arr !,S, olilirie sen';ces >
ifi . H*,,+uqfucLarr t
$hui 0ir^rn
E lidbrpi'oftVisuat Easie6"0 t
Fageii*k $ HP Piecisin"r-icani-IX I
iii* l,ii
{! I
:Connected to:
OracleBi Personal Edition Release 8--t.5.0"0 - Production
l,ith theJaua option
PL./SQL Release 8 -l -5 - 0- 0 Production
SQL> I
24.8Dalabase Obiects
An oracle table can be created at any time. An Oracle database can conatin multiple data structures. Each
structure should be defined in the database design stage so that it can be created during the initial stage
of
database developement. The following are the Database objects available in SQL :
24.11SQt DataTypes
When you are creating a table , you need to specify ihe datatype of each coiurnn. The table given below
list
important daiatypes.
The data type may be follovyed by one or more numbers in parentheses which give information about
the
column's width. The colur,rn's rvidtlr determines the maximum width that values in the colurnn may have.
\ARCHAR@ columns must bave a size specifiecl. NUN,IBER and CHAR columns may be givcn a size, but
defaults are available. The follorving listing 24.I shows the sel data types.
Listing 24.I SQL dara types.
Dataffie Dese ription
IAPCHAR2(w) variable length character values upto width w. Maximum width is 2000 characters.
CHAR(w) Fixed length characters values of width w. Default width is I and maximum width is
235.
NUMBER(qp) Number with precision w and scale p. precision represents the maximum significant
digits allowed , which rnay not exceed 38. Scale is the number of decimal piaces .
DATE Date value from January 1 ,4712 BC to Decernber 3 l, 4712 AD.
LONG Variable length character value upto 2 gigabytel,
C[,OB Single-byte character data up to 4 gigab).tes.
RAW(size) Raw binary data of length size( A maximurn size must be specified Maximum size is
20oo)
I-ONGRAW Raw binary dat of varibale length up to 2 gigabytes
BI.OB Binary data up to 4 gigabytes.
BFILE Binary data stored in an external file;up to 4 gigab1,1es.
24.12 Creating aTable Using SeL CREATE Command
You use the CR.EATE TABLE command to create a new database. With this command ycu speci!,
a name, type,
precision, and s6ale for each field in the database to be created. The form is as :
CREATETABLE table name
(column_name type(size),
column_name type(size),
.,''',,',
\.
) l
A The table rvill be created with the specified columns and the rows retrieyed by the select statement
inser-ted into it.
tr Constraint information is inherited from the selected table.
tr If all the columns in the SELECT statement have well-defined names, (that is, no expressions, arrd so
on), the column specifications may by omiffed.
B If column specifications are given, the number of columns must equal the number of items in the
SELECTlist"
t--
To create a table TEACIIER holding the Tno, Tname, Address, Salary Dept_no. DOJ the following
command has to be written ;
Example CREAIE1hBI-ETEACHER
(TNOCF{Aiii4),
TNAMECHAK2O),
TADDRESSCHAR"(2s),
SALARYNUMBER.(7,2),
DEPT_NO CrrAR(4).
DOJ DATE);
S,/hen you will be write the above conimand in SQL Plus and press Enter key, it wiil display a scrqen as
shown in Fig.24.4.
:Connected ta:
r0racle8i Per<orral Edition Release 8-1"5-B-0 - Froduction
,t!i.th the Jeira opiion
,PLISQL Belease 8-1.5-B.B - Production
Tabl€ created.
SQL> I
DESCRIBETEACHER;
at SQL Plus command prompt. The following screen F'ig. 24.5 vtill appear.
Note. Use CLEAR SCREEN command at SQL PLUS command promptto clearthe screen orgarbages.
516 Saraswati lnformatlcs practices (Xl)
S QL>
Null Indicates whether a column must contain data. If it indicates NOT NULL, we assume that the
column must contains data. The NOT NULL concept wiil be read in continuing sections.
Type Displays the datatypes for a column which we create using CREATE command"
The above querv is used to view tables, views. synonyrns and sequences owned by the user scott as
shown in Fig. 24.6.
BOHUS Tfi8L E
DEPT TftBLE
EhP TRSLE
SALGRRT}€ TABLE
-TEACHEfi TABLE
'sQt-> I
SQL> EDII
tlrote $ile afledt-buF
1 CSEfITE TfiBLE ]EAOHEN
,2 (IN0 CtisB{4) }toT HI,LL,
3 Tflflt'l€ cHfiR{2 0} ,
,4 TaDDBESS CHfr&(25),
se LflBY HUt'iBEs{7,t},
6 oEPT_ili CHfifi(4),
,F* DOJ D8IE)
'sqL>
Tabls [feated-
rsqL> sELECT coNSTBffIflT_NfiNE,
COIISTESIHI TYPE FROI,I USER_COHSIE&Ii{TS ;
,qONSTBRINT HNUE
J -
_--------- - I
iPI(-DTPT P
;Pl{_EtlP P
FI( DEPTHO n
sYs c60818 e
Example CREATETABLETEACHER
(TNO CHAR(4) CONSTRAINT T_NITMBER NOT NtrLL.
TNAMECHAR(20),
TADDRESSCHAR(25),
SALARYN[iMBER(7,2),
DEPI_NOCHAR.(4),
DOJDATE);
Where T NIJN'IBER is the name of the constraint. To see the constrants apply
the command,
SELECT CONSTRAINT_NAME, CONSTRAINT TYPE FROM USER_CONSTRAINTS;
From the above command, SQL PLUS will display the output screen as
shown in Fig.24.g.
CBHSTRfiIHT Hf,NE
'p( nrpr P
iPT ENP
.FI{ P
DEPINO R
iT HUH&ER f,
sql> I
Here, the column SALARY can accept value between 5000 and 10000 (including 5000 and 10000 also).
Note. Before using the Foreign Key constraint, create the parent table rvhere the tbreign key treated as primary
key.
The above example defines a table constraint unique that accepts values when Tno and Tname both are
unique. You can view the constraint defined for a specific table by looking at the USER-CONSTRAINTS data
dictionary table is as :
SELECT CONSTRAINT-NAME, CONSTRAINI-TYPE FROM USER_CONSTRAINTS ;
From the above command, SQL PLUS will display the output screen as shown in Fi9.24.9.
;iii r'.($j ; ,. - +
. .-r: r(ri
.:e .,i.:
,, :;.ii*. , " 'i -
SQL} SELEET GONSIBAINI CONSTREIflT TYPE FNOff USEB GOHSIRAIHTS;
iDONSTRAINI NR}IE
sYs_88s825 ?
PI( DEPT P
PI{ EHP P
rH DEPTIIO F
SYS C8883lr C
sYs c30635 c
svs-c0w36 P
svs 800837 U
TEECH DEPT R
9 rovrs 5elected.
isqL) I
CREATETABLETEACI{ER
(TNO CHAR(4) CONSTRAINT TEA-NO PRIMARY KEY NOT NI.]LL,
TNAMECHAR(2O),
TADDRESSCHAR(25),
sALARy NLMBER(7,2) CONSTRATNT T_SAL CHECK (SALARY BETWEEN 5000 AND 10000),
DEPT-NOCHAR(4),
DOJ DAIE DEFAUUI SYSDAIE.
522 Saraswati lnformatics practices (Xl)
CONSTRAINT TNO_TNAME LrNIQr.iE (TNO, TNAME),
CONSTRAINTTEACH-DEPTFOREIGNKEY@EPT_NO)REFERENCESDEPARIMENI@EPI_NO));
)ffi.6*i,iik
conEtr
i,.
ch
t,c W
e
, 2 FROH usef constraints ,!t
1I lrhEre tatle_nane = 'TERCHEfl.;
I
CONSTRAIHI TIfiI,IE
ISERRDH GONDITIO}I
rSYS_G80854 c
i"rH0" rs Nor HULL
T SRL c
:Sf,LERV BEII..EEH 5OOO A}II} lOOOO
TEf, NO P
THO Tt{AI'IE U
IEEEH DEPI R
l
.sqL) |
From the above command, SQL PLUS will display the output screen as shown in Fig.24.ll.
Starting with SQL 523
Tn r n{ c0LUHN_NnilE )
,svs c0085rt
,TNO
]TEACh DFPT
1DEPT H0
ITEE HO
lTNO
i
rTH0_TNnnE
,Ilt0
'IHO_TilE}E
)rNe n€
T SEL
SALNRV
6 rous selPcted.
SQL>
Note. You can add a NOT NULL constraint to an existing column by using the MODIFY clause of the ALTER
TABLE statement. You can define a NOT NULL constraint only in the table contains no rows.
24.19 Dropping a Constraint
To drop a constraint you can identify the name of the constraint from the USER-CONSTRAINTS and
USER_CONS_COLUMNS data dictionary. Then use the ALTER TABLE statement with the DROP clause. The
syntax rs :
524 Saraswati lnformatics Practices (X!)'
AUIERTABLEtable
DROP PRIMARY KEY I UNIQUE(cotumn)l GoNSTRAINT constraint
[GASCADE];
Where,
table is the name of the table
column is the name of the column affected by the constraint
constraint is the name of the constraint.
E.rample AUIERTABLETEACHER
DROP CONSTRAINT TEACHER CONS
If
you remove the PRIMARY KEY constraint on the DEPARTMENT table and then you must drop the
associated FOREIGN KEY consrraint on the TEACHER.DEPT NO column.
ALTER TABLEDEPARTMENT
DROP PRIMARY KEY CASCADE
The CASCADE option of the DROP clauses any dependent constraint also to be dropped.
ALTERTABLEtable
DISABLE CONSTRAINT constraint [CASCADE];
Where,
table is the name of the table
constraint is the name of the constraint.
The CASCADE clause disables dependent integrity constraints.
Example ALTERTABLETEACHER
DISABLE CONSTRAINT TEACHER CONS
24.21 Enabling Constraint
You can activate a constraint without dropping it. You can use the ALTER TABLE statement with the ENABLE
clause to enable a constraint, The syntax is :
AUIERTABLEtable
ENABLE CONSTRAINT constraint [CASCADE] ;
where
table is the name of the table
constraint is the name of the constraint.
The CASCADE clause disables dependent integrity constraints.
Example ALTERTABLE TEACHER
ENABLE CONSTRAINT TEACHER CONS
Note. lf you enable a constraint, that constraint applies to all the data in the table. All the data in the table must
fit the constraint. A TINIQUE or PRIMARY KEY index is automatically created ifyou enable a UNIeUE key or
PRIMARY KEY consffainr.
24.22 AlterTable
This command is used to change the table. We can add new colurnn, change the datatype of column
or drop any
constraint using alter command.
Starting with SQL 525
6 Yol,ti selected"
SqL> TRELE TERCHER
AOD (PH H0 nunberdT,8));
t 2 'LTEF
.Table altered-
After adding a column, you can check the structure. For example, to display the TEACHER table's structure,
wnte
DESCRtsETEACHER:
at SQL Plus command prompt. The following screen Fig. 24.13 will appear.
:,ii.i
isQL> DES8RIBE
HailP NuIl? Type
SQL>
i,:1. I
Example AIjIERTABLETEACIIER
MODIFY (PH_NO number(8,0)) ;
526 Saraswati lnformatics practices (Xl)
Whenyou seethe structure of modified column withDESCRIBE TEACIIERcommand atSeL plus command
prompt, the following screen Fig. 24.l4willappear.
lLl \\
,Taole altpred.
SQL> DESCRIBE TENCilER;
: Name ilul1? Tupe
TNO
NIT lnrLL c[n8({)
r IHftl{E cHcR (2 0)
1 TEDDRESS cHnR(25 )
SAL6BV iflrH8ERt7.2)
, DEPT-HO cHftB( 4)
00J DNTE
PH I{O MJNBER (8)
sql> I
tr You may not change a column containing null from NULL to Nor NULL.
tr You may not add a new column that is NOT NULL.
B You may not decrease the size of column.
tr You may no[ use the MoDIFy option to define constraints on a column .
DROP TABLEtable_name;
Example DROPTABLETEACHER;
But before dropping a table it is necessary that all its rows must be deleted. A table with rows cannot be
dropped. We can delete the rows of a table using delete command. We will discuss the DELETE command in
DML commands.
24.24 Data Manipulation Language (DML)
So, far we discussed number of DDL commands in last section. These commands are more important to create
table structure, modi$, table structure, etc. Other than these, definition language statements and those used to
manipulate data inthe tables are grouped into a class called datamanipulation language @ML). Datamanipulation
capabilities allow one to retrieve and modif, constants ofthe database. These DML commands are affected on
the records either to insert, modif,, delete, etc.
table_name specifies the name of the table to which a record will be appended. The VALUE clause contains a
list of expression (<expr1>[, <expr2>[, ...]]) that are evaluated, and the res,rlting value is stored in the field.
Before inserting create a new table called TEACHER with the following structure :
CREATETABLETEACT{ER
(TNO CHAR(4) PRTMARY r(EY NOT NULL,
TNAMECHAR(2o),
TADDRESSCHAR(25),
SALARYNUMBER(7,2),
DEPT_NOCHAR(4),
DCiDATE);
It is pcssible to insert a new row with values in each column, in which case the column list is not required.
It is recommended that the column name is always specified. If the name is not specified, your software will
require modification whenever the table definition is altered. So, to insert a new teacher's information, enter:
Example INSERTINTOTEACHER
VALUES('T0 l',Rakesh Sharma', '245-Malviya Nagar', 5600, 'D05', '12-Dec-200 l')
OR
INSERTINTOTEACHER
(TNO, TNAME, TADDRESS, SALARY DEPT_NO, DOI)
VALUES('TO l','Rakesh Sharm a' ,'245-Malviya Nagar', 5600, 'D05', '12-Dec-2001')
Note. Character strings and date values are enclosed in single quotation marks. Character values are case
sensitive and date values are format sensitive. Default date format is DD-MON-YY.
528 Saraswati lnformatics practices (Xt)
Always remember the order of values matches the order of columns in the create table command
of
student. So, writing the column name is optional. When you will execute the above
SeL plus statement, the
following Fig .24.16wlllappear in front of you.
,SQL>
'.2 ufiLuEs(,T01,!'Rakesh '24s-italuiya Nagar., F600, '12-Dec-2OBl ' );
It .o* creatFd -
.SQL> I
DELETEFROMtable name
IWHERE <condition>l;
The WHERE clause is optional. You can use where to delete a particular or the
rows satisfied the condition
given in WHERE clause. To remove all the rows of a table the form is
as :
Solved Exercises
Ql. What is DDL?
Ans. Those commands, which are used to create and rnaintain database, are grouped into the class called data
definition language (DDL).
Q2. What is DML?
Ans. Definition language statements and those used to manipulate data in the tables are grouped into a class
called data manipulation language(DML).
Q3. Write some features of SQL.
Ans. The SQL commands are dealt with three issues
-Recovery and concurrency. Concurrency is concerned with the manner in which multiple users
operate upon the database. Each user can either reflect the updates ofa transaction or can cancel
all the updates ofa transaction.
Security. The security can be maintained by view mechanism. A view is used to hide sensitive
information and defines only part of a table which should be visible.
Integrity constraints. Integrity constraints are enforced by the system. For example , one can
specif that an attribute of a relation will not take on null values.
Q4. What are the database objects are available in SQL?
Ans. The following are the Database objects available in SQL :
Table. A table is used to store the data.
View. A view is the temporary table created using a Original Table. You can say it is a subset of one
or more table.
Sequence. Sequences are used to generate the Primary Key values.
- lndex. They are used to improve ttre performance of some queries.
Synonym. They give altemative names to objects.
Q5. Write the rules to name an objects.
Ans. The following are the rules to name an objects :
- The object must be maximum 30 characters long(except the database names which are limited to 8
characters.
- The object name should not contain the quotation mark.
- The name must start with leffer.
- The use of $ and # is discouraged in the object name.
- A name must not be a reserved word.
Q6. Which command is used to create a table in SQL ?
Ans. CREAIETABLE
Q7. Which command is used to list the structure of a table ?
Ans. DESCNBE.
Q8. How will display the tables owned by the users ?
Ans. SELECT * FROM user tables;
Q9. What is integrity constraints ? Describe two types of consfraints.
Ans. SQL allows integrity constraints to be defined for tables and columns to enforce certain rules, either
within a table or between tables.
Constraints are used to enforce rules at table level whenever row is inserted , updated or deleted from the
table. The constraints are used to prevent invalid data entry into teoles. Constraints can be defined at
one of two levels :
- Column level. Refrences to a single column; can be defined any type of integrity constraint.
-Table level. References one or more columns and is defined separately from the dehnitions of the
columns in the table, can be dfined any constraints except NOT NULL.
Ql 0. What is the difference between UNIQUE and PRIMARY KEY ?
530 Saragwati lnformatics Practices (Xl)
Ans. A table can have any number of UNIQUE constraint but only one PRIMARY KEY per table is allowed.
Qll. How will you drop a constraint from a table ?
Ans. To drop a constraint you can identifo the name of the constraint from the USER CONSTRAINTS and
USER_CONS_COLUMNS data dictionary. Then use the ALTER TABLE statement with the DROP
clause. The sl.ntax is :
ALIERTABLEtable
DROP PRIMARY KEY I UNIQUE(column)l CONSTRAINT constraint [CASCADE];
Ql2. What is the purpose of ALTER TABLE command ?
Ans. This command is used to change the table. We can add new column, change the datatype of column
or drop any constraint using alter command.
Q13. How will you drop a column from a table ?
Ans. To remove a column which is no longer required for your table you can use an ALTER TABLE statement
with the DROP COLUMN clause. This feature is available from Oracle8i onward.
Ql4. How will you delete all the rows of a table?
Ans. This command is used to delete rows of a table. The delete command deletes the entire row not a specific
column. The form is as :
DELETEFROMtable name
[WHERE <condition>];
Ql5. Write SQL commands to create the table HOSPITAL with follwing specification :
CREATETABLEHOSPITAL
(PNO Numbe(4,0) PRIMARYKE!
NAME Char(20) UMQLJE,
AGE Number(2,O),
Department char(I5) DEFAULT'OpD',
DATEOFADM Date DEFALILT SYSDATE,
CHARGES Numbe(7,2) CFIECKcharges> 100,
SEX Cha(l));
(D INSERTINTOHOSPITAL
VALUES( l, 'Arprit', 62, 'Surgery', '21-Jan- 1998', 'M');
Similarly, You can insert the rest of the values into the table.
(i,) DESCRIBE HOSPTTAL;
(rrr) SELECT constraint name, column name
FROM user cons columns
Where table name : "HOSPITAL"
(,v) ALTER TABLE HOSPITAL
ADD CONSTRAINT PATIENT CONS
FOREIGN KEY(DEPARTMENT) REFEREI.iCES DEPT(DEPT_No);
(v) AUIER TABLE HOSPITAL
DISABLE CONSTRAINT PATIENT CONS
(ur) ALIER 1ABLE HOSPITAL
ENABLE CONSTRAINT PATIENT CONS
(vii) ALIERTABLE HOSPITAL
DROP CONSTRAINT PATIENT CONS
(vlil) AUIERTABLE HOSPITAL
ADD (ADDRESS Char(2O));
(n) ALIERTABLE HOSPITAL
MODIFY(ADDRESS Cha(2s));
(x) ALTER TABLE HOSPITAL
DROPCOLUMN ADDRESS;
(xr) DELETE FROM HOSPITAL;
Ql6. Create database named as EMPLOYEE using SQL command of following structure :
l0 ACCOLINTING DELHI
N RESEARCH KOLKOTA
30 SALES MUMBAI
4 OPERATIONS BANGALORE
Ans. The command used to create a EMPLOYEE table is :
CREATETABLEEMPLOYEE
(EMPNO Numbe(4,0)NOTNULL PRIMARY KEY
ENAIIE Yarchw2(2}),
JOB Varchar2(9),
MGR Number(4),
HIREDATE Date,
SAL Numbe(7,2),
COMM Number(7,2),
DEPTNO Numbe(2) Constraint FKDEPTNO REFERENCES DEPTM(DEPTNO));
Now, inseft the values with the help of insert into command :
hiSERTINTOEMPLOYEE
VALUES(7369,'SunitaSharma','CLERK', 7902,'17-DEC-1980', 2800, NULL,20);
Similarly insert rest of the records in the EMPLOYEE table.
The command used to create a DEPTM table is :
CREAIETABLEDEPTM
(DEPTNO Numbe(2,0) NOTNULLPRIMARYKEY
DNAME Varchar2(14),
t0c Varchar2(13) );
Now, inserl the values with the help of inserl into command :
INSERTINTODEPTM
VALUES( I 0,'ACCOUNTING"'DELHI');
Similarly insert rest ofthe values in the DEPARTMENT table.
Ql7. What is the purpose of DROP TABLE ?
Ans. This command physically delete the table but the condition from dropping a table is that it must be an
empty table.
Review Questions
l. NamethreeDDLcommand.
2. Name some DML command.
3. Summarize rules for SQL commands.
4. Write the steps to start SQL.
5. Describe the data types available in SQI-.
6. How will you execute the SQL statements ?
7. Describe the syntax of CREATE TABLE command ?
8. What is Oracle Data Dictionary ?
9. Describe the column constraints.
10. How will you view the table constraints ?
11. How will you view the columns name along with the constraints.
12. What is the difference between Disable and Enable the constraints ?
13. What is the difference between ADD and MODIFY clause in the ALTER TABLE ?
14. What are the four changes not allowed in the ALTER TABLE ?
15. What is the purpose of DROP TABLE and INSERT INTO command in SQL ?.
16. Name some DCL commands.
17. Create database named as MEMBER using SQL command of following structure :
FieldName FieldType Width DecimalDescription
mem code Character 3 Member code
mem name Character 30 Member name
mem add Character 50 Member address
/ memlhone Character 7 Member contact number
, no of bk Numeric 3 Number of books stock
no of iss Numeric 3 Number of books issued
(,) Add new field in the table called F_no_mem ofNumeric type and width is 3.
(lr) Insert at least 6 records in the table.
(iii) Add the following constraints :
PRIMARY KEY and NOT NULL on the field mem code
UNIQUE on the field mem_phone
CHECKonthe field no of bkas<3
Default on no of iss as 0
534 Saraswati lnformatics Practices (Xl)
FieldType
FieldName Width Dec Constraint
NO Number 3 Primarykey
NAME Character n
SAI-ARY Number 7 2 Default:5000
AREA Character l0 Check In A, B or C
AGE Number 3
GMDE Character 3 NOTNULL
DEF| Character -5
25.1 lntroduction
ln the last chapter you learnt how to create the table and then how we inseft the value into the table. We use the
DDL and DML commands like, CREATE, INSERT, ALTER, DROR DELETE, etc. This chapter introduces you
how to retrieve information from a table.
tr A keyyey6ly"fers to an individual SQL statement, i.e., SELECT and FROM are keywords.
tr A clattseis a part of a SQL stateilent, i. e., SELECT tno, tname, .... is a clause.
tr A statement is a combination of fivo or more clauses, l. e , SELECT * FROM teacher is a SQL statement.
(537)
SELECTXFROMTEACFIER;
in SQL PLUS as shown in Fig. 25.1. When you prcss Eenter key, SQL PLUS will display the result as shown in
Fig.2-5.1.
15 roros selected-
SQL> I
The above statement retrieves the TNo and TNAME of'all the teachers from the table TEACHER
as
.
l"teh l !,+ l:.: a'. ,?.. t6 '-? :h
I HE}IE THI)
'Ehr,lana Lar*ba
.Jagjit Tl ra
Slngh Tis
115 ,'ourr serected.
.SQL>
I
tr A column name
D A comparison operator
tr A column name, constant or list of values.
The WHERE ciause goes through the entire table one row at a time and examines
the condition is true or false.
each row to determine if
Example SELECT TNAME. SALARY
FROMTEAC}IER
WHERESALARY= 10000;
From the above command, SQL PLUS will display the TNAME and SALARy rorvs
whose SALARy is
equal to 10000 as shown in Fig. 25.4.
gdt
SELET]T
FROH
IdHERE
Suppose you want tcr display the naine and salary of the teachers getting saiary more than 12000. Then the
statemet will be :
Seetth s,]i4
STL SELECI IHFI,IE , SALAS f J^t
2 r80tt TEsCHER
tilHEBE SNLRBY > 106BO;
)
TN*TIE S*L*RY
6 rours seleftpd-
s{L> I
Fig. 25.5 Using WHEBE clause wiih relational operator in TEACHER table.
D Boolean Operators. Boolean operators are the one which are either true or false. They are used to
combine one or more conditions. The list of boolean operators with the meaning is listed below:
Operator Meaning
AND Takes two Booiean arguments as input and return true if both the input are true.
OR Takes two Boolean arguments as input and return true if any either is true.
NOT Tatrres a single Boolearr argument and changes its value from false to true or from
true to false.
Example SELECT TNO.TNAME
FROM TEAC}IER
WHERE (DEPI_NO='D03' AND SALARY> 10000)
This example displayed the
TNO and TNAME of the teacher fde fdfl !ea;h fuibri Eelg
sQL> SILEST TND, THRt'lE
whose DEPT NO is D03 and 2 FROI4 TIACIIEB
SALARY more than 10000 as 3 r,,HEnE (DIPT_Ho = ',D63', fiHD SALftBY > 18000);
shown in Fi5.25.6. THO TNNfiE
SQL> I
Fig. 25.6 Using WIIERE clause with boolean operator AND in TEACHER table.
542 Saraswati Informatics Practices (Xl)
T}IO TNfi}.IE
SQL>
";:__. *,.;iti
sQL) SELEEI
2 FB0tl TENCHER
I+H ERE (NOI SRLARV
1g roes selected.
sQr> I
Fig.25.B Using WHERE clause with boolean operator NOT in TEACHER table.
The above example displayed the TNO and TNAME except Rakesh Shanna from TEACHER table as
shown in Fig. 25.9.
$',$ilt,.iSewrn delr, .
sql> sELErlI TNO, TNAI4E
2 Fff0l,l TEECHET
3 IJ}IEBE tl0l Tilel4E = 'Rakesh Sharna' 0B TH0HE = 'Jugal l'littal';
tilo rileilE
I{f2 Juga} Hittal
I03 Sharni),a Kaur
T 8t4 Sandeep [aushik
Tt!5 SangePta Uats
T06 Rariesh Kumar
I6t Shrao Rrora
I tl8 Shiu 0,r!
TSg Uiuek fial,at
11 0 &ajest uerna
111 Ashdk Singhal
I12 Ch€tan Shukla
113 Beena l,lehta
T14 Ehurana Linba
T1s Jagjit singh
14 rDrqs selPcted.
SQL>
dJ
Fig. 25.9 Using WHERE clause with boolean operator OR in TEACHER table.
You could obtain another result with this command :
In the above example parentheses indicate that everything inside it will be evaluated first and treated as a
single expression by everything outside them.
tl l
sQr> SELECT *
2 FROI4 TERGHER
3 II}IERE SNLRBY IS NULL;
TNt) IHNI{E IA}DBESS SBLRRY OEPT DOJ
tl i
.i#..--
Fig.25.11 Rows whose SALARY is NULL.
You could obtain another result with this cortmand :
$EI. ETI
F80tl TESEHEft;
SELSRV
3{08
45 EE
55sS
56 80
6508
ls86
81 88
"t it0BB
'i2*00
1 3&A6
I 4800
15 006
28068
5QL>
EJIB dfil.uS""31ri,
sqL SELECT TNO, THOHE
2 FROII TEfiCHEH
I,'HENE SRLRBY BET!'EEN i0006 RHD 'r5660;
TNO YMlfif
6 rotrs selected-
s0L>
{H0 THf,l'lE
tr %o(percent) - For matching any substring. The 7o stands for any number of characters.
tr _ (underscore) - For matching fixed number ofcharacter. The - stands for any single character.
Ihe LIKE clause is used to select rows which are matching wiidcards pattern. Note that the pattems are
case sensitive i.e., the upper case letters do not match lower case letters. The form is as :
The above example displayed the TNO and TNAME of all the teachers whose name starts with the
alphabet R as shown in Fig. 25.15.
isqu I
The above statement displayed the name of all the teachers whose name has an
"a" as the second character as
EM lgiom Edr
SQL> SELECI tnaoE fiS nan€, salarg nS sa]
2 FRON TEACIER;
}IANE
Rakash Sftarma 56 S0
JugBl HittaL 1 2008
Snarmila l(aur 2 UBo0
Sandeep Kaushik 15600
Sangeeta Uats 89 0g
Rafiesh Humar 1 q000
Shyan firora 12 000
Shiu orn 13 900
,Uiuek Ra$at 1 0000
,Sajest Uerna 56 00
.f,shok singhal 7g 00
Chgten Shukla 3rr0g
fteena l,tahta 55 00
Bhll,tna Lamba +500
Jagjir Singh 65 00
Dinesh GoPl
'Lokesh Bathore
17 ro(,rs selected,
,sQL> I
JlJ
Fig.25.18 Using colurnn alias with SELECT.
Example SELECT TNAME "Teacher Name", SALARY* 12 "Annual Salary"
FROM TEACHER;
The above examples display the name anC the annual salary, of all the employees. Beacuse Teacher Name
and Annual Salary contains spaces, it has been enclosed irr double quotation marks. Notice that the column
heading in the output is exactly the same as the column alias as shown in Fig.25.I9.
25.5 Using Concatenation Operator
\bu can link columns to other columns, arithmetic expressions or constant values to create a character expression
by using the concatenation operator (ll). Columns on either side of the operator are combined to make a single
output column.
550 Saraswati !nformatics Practices (Xl)
Teachers
The above example changes the name Rajest Verma with the name Rajesh Verma. To see the changes, use
the SELECTcommand as
TNO TNAI,IE
'sQr-> I
The above example set the SALARY of all the teahers as an incrementing value of Rs. 200 with each
existing salary. So to display the new vlaues, use the command,
SELECT TNAME AS name. SALARY sal
FROM TEACHER:
as shown illFig.25.22.If you compareFig.25.22 with Fig. 25.18, then you will find the changes in SALARY
column with an addition value Rs.200.
rF.te g{it' 5e,xt*r,.,4iiyC,
SqL> UPDNTE IEOCHER
z SET SALAfiY - SALART + 2gD;
17 roau5 ufidatpd.
SQL> SELECT TNAI{E AS Dame, SeLpBv sal
Z FBOI{
TEftDHEft;
Example T PDATETEACffiR
SET TNAME = 'John Ray' , DEPT_ NO = ,D03'
WHERE TNA.ME ='Shiv Om';
The abovqexample changes the name Shiv Om with the name John Ray and dept column with D03 whose
name become "Shiv Om". To see the changes, use the SELECT command
1 rord updated-
SQL> SELEUT INO, IT{EHE, DEPT HO FBOI4 IEACHER
2 +,]iERE THAttE = John Rai,;
T1IO TTIRKE DEPT
sqL>
17 rous selected.
SQL> [
jl J
19 rovrs selected.
records will be done through DEPT-NO and if the iDEPI DOJ su14( 56LARV )
DEPT_NO's are same then, the records are further grouped
001 g6-JUH-00 26260
using DOJ. As shown in Fi g.25.35, the DEPT-NO and DOJ D61 l2-0CT-01 1 O2BB
columns are grouped only 17 records because. there are two 002 15-RUG-98 12? o0
;ig2 03-JUL-99
records whose DEPT NO and DOJ are same as shown in 092 -11-AUG-99 775$
Fig.25.34. ,002 13-JUN-01 36 00
003 03-JUL-97 1t 2gg
iD03 17-JUL-99
1D0A 18-JIJL-00 1 140s
iD63 08-AUG-{tl 15209
:D03 22-SEP-01 132 60
D0I{ 11-JUL-98 6?80
D0rr 12-ocl-00
tlstr 07-N0u-00 5860
D0t 16-JUL-01 9tr80
D0s 29-FEB-00 91 S0
D65 12-DEC..01 58 00
SQL>
nuG (sALnRY )
FBB'I TEf,CHEB
|*IERE 6UG(SnrABV) > 5006
GSOUP BV DEPI-IM;
I,HEBE fiUtr(SRLRBV) ) 5000
*
Enq0R at line 3:
0BR-00934: group function is not alloroed here
sQL>
.akd - -
Fig.25.37 lllegal queries using group function.
tr Excluding Group results. In the same way that you use the WHERE clause to restrict the rows that
you select, you use the HAVING clause to restrict groups. To find the maximum salarJ of each
department, but show only the departments that have a maximum salary' of more than 10000, you need
to do the lollowing :
SQL SELECT Statement 559
. Find the average salary for each department by grouping by department number.
o Restrict the groups to those departments with a maximum salary greater than 10000.
SELECT DEP[_NO, MAX(SALARY)
FROMTEACTMR
GROUPBYDEPT NO
HAVING MAX(SALARY) > 1 OOOO;
When the above command executed, it will display the department number with there respecrive maximum
salaries as shown in Fig. 25.38.
20200
122US
15290
You can include one group function in E$e €& $eatcfr Qrtions U4
another, it is called as nesting of group SQL> SELECT HRX(CUG(SRLnRY) )
functions. Group functions can be nested to 2 FRB]'I TEhCHER
a GROUP BV DEPT_NO;
r4f,lt(suB(solAsY) )
E x amp le SELECT MAX(AVG(SALAR!)
FROM TEACMR 152S0
, GROUPBYDEPT-NO;
sal> I
Fig. 25.40 Becords are arranged in ascending order wise of TNAME column.
If you want to arrange the data in descending order then use DESC clause with ORDER BY clause. The
commandwillbe:
Example SELECT xFROIVI TEACIDRORDERBY TNAME DESC;
$r SarSh g@
sqL> SELEGT *
2 FROTI IEACI{ER
OEDEB EY I NN]IE
tr ORDER BY with multiple columns. You can sort query results by more than one column. The sort
limit is the number of columns in the given table. In the ORDER By clause, specify the columns and
separate the column names using commas. If you want to reverse the order of a column, specify DESC
after its name.
Example SELECT *
FROM TEACHER
ORDER BY TNAME DESC,'TADDRESS;
rsQL>
ll ORDER BY with column alias. You can use a column alias in the ORDER BY clause.
.tttt Sctrort
,sQL) SELECT TNO, THRl,lE,
j 2 FRril,l IERCI{EB
3 ORDER B? finnual;
:TNO TNONE TRDDRESS AIINUAT
j
:s0L>
SILAR}
THRME
,SOLERYIS' SfiLfiEY
)s8L)
Solved Exercises
Q1. What is query ?
Ans. A query is a command you give your database program that tells it to produce specific iuformation from
the tables in its memory.
Q2. What is the purpose of WHERE clause ?
Ans. The WHERE clause of the SELECT command allows you to define a condition that can be either true or
false for any row of the table. The WHERE clause specifies the search condition used to determine the
data that will appear in the result table.
Q3. What is the purpose of DISTINCT clause ?
Ars. The DISTINCT is useful to remove the duplicate rows in the output. The result obtained in the query
using DISTINCT clause do not contain duplicate rows.
Q4. What is column alias ?
Ans. When displaying the result of query SQL *PLUS normally uses the name of the selected column as the
column heading. In many cases, this heading may not be descriptive and hence is difficult to understand.
You can change a column heading by using a column alias.
Specify the alias after the column in the SELECT list using a space as a separator. By default, alias
headings appear in uppercase. Ifthe alias contains spaces, special characters (such as # or $), or is case
sensitive, enclose the alias in double quotation marks (" ").
Q5. What is the use of UPDAIE command ?
Ans. If you need to change the value of the table, you can do it using LIPDATE command. The UPDAIE
command is used to update rows and we can also use WHERE clause with UPDATE command.
564 Saraswati lnformatics practices (Xt)
Q6. What are group functions ?
Ans' The aggregate functions are group functions. They retum result b-tsed on groups of rows, rather than
one result per row as returned by single row functions. By default
all the rows in a table are treated as one
group. The group functions are :
- AVGO
- couNro
MAxo
MrNo
- suMo
Q7. What is the function of HAVING clause ?
Ans. The HAVING clause restricts grouped rows that appear in the result
table. Groups are specified with the
GROUP BY clause. You can combine search conditions with the AND/OR
NOT operation.
Q8. What is the function of ORDER By ?
Ans. The ORDER BY clause determines the order of rows in the result
tabie. Data is place<J in the rows in
ascending (ASC, the default) order or descending (DESC) order. The
orcler ofthe columns in the result
table is determined by the <order item> values.
Qe. Write SQL commands for (a) to (fl andwrites the outputs for (g) on the basis of table HOSpITAL.
TABLE:HOSPITAL
No. Name Age Department Dateofadm Charges Sex
I Arprit 62 Surgery 2t-Jan-98 300 M
2 Zarina 2. ENT I2-Dec-97 250 F
3 Kareem 32 Orthopaedic l9-,-ieb-98 2N M
4 Arun 12 Surgery ll-Jan-98 300 M
5 Zubin 30 ENT l2-Jan-98 250 M
6 Ketaki t6 ENT 24-Feb-98 250 F
7 Ankita D Cardiology 20-Feb-98 800 F
8 Zareen 45 Gynaecology 22-Feb-98 300 F
9 Kush t9 Cardiology l3-jan-98 g00 M
l0 "Shilpa Nuclear Medicine 2l-Feb-98 400 F
(fl To insert a new row in the HoSpITAL table with the foilowing
data :
I l,'Aftab', 24,'Surgery','25-Feb-9g', 300,'M'
(g) Give the output of following SeL statements:
TABLE: HOSPITAI.
No" Name Age Department Dateofadm Charges Sex
1 Sandeep 65 Surgery 23-Feb-98 300 M
2 Ravina 24 Orthopaedic 20-Jan-98 2N F
3 Karan 45 Orthopaedic l9-Feb-98 2N M
4 Tarun 12 Surgery 0l-Jan-98 300 M
5 Zsbin K EN'f l2-Jan-98 250 M
6 Ketaki 16 ENT 24-FeU98 300 F
7 Ankita D Cardiology 20-Feb-98 800 F
8 Zareen 45 Gynaecology 22-Feb-98 300 F
9 Kush 19 Cardiology l3-Jan-98 800 M
10 Shailya 3l Nuclear Medicine l9-Feb-98 400 M
(a) To show all information about the patients of cardiology department.
(b) To list the narne of female patients who are in orthopaedic department.
(c) To list names of all patients with their date of admission in ascending order.
(d) The display Patient's Name, charges, age for male patients only.
(e) To count the number of patients with age>20.
(fi To insert a new row in the HOSPITAL table with the following data :
1 l,'Mustafa', 37, 'ENT', '25-Feb-98', 250, 'N1'
TABLE:TEACHER
No. Name Age Depaftment Dateofioin Salary Sex
I Jugal y Computer l0-lan-97 l2N0 M
2 Shannila 3l History 24-Mar-98 20000 F
3 Sandeep 32 Maths l2-Dec-96 30000 M
4 Sangeeta 35 History 01-Jul-99 40000 F
5 Rakesh 42 Mai..irs 05-Sep-97 25000 M
6 Shyam 50 History 27-Jun-98 30000 M
SQL SELECT Statement 567
TABLE:CLUB
COACH.ID COACHNAME AGE SPORTS DATEOFAPP PAY SEX
I KUKREJA 35 KARATE 2i-Mart996 1000 M
2 RAVINA U KARATE 20-lan-1998 1200 F
3 KARAN Y SQUASH l9-Feb-1998 2W M
4 TARUN 33 BASKETBALL 0l-Jan-1998 1500 M
5 ZUBIN % SWIMMING 12-Jan-1998 750 M
6 KETAKI 36 SWIIUN4ING 24-Feb-1998 800 F
7 ANKITA 39 SQUASH 20-Feb-1998 22Cf. F
8 ZAREEN 37 KARATE 22-Feb-1998 ll00 F
9 KUSH 4l SWIMMING l3-Jan-1998 900 M
10 SHAILYA 37 BASKETBALL t9-Feb.l998 t7Cf M
(a) To show all information about the swimming coaches in the club.
(b) To list names of all coaches with their date of appointrrent (DATOFAPP) in descending order.
(c) To display a report, showing coach name, pay, age and bonus ( I 5% of pay) for atl the coaches.
(4 To inseft a new row in the CLUB table with the foilowing data :
I l, 'Raiiv', 40, 'l lockey'.'27-May-2000', 2000,'M'
568 Saraswati lnformatics Practices (Xl)
(e) Give the output of following SQL statements :
(I) SELECT COUNT (DISTINCT SPORTS ) FROM CLUB;
(,i) SELECT MrN(AGE) FROM CLUB WHERE SEX:'F ;
(llD SELECT AVG(pAy) FROM CLUB WHERE SpORTS :'KAR.AIE';
(,r.,) SELECT SUM(PAY) FROM CLUB WHERE DAIEOFAPP > '3 1-Jan-98';
Ans. (a) SELECT *FROMCL.UBWHERE SPORT'S:'SWIVIMING';
(b) SELECT COACHNAME FROM CLUB ORDERBY DATOFAPP DESC;
(c) SELECT COACHNAN,IE, PAY AGE, Pay * l5i 100 FROMCLUB;
(d INSERT fNTO CLUB \ALUES (l l,'Rajiv',40,,Hockey',,27-Ma1-2000',2000,'M');
(e) (D4(ii)34 (i,r) i 100 (rv) 7s00
Ql4. Write SQL commands for (a) to (@ and write the outputs for (e) and (fl on the basis oftables CRADUATE
and GUIDE:
TABLE:GRADUATE
SNO NAME STIPEND SUBIECT A\TRAGE DIV
1 KARAN 4OO PHYSICS 68 I
2 DIVAKAR 450 COMPUTERSC 68. 1
TABLE:EMPIOYEE
SNO N.AME BASIC DEPARTMENT DATEOMPP AGE SEX
I KARAN SOOO PERSONNEL 2'7-Mar-9'7 35 M
2 DIVAI(AR 95OO COMPUTER 20-Jan-98 Y M
3 DI\TTA 73OO ACCOUNTS l9-Feb-97 Y F
4 ARLIN 83-50 PERSONNEL 01-Jan-95 33 M
5 SABINA 95OO ACCOUNTS l2-Jan-96 36 F
5 JO}IN 14ffi FINANCE 24-Feb-97 36 M
7 ROBEKT 8250 PERSONNEI- 20-Feb-97 39 IvI
(i) Display the names of the students who are getting a grade 'C' in either GAME or SUPW.
(ii) Display the nurnber of students getting grade 'A' in Cricket.
(ili) Display the different games offered in the school.
(lv) Display the SUPW taken up by the students, whose name starts with 'A'.
(v) Add a ne\\,column natned'Marks'.
570 Saraswati lnformatics Practices (Xl)
(rri) Assign
a value 200 tbr Nlarks for all those who are getting grade 'B' or above in GANIE
(vll)
Arrange the whole table in the alphabetical order of SUpW
Ans. (l) SELECT' nameFROM studerrt WI IERE grade--'C' ORgrade1 ='C';
(ii) SELECT COUN-l'(grade) FROM stndent WHERE grade: 'A' AND game -'Cricket';
(li) SEI-ECT DIS'f INCT game FROM student:
(A') SEI,ECT suprv FROM studenl WIIERE narne LIKE'A%o';
(r) AI-I'EIR'IABLE student ADD (nrarl<s NLJMBER(3))r
(r,i) UPDATE student SET rnarks:200 WHERE grade IN ('A', 'B');
(vil) SIiLECT * FROM student ORDER BY supw;
Ql7. Write SQL. cornmands for (i) to (vli) on the basis of the table SPORTS.
TABLE: SPORTS
Student No. Class Name Gamel Grade Gamc? Grade
107 Sarneer Cricket B Swimming A
1l 8 Sujit Tennis A Skating C
t27 Kamal Swimming B Football B
137 Veena Tennis C Tennis A
149 Arclrana Basketball A Cricket A
l,s l0 Arpit Cricket A Athletics C
(i) Displal'the names of the studenls who have grade'C' in eitherGamel or Game2 or both.
(li) Display,the nurrbel olstudenrs getting grade 'A' in Cricket.
(lli) Dispiay the names of the students who have same game for both Gamel and Game2.
(n') Displal, the games taken up by the students, whose name starts with 'A .
(r) Add a new column named "Marks".
(t'l) Assign a value 200 for Marks for all those who are getting grade 'B' or grade 'A' in both
Gamel and Game2.
(i'ii)Arrange the whole table in the alphabetical order ofName.
Ans. (r) Slllt;C f NAME FROM SPORTS WHERE GRADE:'C'ORGRADEI :'C' ;
(il) SEI-EC I COUN T(*) FRONI sporrs
WHERE (game l-'Cricket'AND grade:'A') OR (game2:'Cricket'AND gradel :'A');
(lil) SEI-|CT narne FRONI sporrs RIHERE samel:oame2:
(i, SELITCT game I , game2 FROIvI sports \\,HERE name LIKE ,AoZ';
(t) AUIER TABI-E SPORTS ADD (MARKS T.NUMBER(3)):
(r,i) UPDAl-E sporls SE'f marks -= 200
WHERE grade -'A' OR grade =.'B' OR gradel :'A' OR gradel :,B,;
(r'ii) SELL:CT' * F ROM soorts ORDE,R IIY name;
Ql8. Civen the following Lab re lations : Write SQL command for questions (a) to (fl and the output for (g).
TABLE: Lab
No ltemName CostPerltem Quantity DateofPurchase Warranty Operational
I 60000
Conrputer I 2l.May-96 11
2 Printer l5m0 3 21-May-97 42
3 Seanner 18000 I 29-Aug.9B 3l
4 eamera 21000 2 13.,tun-96 t2
5 l-lnb 8000 I 31"Ou.99 21
6 UPS 5000 5 21.May"96 14
7 Pioltet 25000 2 1l=Jan"2000 22
SOL SELECT Statement 571
Sunita SharmaCLERK
Ashok SinghalSALESMAN
Rohit RanaSALESMAN
Jyoti LambaMANAGER
Martin S.SALESMAN
Binod GoeIMANAGER
Chetan GuptaMANAGER
Sudhir RawatANALYST
Kavita ShannaPRESIDENT
Tushar TiwaTiSAL,ESMAN
Anand RathiCLERK
Jagdeep RanaCLERI(
Sumit VatsANALYST
SOL SELECT Staternent 575
Manoj l(aushikcLERK
(l,i) ENAME
Martin S.
Kavita Sharma
Jagdeep Rana
Manoj Kaushik
(n) ENAME MGR
Kavita Sharma
(u) AVG(SAL) MAX(SAL) MrN(SAL) SUM(SAL)
4t4.28571
(vii) DEPTNO AVG(SAL)
l0 4250
20 4475
30 s066.6667
(viii) COUNT(*)
5
(,x) COLINT(COMM)
5
(r') DEPTNo MAX(SAL)
l0 5300
20 6100
30 6250
Review Questions
l. What is the purpose ofthe SELECT statement ?
2. What are the relational operator available in SQL ?
3. What are the boolean operator available in SQL ?
4. What is the purpose of IS NULL ?
5. What is the purpose of BETWEEN, IN and LIKE clause ?
6, What is th- purpose of concatenation operator ?
7. Write the purpose and syntax of all the group functions.
8. What is the restriction with the DISTINCT clause ?
8. Can we use WHERE clause with the GROUP BY ?
8, How will you format your query ?
9. Create a database named as MEMBER using SQL command of following structure:
FieldName FieldTtpe Width Decimal Description
RELATION:EMPI_.0YEE
NO NAME SALARY AREA rcE GRADE DEPT
I KESHARSTORE40000 'I\EST 45 C CIVIL
2 K]RTI ARTS 35OOO SOUTH 38 A ELEC
3 KRIPPLE 6OOOO NORTH 9 B CML
4 ARYAN STALL 38OOO NORTH D B CML
5 SAMSONS 42OOO EAST 35 A COMP
6 BISWAL 29ffi0 SOUTH Y A MECH
(a) To display the names of alr employees who are in the area Soutir.
(b) To display name and age of all employees HAVING age > 40.
(c) To display list of alr emproyees whose salarv >:30000 and <:40000.
(a) To display the list departmenr wise.
(e) To display the employee names in descending order of age.
(fl To insert a new row with the following data :
RELATION: STUDENT
No. Name Age Dept Dateofadm Fee Sex
1 pankaj 24 Computer l0-Jan-97 DA M
2 Shalini 2l History 24-Mar-9g 20A F
, Sanjay 2. Hindi t2-Dec-96 300 M
4 Sudha 25 History 01-Jul-99 m F
SQL SELECT Statement 577
RELATION:TOY SHOPPE
Sno Toy_name Category Price Quantity Starting_Age Ending_Age
1 Popeye StuffToy 450 12 0 I
2 Rapid Fire Trvo Pla;,sr 600 25 5 1
3 TeddyBear StuffToy 3m q I 5
(a) Display the names of all tlrose Toys, which are for two players.
(b) To display the names of Toys and their Price having quantity more than 20.
(c) 'fo display the list of all those Toys wit Starting_Age > 2 in descending order of Price.
(d) To display a report with Toy_Name, Category Price and Total Value for only those toys for which the
Starting_Age is above I aud Ending_Age is below 9.
(e) To display the categorv and number of Toys of each Category in the table Toy_SHOPPE.
(/) To insert a new item in the existing table with the following data :
RELATION:STUDENT
No. Name Stipend Stream AvgMark Grade Class
1 Neha 450.00 Medical 89.2 A llc
578 Saraswati Informatics Practices (Xl)
SQ!- Functions
26.1 Introduction
Functions are predefined formulae. They have also been calied calculation engines, because functions cleliver
their results quickly by intemally calculating multiple and sometimes cornplex sets of mathematical expressions.
Functions are built-in forrnulae that perform complex Math for you. Functions, like other operands, always
return a particular type. In this chapter we rvill describes various types of SQL function's syntax, purpose,
examples, and data type ofthe returned value.
SQL provides tw'o +/pes of functions :
tr Character
tr Number
tr Date
tr Conversion
tr General
tl Case conversion functions. LOWER, U PPEP. and INITCAP are the three case conversion functions.
tr Character manipulatuon functions. CONCAT, SUBSTR, LENGTH, INST& LPAD and T'RIlvl are the
six characters manipulation functions.
(57s)
580 Saraswati lnformatics Practices (Xl)
T'he character functions are listing in Listing 26.1 below.
Listin 25. 1 Character functions.
Funrtion Purpose
LOVTER.(colu m.n e ;:1t r e s s i ort s Converts ai1:ha character values to lowercase.
UPFER.(colurnn exp re s s ion'1 L'onverts alpha character values to upperca-se.
IN-ITCAP(coI urnn I expre s s ion I ) Converts alpha character values to uppercase for the first
letter of each word. all other letters in lowercase.
CONC,{I(columnl expression} . Concatenates the first character value to the second character
colurnn2 expression2) vaiue equivalent to concatenation operator (ll)
SUBSTR(column expression, m[, n]) Refurns specified characters from character value stafiing at
character position m. n characters long (trf n is negative, the
count stafls from the end of the character value. If n is omitted,
all characters to the end of the string are returned).
LENGTH(co h,tmn I expre s sion) Returns the number of characters in value.
INSTR(column I exp re s s ion, m) Returns the numeric position of a named character.
l-PAD(column I expression, n, 'string') Pads the character value right-jusified to a total width of n
character positions.
TRll{(leading I trailing I both, Enables you to trim heading or trailing characters (or both)
trim_claracter FROM from a character string. If trim_character or trim_source is a
trim_source) character literal, you must enclose it in single quotes. This is
a f'eature available from Oracle8l onward.
LOWER
Ffle
19 rofrs sel*cted.
'sQL> I
_Jl*
Fig. 26.1 Names in lowercase using LOWER function.
T]PPER
The syntax is as :
19 rou,s selPctPd.
sqr> I
CONCAT
The syntax is as :
tib glir
sqt) SELEcT
:CO}ICRI ( IHf T.IE, TRDDRSSS )
Bak"sh SharEa 2{s-Haluiga Nag.r
rJugil HittaI 30, RaneEh l{agar
Sharrnila Naur D-31, ftshok Uihar
Sand?ep Kauehik fG-$2, Shaliflar tsagh
,Sangeeta Uats G-35, t4aluiya Nagar
Ramesh ltunar BE-Ir2, shalinar Bagh
'Shy*rrr A!"ora 50" llIG FLf,IS, ltohini
'John nag R-4{, Hirti Hagar
Uiueli ftdtuEt E-A3/?7 , Sec-1, Bohini
'Rajesh Uerrna D-1i,/136, Sec-s, D!,areka
Asnok singhal F-1/65, East Patel Ngr
'Ehetan Shukla C-105, l8th Eross
]&eena Hehta f2O, oDR golony
lBhuana tamDa E-14G, Suastik Rpptt., DLF
.Jaqjit singh e-240, Printers Apptt.
'Dinesh EoeI R21-Triueni Apptt,
ilokesh Rith0r€ C-'t1, HIG FLat
,ekash Bathi A-92, t+nsad t{arg
Sinran Cna(ula 0-1/128, Sec-5, Rohini
19 rous selected-
SQL>
rl ".1
Fig. 26.4 Names and address are concatenated using CONCAT function.
SUBSTR
The syntax is as :
LENGTH
The syntax is as :
'Blal,,Etr
St
sQL> SELECI TNo, LPED(SfiLRRY, 12, FRON TEACHER;
.,$k'g# Scxr--fr"€nt[fr*,;r:ljg> ::,,, "t; '. ':.. .'.. .,. ,.;, it.
SQL> SEI-ECT CCNOAT(TRIi((TNAI.II).TROD8ESS) FEOI,I
It{srR( TNftr{€,
j--.----- --"- -.
,RaLesh Strarr$a 2
JJugal t'rittal q
isharmila Ksur Q
jsand€ep l{aushi* 2
:SingeBta Uats 2
:Ball|esft l(umar 2
'Shgal'} Arora Ir
;John Rag 7
;UiveL Bar,rat I
r8aj*rh Uerma 2
iAsarokSiftghal 12
i0n€tan Shukla 5
'ifieeaa hPhtfi 5
lBhrrana Lanba 4
{agjit singh 2
g
:Dinesft Goel
iLokesh Sithore I
lfilrash Rathi 3
iSimran snaHle 5
isor->
I
|
You can use the SELECT command clauses like WHERE, ORDER BY clauses in string functions. For example,
suppose you want to list all the TNO and TNAME whose hrst character is 'p' 1n d3-ocending order of TEACHER
table. For that, write the command as :
SELECT TNO, TNAME FROI\{ TEACHER
WHERETNAMELIKER.To'
ORDERBYTN,ANIEDESC
When the above command executed, it will display the output screen as shown in Fig. 26.8.
SQL>
2 I{HERE THRH€ LIKE 'B*'
d ORDER EY THAHE DESS;
!TX0
Tltese are the four basic arithrnetic functions, which shcr.l, mathematical calculations rvith flvo or more values.
For example,
SELEC'I SALARY SALARY + 1OO. SALARY- 1OO, SALARY * 12, SALARY/30 F'ROM TEACHER;
When the above statement executed, the following Fig.26.9 displays the arithmetic calculations of
SALARY column in T'EACHERtable.
SQL Functions 587
. ABS(value)
Purpose. Absolute value is the measure of the magnitude of something. This function always returls a positrve
integer.
tu 4tr) 345.678
CEIL
The syntax is as :
CEIL(vaiue, precesion)
Purpose. This function returns the smallest integer (or whole number) that is greater than or equal to a specific
value.
When vou execute the above SELECT statement, the following output will be displayed.
588 Saraswati lnformatics Practices (Xl)
tg 456 345
EXP(value)
LN(value)
LOG(value)
Purpose. The EXP is e(2.71828 183...) raised to the specihed power; LN is the "natural" orbase e, logarithm of
a vlaue. The first two functions are reciprocals of one another; LN(EXP(value)): value. The LOG function takes
a base and a positive value. LN(value) is the same as LOC(2.71828183, value).
FLOOR(value, precesion)
Purpose. This function is the opposite of CEIL. This function returns the smallest integer (or whole number)
that is greater than or equal to a specific value.
Examp te SELECT FLOOR(l 64), FLOOR(-456), FLooR(345.678) FRoM DUAL;
When you execute the above SELECT statement, the following output will be displayed.
1g 456 345
MOI,
The syntax is as :
MOD(value, divisor)
Purpose. Divides one numeric expression by another numeric expression and returns the remainder. MOD( )
(modulus) divides two numeric expressions and returns the remainder. The number of decimal places in value,
determines the number of decimal places in the result. A positive number is retumed if divisor is positive, and
a negative number is returned if divisor is negative.
-t
POWER
The syntax is as :
POWER(value, exponent)
Purpose. This function has the abrlity to raise a value to a given positive exponent.
SQL Functions 589
r00
ROUND
The syntax is as :
ROUND(value, precision)
Purpose. This function rounds numbers to a given number of digits of precision. If value is negative, ROLTNDQ
returns a whtrle number containing precesion zeros to the left of the decimal point. For example, if value is -2
the first and second digits to the left of the decimal point in the value are zero.
When you execute the above SELECT statement, the following ouput will be displayed.
ROUND(67689.6ss,r) ROLTND(-3456.65,-2) ROUND(8976.56,0)
SQRT
The syntax is as :
SQRT(value)
Purpose. This function is the reverse of POWER function, i. e., POWER(value, .5).
10 t2 t6
TRUNC
The syntax is as :
TRUNC(value, precsion)
Purpose.Retumanumericexpressiontruncated toaprecesiondecima! places. If precision isomitted,no
decinral places. Ifprecision is negative, numbers left ofthe decimal points are truncated to zero
SYSDATE
07-JUN-03
26.2.3.1 Arithmetic with Dates
As you know that the databases stores dates as nunrber" So. you can perform tne calculation using the
arithrnetic operators. You can add and subtract number to or from a date and the result rs of type date. Also it
is possible to subtract two dates to find the nulnber of days between them.
You can perfonn the following operations :
Operation Result Description
date -l- number Date adds a number of days to a date
date-number Date Subtracts a number of days fiom a date
date date Nurnber of days Subtracts one date from another
date + number/24 Date Adds a number of hours to a date
Example SELECT TNAME, (SYSDATE-DOJ) FROM TEACHER;
26.2.3.2 Date Functions
The entries in this category allow you to generate and manipulate date daia. You can use these functions to
determine the number of nronths betvveen two dates, next Cav of the date specified, or last day of the month.
The Listing 26.3 given below shows the date functions.
Listing 26.3 Date functions.
Function purpose
When the above query will be executed. the fotlowing screen will be displayed as shown in Fig. 26.10.
SQL Functions 591
"lile. Ed,1
$aarch F-;a tr\:
I
"'
Sl}L > SELECT TH*I,IE, DoJ, svsDtTE, 'J
llj
Fig. 26.10 Calculating months difference between two dates.
ADD_MONTHS
The syntax is as :
ADD_MONTHS(date1,n)
Purpose. Returns the date by adding n number of calender months to datel . The value of n must be positive or
negative integer.
Example To add 6 months with the joining dare (DOJ) of all teachers, rhe query will be :
NEXT DAY
The syntax is as :
NEXT_DAY(datel,'char')
Purpose. Finds the date of the next specitied day of the week ('chaf ) i.e., Sundal'. Nlorday, Tuesday, Wednesday,
Thursday, Friday or Saturday after given date. For example. suppose you want to know the date of first
Monday after their joining date of all teachers. The query will be :
When the above query will be executed. the following screen will be displayed as shown in Fig. 26. I l.
592 Saraswati lnformatics Practices (XI)
8b 'Jit,,S<*rti' Qpiiors,-Q*p'r
.
t2-DEt-01 17"DEC-S'l
0?-JuL-ss 05*JtiL-99
06-JUlt-00 12-JUN-00
08-Allt-01 13.-euG"oJ
20-FEB-0G 21-FEB-On
03*JuL-97 07-Jt'1.'97
15-iUC-SB 1]-AUG-9S
22-SlP-01 24-SEP-S1
12-0Cr-0-t 15-0cT"01
87-H0U-06 1?-NoU-80
11-nuc-gS 16-0UG-99
13-JUH-01 18- Jtltt- 0't
1E_JUL_BA 24"JUL_SU
16-JUL-01 23-JtlL-S1
11-Jtlt-98 13-JUt-98
12-0CT-06 16-0C1"90
17 JUL-99 19-JUL-99
18-JUL-00 24-JUL- 08
16-JUL-01 2s-JUL-61
19 ro(as selecterl.
SAL> I
1l,l
Fig. 26.11 Finding the date of next named day of week.
LAST DAY
The svntax is as :
L* Ldt tredctl UidDrE lidp' .' ,s.1
",',
'fi'
sQL> SELECT rlr0tlE, DoJ" Lf,Sr_DflV(DoJ) fiS Enrll'lonth
LAST_DAY(date) 2 FRO}C TENGHEfl;
Purpose. Retums the date of last day of the INAITE 00J ENBtlotiril
month that conatin date, i.e., it produces the RakeEh Strarrla 12-OEC-01 31-DEC-01
date of the laSt day of the month.
Jugal tlittai 03-JUL-99 31-JUL-99
shirmila Iaur 86-JUN-00 3o-JUN-08
Sandeep Kaushik 08-nuG-01 31-euc-81
Example Suppose you want to find the last Sangeeta Uats 20-FE8-n0 2q-FEB-06
day of the month of the joining date of all Baresh l(unar s3-JIIL-97 31-JlrL-97
shgirn erora 15-eUG-g8 S'l-AUG-98
teachers, then the query will be :
Joh{ Rag 22-SEP-01 3o-SEP-01
uiuek flaiuat 12-0CI-51 31-oCT-01
SELECTTNA"ME.DOJ. Rij?sh Ue:rna 07-N0u-80 30-N0u-00
LAST-DAY(DOJ) AS EndMonth ftshok sinqhal 11-RUG-99 31-nut-99
Chetan Shrkla ,3-JUfi-{!1 3o-Jufl-&t
FROMTEACFIER Reena f,lehta 18-JUL-BS 3-l-JUL-09
Bhr,rand Lanba 15-Jt'L-01 31-JUL-.81
When the above query will be executed, Jaqjit siogh 11-JUL-98 31-JUL-98
DineEh GoeI 12-DCr-0t! 31-0cT-0n
the following screen will be displayed as Lokesh Rethore 17-JUL-99 s1-Jl'L-gq
shown inFig.26.12. Akash BEthi 18-Jl'L-00 31-JUL-00
Si!I|ran Charul-a 16-JuL-01 31-JUL-0',r
19 rcr,js s€lectPd.
SQL >
;u" _
Fi1.26.12 Finding the last date of ioining date month.
SQL Functions 593
RotiND(date[,'ftnf'])
purpose. Returns date rounded to the unit specified by the format model frnt. If the forrnat model fmt is omitted'
date is rounded to the itearest day.
The syntax for TRLINC is as :
TRtINC(date[,'ftnt'])
purpose. Returns date with the rime portion of the day truncated to the unit specitied by the format rnodel fmt'
If the format model imt is omitted, date is truncated to the nealest day.
Example Compare the date of joining for all ernplovees who started in 1998. Dispiay the teacher number.
date
ofjoining and months starled using ROUND and TRfINC frrnctioils. The query will be :
SELECTTNO,DOJ,
ROLND{DO,i,'tuIONTH), TP.LNC(DOJ,'MONTH')
FR.OMTEACF{ER
WHEREDOJLiKE'o/o91'
When the above query will be executed, the toiiowing screen rvill be displayed as shown in Fig.
26. l3 '
E0ti$!S{t}0J TSUNC(D8J
tr Implicit datatype conversion. When the Oracle Server automatically convefts data to the expected
used the rule for expression
datatype. Tt is, .onrersion is called implicit cor..version. The Orcaie Server
when a datatype conversion is neede.d in place not covered by a rule for assignrnents conversions'
For assignmenl, the Oracle Server can automatically conveft the following :
trlom To
VARCAHR2ORCHAR NUMBER
VARCHAR2ORCHAR DATE
NUMBER VARCAHM
DATE VARCAHR.2
Saraswati lnformatics practices
For expression evaluation. the Oi.acle Server can automatically
convert the following :
Frum
To
VARCAHR2ORCHAR NUMBER
VARCFIAR2ORCHAR DATE
tr Explicit datatype conversion. Explicit datatyep conversion
are dole by using the conversion functions.
Conversion functjons conveft one datatype to another.
SeL providl theihree explicit conversion
functions are listed in !isting 26.4.
Listing 26.4 Explicit date datatype conversion functions.
Function Purpose
TO_CHAR(numberldate, [ frnt], Converts a number or date value to a VARCHAR2 character
Inlsparams]) string with format model tnt.
Number Conversion :
nlsparams parameter specifies the following characters,
which
are returned by number format elements :
o Decimal character
c Group separator
e Local currency symbol
o Intemational currency symbol
If nlsparams or any other parameter is omitted, this function
uses the default parameter values for the session.
The nlsparams parameter specifies the language in which
month and day names and abbreviations are returned. If
this
parameter is omitted, this function uses the default
date
languages for the session.
TO-NUMBER(char, [fint], [nlsparams]) Converts a character string containing cligits to a number
in
the format specified by the optional format model
firt.
The nlsparams parameter has the same purpose in this
function
as in the TO_CHAR function for number conversion.
TO _DATE(chaa [fmt], [n I sparams]) Converts a character string representing a date to a date
value
according to the fint specified. If fmt is omitted, the format
is
DD-MON-YY
The nlsparams parameter has t-he same purpose in this
function
as in the TO_CHAR function for date conversion.
TO CIIAR
The syntax is as :
A;)
Fig. 26.15 Joining date in Day Month Year format.
597
SQL Functions
The SeL sratement in the previous example displays the name and joining date for ali the teachers.
The
joining date appears as 12 December 200i. Modify the axample to display the dates in a format that appears as
SELECTTNAME
,'of ' Month YYYY fmHH:MI::SS AM') ''Date of Join',
TO-CHAR(DOJ, 'fmD<lspth
FROMTEACTIER;
When the above query will be executed, the following screen will be displayed as shown
inPig.26'16'
'SAgrh !
f .S$ior$
sqL> SELECT TNNHE,
2 To_CHSB(00J,' f m0dsPth llonth VYYY frl[H:l'lI::SS Rtt') "Date of
FBON TEfiCHEB;
' Fig. 26.16 Joning date with character number and time format.
is capitalized and
Notice that the month follows the format mocle specifiecl, in other words, the first letter
the rest in lowercase.
-
'Ek.
#itoft): P6;4
SqL> SELE8T THNilE, 'ooo 999' )
2 FNOh TERCTIEft;
TNAflE ennual S
:BakeshSharna d9,600
rJugal ttittal
,Lokpsh Rathore
.nkash Bathi 6f"qE0
Simran ChaNla 5t,400
19 rots selected-
SQL> I
'sQr> I
ltrJ
Fig. 26.18 Gonverting a character string into date format.
SQL>
JtJ ,.
Step2=Result2
3 = Result 3
Fig. 26.20 Execution style of nested function.
For example, to display the first MONDAY after 6 months in the ascending order of the joining date, the
querywillbe:
SELECT TNAME, TO_CHAR(NEXT_DAY(ADD NIONTHS
(DOJ,6),'MONDAY),
'fmDay, Ilonth ddth, YYYY')
"Next 6 Month Review"
FROMTEACTIER
ORDERBYDOJ;
When the above querv will be executed, the follorving screen will be <lisplayed as shown hFig.26.2I.
Solved Exercises
Ql. How many types of functions are there in SQL and what are they ?
Ans. SQL functions can be divided broadly into four categories viz. Character functions, Data conversion
functions, Date flunctions, and Numeric functions.
Q2. Give the examples of character functions.
Ans. Character functions are LOWERQ, UPPERQ, INITCAPQ.
-
Q3. List the data conversion functions.
Ans. Data conversion functions are TO CHARQ, TO_DATE( ), TO_NUMBER( ).
-
Q4. Give at least three date functions.
Ans. Date functions are LAST_DAY( ), MONTHS BETWEEN( ), NEXT_DAY( ).
-
Q5. Give at least four examples of numeric functions.
Ans. Numeric fi.rnctions are- ROUND( ), TRUNC( ), MOD( ), SQRT( )
Q6. Which function returns the remainder of numeric expression ?
Ans. MOD0
Q7. Write the function returns the character string by convefting each character to lower case.
Ans. LO\VERQ
Q8. S&ich function returns lengih of a string ?
I Ans. LENGTHQ
' Q9. Write the function .,vhich returns the last day of the rnonth ?
Ans. LAST_DAYQ
Ql0. What is the result of expression MOD(-;7, 2) ?
Ans. 1.
Qll. Write the name of function, which returns specified number of character from a string ?
Ans. SUBSTRQ
Ql2. How will you remove leading and trailing blanks from a character string ?
Ans. UsingTRIMQ.
Ql3. How willyou convefi a date to a character ?
Ans. UsingTO_CHARQ
Ql4. What istheresultof ROUND(123 .5618,2)?
Ans. 123.-<7
, Ans. LENGTFIQ function is used to retum the number of characters in a character expression.
Q16. Which functiorr is r.rsed to return the specified expression padded on the left side ?
. Ans. LPADQ firnction is used for this purpose.
Ql7. Which type of parameters are accepted by ADD_MONTHS0 function ?
Ans. ADD_MONTHS( ) accept two parameters. First one is the date and second is the number.
Ql8. Write the function to get number of months befween two dates.
Ans. MONTHS BETWEEN
Ql 9. What is the result of MONTII BETWEEN(' 12-DEC-98','25-JUN-98') ?
Ans. 5.5806452
Q20. Whatrvill be the output ofADD_MONTHS(' 12-DEC-98', 6)
Ans. I2-JLIN-99
Q21. How will you get computer date ?
Ans. SYSDATE is used to get the curent date.
Q22. Write a command to PRINT first three characters of "Information" .
Ans. SELECT SllBSTR(lnformation', 1,3) FROM DUAL;
Q23. A numeric data field AMOUNT stored in table ORDER contains the value as 30309.98. Write a command
in SQL to round off amount :
--------------7
TABLE:HOSPITAL
No. -Name Age Depaftment Dateofadm Charges sex
I Arprit O Surgery 2l-Jan-98 300 M
2 Zarina D ENT l2-Dec-97 250 F
3 Kareem n Ofihopaedic l9-Feb-9g 2W M
4 Arun 12 Surgery 1l-Jan-98 300 M
5 Zubin 30 ENT 12-Jan-98 250 M
6 Ketaki 16 ENT 24-Feb-98 250 F
7 Ankita D Cardiology 20-Feb-9g 800 F
8 Zareen 45 Gynaecology 22-Feb-9g 300 F
9 Kush l9 Cardiology t3-Jan-98 900 M
l0 Shilpa 23 Medicine 2l-Feb-98 e0 F
(a) To display the narne of the patients in upper case.
(b) To add 6 months to the field Dateofadm.
(c) To find the next FRIDAY ofthe Dateofadm.
(ri) To display square root of the field charges.
(e) To retum the 2 to 4th character of the field Department.
SQL Functions 603
(fl To find the months between the current date and the dateofadm
G) Give the output of following SQL statements:
(,) SELECTNAME, Dateofadm FROMHOSPITAL
V/HERE Dateofadm : TO DATE('Feb 19, 1998', 'Month dd, YYYY')
(ll) SET,ECTNAME,
"of 'Month YYYY flnHH:MI::SS AM') "Date of Join"
TO_CHAR(Dateofadm,'fmDdspth
FROMHOSPITAL
(irr) SELECT NAME,TO_CHAR(Dateofadm,'fmDD Month YYYY') "Date of Jo in "
FROMHOSPITAL
WHERENO:3;
(Iv) SELECT NA.ME. DEPARTMENT,CHARGES,
DECODE(DEPARTMENT,'Surgery', CHARGES* I . 1 0,
CHARGES* 1.20) Revised FROM HOSPITAL;
Ans. (a) SELECT UPPER(NAME) FROM HOSPITAL;
(b) SELECT ADD MONTHS(DATEOFADM, 6) FROM HOSPITAL;
(c) SELECT N EXT_DAY(DAIEOFADM,'FRI DAY') FROM HOSP I TAL;
(d) SELECT SQRT(CHARGES) FROM HOSPITAL;
(e) SELECT SUB STR(DEPARTMEN T, 2, 3 ) FROM H OSP I TAL;
(, SELECT MON THS-BETWEEN(DAIEOFADM, SYSDATE) PROM HOSP ITAL ;
(g) (l) Kareem 19-FEB-98
(ii) xaNE Date oF Join
f,rprit Tr,renty-First of Januarg 1998 12 i 00: :00 Rl,l
Zarina TirelFth of Decenber 1997 12:86::08 RN
Kareen Nineteenth of Februarg 1998 12:00::86 Al'l
Rrun Eleuenth of January 1998 12:60::00 Hl'l
:Zubin T+relfth oF Januarg 1998 12:00::80 AH
Hetaki Isrent!-Fourth of FeDruary 1998 12:00::00 R]'l
Ankita .2:00::08 RFI
llrentieth 0f Februarg 1998-1998
Zareen Tr,refit!'Spcond of Februarg 12:00::00 eM
Thirteenth of January -1998
Itush 12:60::08 RH
Shilpa T(,Jenty-First of February 1998 12:00::00 em
(lil) Kareem 19 February 1998
(fu)
nor. DEpARTr,rENr cHfiRGES REuIsE,
Review Questions
11. A character expression trame contains "try this problem". Write a command to pick the following set of
characters fronr it:
(a) First 6 charactels
(b) Frorn 3rd to 7th cha-r a,,r,'r:.
12. What wili be the result c j'ilre foiicrrying comrrands ?
t 3. A numeric data field NU M corriains 1256 i,195. Write a command to round offNUM to 1
Multiple Tqbles
ond Sub-Queries
27 "1 lntroduetion
One of the most powerful features of SQL is its capability to gather and manipulate data from across several
tables. Without this feature you would have to store all the data elements necessary for each application in one
table. Without common tables you would need to store the same data in severai tables. Imagine having to
redesign, rebuild, and repopulate your tables and databases every time user needed a query with a new piece
of information. The .IOIN statement of SQL enables you to design srnaller, more specific tables that are easier to
maintain than larger tables.
27.2Tables and Colurnn Names
In any query the column name is generally followed by the table name. First the table name is written followed
by a dot operator then the column name. For example :
tr Teacher.Tname
tr Departrnen t. Dept_no
Till norv you are not writing the table naine because vou are handling the single table at a time. But in the
multiple tables handling you have to urite the table naine. In the multiple table handling it is possible to write
the column name without the table name provided that all the columns must have the different names. But it is
not possible all the time.
The ability to relate data in one table to data in another enables you to organize information in separate.
manageable units. Teacher data can be kept togically distinct from DEPTM (department table) by storing it in a
separate table.
27.4What is Join ?
The most important fbature of the SQL is its capabitily to retrieve data from the muitiple tables in tenn of
relationship according to the common field, in the single commanC. This kind of operation is called join. In the
join the tables are listed in the FROM clause separated by commas. So, join is used to query data from more than
one table. The syntax for joining the two table is :
TEACHER DEPARTMENT
TNAME DEPARTMENT
JugalMittal Maths
SharmilaKaur Maths
The Cartesian product of the above two relations, department x teacher will produce the relation which
have5x5=25rows.
The cartesian product is ibrmed when a join condition is invalid. SO, all the rows of the first table get
joined to all the rows in the second tabie. A cartesian product is generally useless, which
tends to generate a
large number of rows. To avoid carlesian product always include a valid join concliticn in a WHERE
clause.
27.6Types of Join
Mainly there are two types of join conctitions. These are :
O Equi-join
tr Non-equi-join
But they can be further extended to :
tr Ourer joins
D Selfjoins
27.6.1Equi-join
The join, in which joining condition is based on equality between values in the
common column, is known as
equi-join' Equi-join is also called as the inner join or simple join. Equi-join is the probably the
most common
type ofjoin. You can use any type of relational operator in equi-join. Now, consider the
two tables with data as
shown in Fig. 27.3.
TEACIIERtabIe:
DEPARI'lVtrENTtable:
-
t^.i - -l
Fiie Ed 0rarons {dp
SqL> SELtfrf * FRBtI DEPBRTi{ENT;
DEPT DEFT}IftI,IE
,&s't Phgsieg
iD02 [fte&:istrg
D&s Flaths
Dti4 ConrFut*r
Bsg Eiolfgg
In the above qirery, ihe SEI-ECT ciause specifies the columl name tc retrieve. The FRCM ciau-ie specifie -c
the two tabie from which the data are to be retneve and the WHERE clause specilies how the iables are to be
joined. Beacuse, DEPT_NO is common in both the tables so it is necessary to prefix the labie rrame.
The above query produced the resuit as shown intheFig27.4.
THRI.IE DEfTNRHE
19 rorlrs sElEcted"
sQL>Li
:i-l ,tij
Fig.27.4 TEACI'lER and DEPF\RTMENT table in equi-ioin.
610 Saraswati Informatics Praetices (Xl)
TEACFIER (TNO, TNA[,IE, 'I-ADDRESS, SALARY, DEPI_NO, DOJ), rvhere the data is shown in Fig. 27.3
Now create a table STUDENT with the following data t1,pes and enter the lbllowing records :
Similarly, insert all the records into STUDENT table. After inserting, when you will apply the command,
SELECT*FROMSTUDENT;
the following output screen will appear as shown hFig.27 .7.
Seach'0F&rc tlti<.;
SQL> SELEGT * Ffl014 STUD E?,IT;
16 raus selected,
saL> I
Create another table TEACHES rvith the following data types and enter the following records :
m1 s01
m2 s03
m3 s02
TD2 s04
1V2 s05
T04 s01
m5 s06
m2 s04
T03 s03
T01 S07
Apply INSERT command to insert the above records into TEACHES table. For example,
the
INSERTINTOTEACHES
vALtrES(T01"'S01');
Similarly, insert all the resords into TEACHES table. After inserting, when you will apply the command,
SELECT*FROMTEACHES:
the following output screen will appear as shown in Fig. 27.8.
Tilo sNo
:T 01 SS1
lT 82 S03
iT A3 SS2
iT 62 t0Ir
lr 82 s8s
,lw sB1
1T85 S06
ll b:2 solr
ir or sBa
I01 SB7
:1 B ror,rs sel.ected -
I
lsqr-> I
!
TEACHER (TNO, TNAME, TADDRESS, SALARY DEPT_NO, DOJ). where the data is shori n in Fig. 27 3
Now create
a table GRADE with the following data types and enter the following records :
Apply the INSERT command to inserl the above records into .XsF',tt
GRADE table. For example, sql> SEt-tDT * F*tlM ER4DE;
In the ahove tahles TEACHER and GRADE, there is no cornmon column exists. So. it is not possible to
perform the equi-jcin. There is no direct relationship between the two tables. The only relationship between the
above two iables are that the SALARY in the TEACHER table in between the MINSAI- and MAX SAL column
of the GRADE table. So, we cannot obtain the result using the '=' operator. Thus the query will be :
Exaruple SELECTT.TNAME,T.SALARYG.GRADE
FROMTEAC}IERT.GRADEG
\\.HERE I"SALAI{Y BETWEEN G.MM{SAL AND G.M.AXS,AL;
The above query wiii produce the result as shown in Fig. 27.1 1.
r:ifiu
lrle.. *na+,+*, Silpi;.". ,il;. :'';:
sQL,' SEL€8T T.TN*t{E, T.S9L&&V, 8. GE6DE
2 FROI4 TE{TCUFR I, GBf,NE G
]IHINE T.SRLHRY BETHE€N B.TIiHSSL ftHD G"I'IR}iSRL;
1trNnNE SRLN*Y G
16 robrs s?lected-
SQL> I
{
.E
Before, make an outer-join, let us consider a department
sal) SELECT T.TM[4E, D-DEPTIA]IE
'Economics' whose department number is "D06". This Z FR(II'I TESCHER T, DEPNflTNENI D
department does not have any teacher who teaches 0 lll{EBE T-DEfT_N0 = D.0EFI-N0;
economics. After inserting the department number "D06" rHfi}IE DEPINEHE
record, when you make an equi-join query between Rakesh Sharna Biology
TEACHER and DEPARTMENT tables, it does not display Jugal l4ittal chemistry
Sharmila l{a.rr Ph]lsics
the inserted deparlment number" Because, there is no teacher Sande€p Naushik ilaths
in such department. Thus, the query output will be as shovrn Sanqesta lrets Biolo!9
ftanesh Humdr l4aths
inFig.21.l2. Shgam Arora Chemistry
John Bay l,fathe
uiuek Raoat Phgsics
RajPsh Uerma ConputPr
,*shok Siilghal Ehemistrg
jchetan Shukla cheEistr!,
;Reena ilehta i(aths
,Bhurana Lanba ConputPr
Jagjit sinqh Conputer
Dinesh Goel Conputer
LokEsh Rathore N.ths
Rkash Rathi lleths
Simran Chaula Computer
19 rous se1?cted,
sol> |
2l rous selected.
s0r >
ESI
xql> sELfcT T-TM), T-Tt{f,ftE, Tl .rripiis
2 FfiI}}: TE8*}!EB T, TE*GHER T1
3 NHER€ T.SSLRBV = TI.SALARf;
TTIO THfiI4E INNflE
tr WHEREclause
tr HAVINGclause
tr FROM clause
The syntax of the sub query is :
uery
lnnerquery
Example SELECT TNAME
FROMTEACTMR
WHERE SALARY>
(SELECT SALARY FROM TEACHER
WHERE TNO ='T05');
The above query display the teacher name whose salary greater than the teacher number T05. The outer
query takes the result of the inner query and uses this result to display all the teachers who earn more than this
amount as shown inFig.27.l5.
.Sharnila t(aur
jsandeep ilaushilr
'Reftesh Xrmar
Shyam Arara
lJohn Ray
'Uiuek Baruat
i6 rous selected-
SQL> I
tr Single row. This query returns only one row from the inner SELECT statement.
tr Multiple row. This query return more than one row from the inner SELECT statement.
618 Saraswati lnformatics Prdctices fil)
tr Single column. This query returns only one column from the irurer SELECT statement.
tr IVlultiple column. This query return more than one column from the inner SELECT statement.
27.9.1 Single Row Sub-Query and its Execution
Single row sub-query returns only one row and used single row operators. The single row operators are :
Operator Meaning
= Equal to
> Greater than
- Greater than or equal to
:SQL}
The above example consists of three queries i.e.,the outer query and two inner queries. The inner queries
will execute first, producing the result : 'DO3' and 5800, respectively. The outer query then uses the result of
the inner queries to complete the search. The output screen Fig. 27.16 shows the three queries.
Both the inner queries are the single value because they are retuming the single result. So this statement
is called a single row sub-query.
IiE'
SELEET INEME
" SALARV
FROI,I TEECHER
DEPT N0 =
( SELECT DEPT_NO
FBOH TEADHEB
UHERE rNo = 'r04')
SNLEBY }
( SELE0T SfiLenV
FROT4 IENCHEB
t,l{EBE lll0 = ' Tl 0' ) i
TNAI,IE STLARV
query uses this result to display the data of all the Chetao thukla 36 00
teachers whose salary is equal to the minimum salary
as shown inFig.27.l8.
j8 rous selected.
JSqL>
:THO INfil,IE
;T 01 flakesh Shar$a
lTs Sangeeta Uats
,TCC Uiu€k Ra$at
irl0 Bajesh Uerma
T11 Bsfrok Sinqhal
:T'12 Chptan Shukle
ir 13 feeca llehta
rT14 thrrana Lanba
,T15 Jagjit singh
T't 8 &kash Bathi
,rl g sirnran Charol;
11 rolrs selected "
s0L>
!sQL>
IITO TNAhE
19 ro?rs sPlected-
SQL> I
I.IPDATETEACMR1
SET TNAME = 'Rahul Verma'
WHERE TNO = (SFI ECT TNO FROM TEACTIER
WHERESALARY=9100);
When the above command executed, the
SALARY = 9100 will search from TEACHER
sqr) UPDRIE TEECilEftl
table in the inner query and respective name 2 SET INRI4E = 'Bahul Uerma'
will be changed in the TEACHERI table, i.e., 3 t,llEBE TNO -
(SELECI THo Fn0H TENCHER
lt $IHERE SRLRRV = 9100):
the narne Sangeeta Vats name witl be changed
to Rahul Verma. Because, the teacher Sangeeta Il ror{ updated.
Vats teacher no. is T05. When you will apply
SQL> SELEGI * FBot'l
the SELECT command wirh TEACIIER I tabte,
the fbllowing Fig.27.'26 will be appear. I}IO TNRME
SELECT starement
LNION
SELECT statement;
Consider the example if there is two tables having the same fields named as TEACTIER and TEACHERI
,
then you can display bcth the tables at a time using the UMON clause.
Exannple SELECT TNO, TNAMEFROM TEACI{ER
L]NION
SELECT TNO, TNAME FROM TEAC}IERI ;
The above statement displayed TNO and TNAME columns of two tables TEACHER and
TEACrIERI ar
a time on the screen. The duplicate rows has automatically deleted in
the UNION clause as shown in Fig.27.27.
Multiple Tables and Sub-Queries 625
iTHo IHRnE
itot'
l
SELECT statement
LiNION[ALL]
SELECT statement;
Example SELECT TNO, TNAMEFROMTEACIDR
I.]NIONALL
SELECT TNO, TNAME FROM TEAC}IERI;
Similarly, you can insert specific date values into the table. If you want to insert a new records into the
TEACHER table with the date value other than default format then you have to use TO-DAIE function.
INSERTINTOTEACHER
VALUES('T21','Rohit Dew aa','H-26l56,Moti Nagar', 8900, D04',
TO-DATE(April 5, 1998','Month dd, YYYY'));
When the above two commands are executed, two records will added in TEACIIER table. To show the
records including existing records, use SELECT command as shown in Fig.27.28.
SQL> INSERT I}IIO IEOCI,IEE
2 UALUES('T21', ,Bohlt De$an,, ,1fl-Z6l5.6, noti Nagar.. 0900,
e To_DRIE('fiprit 5,199A-, ,honth dd, VVVy.));
i1 rou created"
sQL> SELECT * FRot,t TEfiCilEn;
(l I
SQL}
Donnit conplete.
rsql> |
Rlok Joshi
FRO}I TEAIHE*I
- 'T0t';
Solved Exercises
Q7. What is the condition to combine the table using UNION clause ?
Ans. Both the tables must be union compatible i.e., having the same data type for all the columns.
Q8. Which command is used to create a table suing sub-query ?
Ans. CREATE TABLE AS SELECT
Q9. What is the difference between single row query and multiple row query ?
Ans. A single row sub-query retunss a single row while the multiple row sub-query returns more than one
row.
Q10. What is the difference between singie column query and multiple column query ?
Ans. A single column sub-query return a single column while the multiple column sub-query returns more
than one column.
Qll. What is the purpose of COMMIT statement ?
Ans. The commit statement ends the current transaction by making all pendlng changes permanent. The
previous state of the data can be recovered before applying the COMMIT statement. After applying the
COMMITstatement the data changes are made pennanent in the latabase. The previous state of the
data is permanently lost.
Qll. What is the purpose of ROLLBACK statement ?
Ans. The ROLLBACK discards all pending changes. The data changes are undone and the previous state of
data is restoled.
Ql2. Consider the two table given below and the write the command for (a) to (o) :
TABLE: EMPLOYEE
TABLE:DEIrTM
DEPTNO DNAME I]OC
IO ACCOUNTING DELHI
2A RESEARCH KOLKATA
30 SALES MUMBAI
4 OPERATIONS BANGALORE
(a) To display the employee name. department name and department number.
(b) To display the ename, dname and loc of all employee who earn commission.
(c) To display the ename and dname of all the employees whose name start with A.
630 Saraswati Informatics Practices (Xl)
(d) To display the name, job, department number and department name for all employees who work in
DELHI.
(e) To display the employee number and employee name along with their manager's name and manager
number.
(/) To display the name and hiredate of all the employee hired after employee Jagdeep Rana.
(g) To display the employee name whose salary is greater than the salary of employee number 7900.
(ft) To display the name of the employees whose job is same as that of employee number 7369.
(i) To display the name of the employees who are earning more than the average salary.
f) To display the name and salary of all the employees having minimum salary in their department.
(t) To display the name and salary of all the employees who are in SALES department.
Ans. (a) SELECT EMPLOYEE.EMPNO, EMPLOYEE. DEPTNO, DEPTM.DNAME
FROMEMPT,OYEE,DEPTM
WHERE EMPLOYEE.DEPTNO: DEPTM.DEPTNO;
(6) SELECT E.ENAME, D.DNAME, D.LOC
FROMEMPLOYEEE, DEPTMD
WHEREE.COMM ISNOTNULL
AND E.DEPTNO : D.DEPTNO;
(c) SELECT E.ENAME, D.DNAME
FROMEMPLOYEEE,DEPTM D
WHERE E.ENAME LI KE' AYO' ;
(d) sELEC'f E.ENAME, E.JOB, D.DEPTNO, D.DNAME
FROM EMPLOYEE E. DEPTI\,I D
WHERED.LOC:'DELHI'
AND E.DEPTNO: D.DEPTNO;
(e) SELECT E.EMPNO, E.ENAME, E.MG& EI.ENAME
FROM EMPLOYEE E, EMPLOYEE EI
WHEREE.MGR:EI.EMPNO;
(, SELECT ENAME, HIRED/\TE
FROMEMPLOYEE
WH ERE HIR-EDATE > (SELECT H I REDATE FROM EMPLOYEE
WHERE ENAME :'Jagdeep Rana');
G) SELECT ENAME. HIREDATE
FROMEMPLOYEE
WHERE HIREDATE > (SELECT HI REDATE FROM EMPLOYEE
WHERE ENAME :'Jagdeep Rana');
(/, SELECT ENAME FROM EMPLOYEE
WHERE JOB : (SELECT JOB FROM EMPLOYEE
WHERE EMPNO:7369);
(,) SELECTENAME FROM EMPLOYEE
WHERE SAL > (SELECT AVG(SAL) FROM EMPLOYEE)
(/) SELECTENAME,SAL
FROMEMPLOYEE
WHERE SAL IN (SELECT MIN(SAL)
FROMEMPLOYEE
GROUPBYDEPTNO)
(I) SELECTENAME, SAL
FROMEMPLOYEE
WHERE DEPTNO : (SELECT DEPTI \-O
FROM DEPTM WHERE DNAME :'SALES');
Multiple Tables and Sub-Queries 631
Review Questions
l. What is the difference between join and the sub-query ?
2. What is the difference between equi and non- equi-join ?
3. What is the difference between inner and outer join ?
4. Explain self join with exarnple ?
5. How will you delete the rows based on condition frorn another table ?
6. How will you insert the rows based on condition ftom another table ?
7. How willyou update the rows based on condition from another table ?
8. Explain type of queries with example.
9. How will you inserl the date values in the database ?
10. What is database transaction ?
TABLE:CLUB
COACH-ID COACHNAME AGE SPORTS DATEOFAPP PAY SEX
1 KUKREJA 3s KARME 2710311996 1000 M
2 RAVINA A KARATE 2010v1998 1200 F
3 KARAN 3+ SQUASH 19102/1998 2m0 M
4 TARLN 33 BASKETBALL OIIOIII99S I5M M
5 ZUBIN 36 SWTMMING 12;0111998 750 M
6 KETAKI 36 SWTMMING 241021t998 800 F
7 ANKITA 39 SQUASH 2010211998 22n F
8 ZAREEN 37 KARATE 2210211998 1100 F'
TABLE:GRADUAIE
SNO NAME STIPEN'D SUBIFCT AVERAGE DIV
I KARAN 4OO PHYSICS 68 I
2 DIVAKAR 450 COMPUTERSC 68 I
632 Saraswati lnformatics practices (Xl)
TABLE:GIJIDE
MAINAREA ADVISOR
PHYSICS VINOD
COMPL]-TERSC ALOK
CHEMISTRY RAJAN
MIIHEMATICS MAHESH
(a) To display the name, subject and advisor for all the graduates.
(b) To display the name, stipsnd and main area of all graduates who score average 68.
(c,) To display the name and advisor of all the graduates whose name start with
R.
(d) To display the name, div and advisor for all graduates whose subject is PHySICS
.
(e) To display the Sno and name along with their main area and advisor.
f) To display the name whose average is greater than the average of DIVyA.
(g) To display the name of the graduates whose subject is sarne as that
of graduate number 2.
(h) To display the name and average of all the graduates having minimum average in their subject.
(r) What willbe the ourput of the following query :
SELECI' NAME, ADVISOR
FROM GR.ADUATE, GUIDE
WHERE SUBJTJCT : MAINAREA;
15. Consider the two tables given below :
TABLE: SUPPLIER
S# PName SName ety price City
Sl Bread Britannia 150 g.00 Delhi
52 Cake Britannia '2SO 20.00 Mumbai
33 Coffee Nescafe l7O 45.00 Mumbai
54 Chocolate Amul 380 10.00 Delhi
55 Souce Kissan qio 3d.00 Jaipur
56 Maggi Nestle 3q 10.00 Kolkata
57 Biscuit Marie 560 2 t.00 Chennai
58 Jam Kissan DO 40.00 Delhi
59 Piknik 345 5.00 Kotkata
TABLE:PRODUCT
P# Pname pcity
Pl Bread Delhi
n Cake Delhi
P3 Coffee Kolkota
P4 Souce Jaipur
(a) To display the Pname having same city and pcity .
(D) To display the product name having city of supplier as Jaipur.
(c) To display the?name, Sname having P# value 1.
(d) To display the Pname and Pcity where qty is 340.
(e) What will be the output of the following query :
Select Pname, P#
From Supplier, Product
Where City -Pcity;
16. Consider the two tables given below :
TABLE: BANK
Acc no CName Bname Amount Dateofopen T_Transactions
I Karan BankofBaroda . 15000 tauDS 10
t
Chapter - 28
28.1 lntroduction
The tables you are dealing till now are known as the base tables.
These are the tables which contain data. There
is another kind oftable known as view whose contents are derived
liom other tables. They can queriesjust as
base tables, but they contain no data of their own. Views are like
windows through which you view information
that is actually stored in a base table. But the view also follow
some object naming rules which are discussed
below.
28.2Database Objects
An oracle table can be created at an1' time. An oracle database can
contain multiple data structures. Each
structure should be defined in the database design stage so
that it can be created during fhe initial stage of
database development. The following are the Database objects
available in SeL :
tr Thble. A table is used to store the data.
tr View. A view is the temporary table created using a Original Table, you can say it is a subset of one
or more table.
O Sequence. Sequen Lmary Key values.
Index. They are us
?
tr
ofsome queries,
Synonym. They gi
28.3 Database Object Naming Rules
B The object must be maximum 30 characters Iong (except the
da,tabase names which are limited to g
characters.
tr The qbject name should not contain the quotation mark.
A The name must start with letter.
tr The use of $ and # is discouraged in the object name.
tr A name must not be a reserved word.
28.4 Simple Views and Complex Views
The views we have created in the above examples are called as
the simple views. But you can also create the
complex views using the GREATE vIEw command. The main difference
between the simple view and the
complex view is :
Simpleview Complexview
l. A simple view can use one table. A complex view can use one or more tables.
2' A simple view does not contain functions. A complex vierv can contain functions.
3. A simple view cannot contain group of data. A complex view can have group of data.
4. can perform DML through the view. Does not always allow DML through vierv.
(634)
Creating Views and Privileges 635
28.5 The CREATE VIEW Command
A view is table that has no data of its own. A view is derived from another table .A view is often referred to as
a virtual table. Views are created by using the CREAIE VIEW statement. After the view has been created, you
can use the following SQL commands to refer to that view :
tr SELECT
tr INSERT
tr LPDATE
tr DELETE
You can use views, or virtual tables, to encapsulate complex queries. After a view on a set of data has
been created, you can treat that view as another table. However, special restrictions are placed on modifying
the data within views. When data in a table changes, what you see when you query the view also changes.
Views do not take up physical space in the database as tables do.
You can create view using CREATE VIEW command. The form is as :
CREATE VlEWviewname
AS
SELECT srarement
I wirh check oprion]
Example CREATE VIEW TEACH
AS
SFLECT TNO,TNAME,SALARY
FROM TEACMR
WFIERE TNO >'TO4';
sqL) CBERTE UIE(I TEECH
When the above command executed, the 2 R5
3 SELECT THO,THNl.IE Sf,LERV
message will be displayed as View created as shorvn 4 FBO1..I TERCHER
,
in Fig. 28.1. 5
You can also use the order by clause in the rUiel,, created "
CREATE VIEW as shown in the example given
below:
]SQL> SELECT i FffOH IEACH;
can display the contents of the above view ,BioIog! 5806 9100
,Cha mistrg 36&6 1?288
using the SELECT statement. rComputer q700 8906
;Haths 5700 15206
Example SELECT * FROM COM_TEACH; PhUsics 1 0200 28260
The above comrnand will produce the a SQL >
complex view resultin table COM_TEACH
as shown in Fig. 28.3.
DROPVIEWview name;
The only thing to remember when using the DROP VIEW command is that all other views that reference
that view are now invalid. Some database systems even drop all viervs that used the view you dropped.
28.12What is User ?
SQL is mostly used on the computers that have more than one user. When number of user are working on a one
computer there is a need to differentiate between them. So, it is necessary that there should be some authorization
code be there to identi$ the user. When the user starts working on the SQL*PLUS, he or shc must logs on,
which tells the computer which user, identified by its authorization ID is working on the computer. Any number
of people with same authorization ID is treated as one user. On the other hand, a person can be many users by
using different authorization lD.
A table or cther objects which is created by one user is or+ned by that user only. A user may or may not
have the privilege to perform an action on an object he or she does not own l.e., created by the other user until
that user give the privilege. How one user can give privilege to other will be discussed later on.
SELECT A user with this privilege can perform queries on the table.
NSERT A user with this privilege can perform the INSEM command on the table.
UPDATE A user with this privilege can perform the UPDATE command on the table.
DELETE A user with this privitege can perform the DELETE command on the table.
Saraswati lnf ormatics Practices (Xl -
The GRANl'command is used to give permission to one user to access the table of another user or can
do any other desire operation according to the privilege assigned. For example, Iest Master owns a
EMpLOyEE
table and wants to let Tlansaction perforrn queries on it. l'hen Master would enter the following command
:
Itt the above example there are two grants given to two users TRANSACTION and SLAVES.
At the same tinle 1,ou can restrict the grant on the certain columns. For example, you want to restrict the
user TRANSACTION to update only the NAME column of the table EMPLOYEE then the statement wilt be :
G RAN T U PDATE(NAME) ON EMPLOYEE TO TRAN SACTION;
The GRANT statement is used to grant privileges to the user on the other hand the REVOKE statement
is used to remove the privileges granted by the GRANT statement. The syntax of the REVOKE is
:
SELECT*FROMCT;
When you will execute the above statement. SQL PLUS will display the synonyms as shown in Fi
9.28.4.
11T___ ____ _
HrH sRL Hex snl
Eiology 5888 9100
Dhenistry 36BB 12295
Computer {708 8960
ll4aths s76B 15206
,f hysics 1S290 2@00
rsQL>
Solved Exercises
Ql. wharisvtEW?
Ans. A view is table that has no data of its own. A view is derived from another table .A view is often referred
to as a virtual table. views are created by using the cREATE vlEw statement.
Q2. What is complex VIEW ?
Ans. A complex vierv is one which is created from more than one table. It can also contain the group function.
Q3. What is purpose of GRANT statement ?
Ans. The GRANT command is use to give permission to one user to access the table of another user or can
do any other desire operation according to the privilege assigned.
Q,l. What is purpose of REVOKE statement ?
Ans. The RIIVOKE statement is used to remove the privileges granled by the GRANT statement.
Q5. What is synonyms ?
Ans. A synonvlns is an another name of table. It refers to the a table owned by another user and used to
shoften the lengthy names.
Q6.Considerthetablegivenbelowandanswerthequestion(a)to(g).
TABLE:EMPI.,IOYEE :
(a) Create a view having the field ENAME and JOB where COMM is NLILL'
(b) Create a view with all the fields of the above table in the ascending order ofthe field ENAME.
(c) Create a view with the fields ENAME and SALARY having salary more than 8000.
(d) Suppose their is another user Rahul and the user of the table EMPLOYEE is Amit' Write a grant
statement to give the select and insert privilege to the user Rahul.
(e) Revoke the privilege given to the user Rahul'
$) Create a synonym ofthe view created in part (a).
(g) Drop the synonym.
Ans. (a) CREATEVIEWEI
AS
SELECT ENAME, JOB FROM EMPLOYEE
WHERECOMMISNULL;
(b) CREATEVIEWE2
AS
SELECT * FROM EMPLOYEE
ORDERBYENAME;
(c) CREATEVIEWE3
AS
SELECT ENAME, SAL FROM EMPLOYEE
WHERESAL>8OOO;
(d) GRANT SELECT, INSERT ON EMPLOYEE TO RAhUI;
(e) REVOKE SELECT, INSERTON EMPLOYEE FROMRahul;
(l) CREATESYNOIM\4 T
FOR EI;
(s) DROPSYNONWIT;
Review Questions
L
Somple Proiect r Mqth Test
lntroduction
This is a mathematical test project. ln this project you can use calculations and can guess your calculation.
While checking your anwer, the project lvill display either correct or incorrect result. You can also change the
mathematical signs, 1.e., when you ciick on the Change Sign button and press Next button at runtime the
mathematical signs will be changed automatically'. Otherwise, you can use the Auto Change Signs RedioButton
to change the sign automatically. In siniply, you can say that this is a general purpose calculator.
To utilize a geneial purpose calculator contarning Math Project, create a fbrm given below :
L,-..i
Name Framel Identifies the frarne.
Label A Name lblNumberOne Identifies the Label.
Caption 0000 Label value.
BackColor White Background Background cclor.
ForeColor &H000000FF& Foreground color.
(643)
;w Saraswati lnformatics Practices (Xl)
I^abd
o- Name imgDiv Bitmaplmage.
o
Label Name lblSign Identifies the label.
Caption + Label value.
BackColor WhiteBackground Background color.
ForeColor &H000000FF& Foreground color.
Label IR Name lblNumberTivo Identifies the Label.
Caption 0000 Label value.
BackColor WhiteBackground Background color.
ForeColor &H000000FF& Foreground color.
l,abel A Name lblEquals Identifies the Label.
Caption Label value.
BackColor WhiteBackground Background color.
ForeColor &Hm0000FF& Foreground color.
Identifies TextBox.
TextBox l6i Narne brtAnswer
BackColor WhiteBackground Background color.
ForcColor &HfiXXNOFF& Foreground color.
EnaHed False Enabled/disabled.
Frame t#ft Narne Frame2 Identifies the frame.
t abel &: Narre lblMessage Identifies the Label.
Capdm Incorrect Label value.
BackCol,or &HfiXXXXMO& Background color.
ForcColor &HfircOOOFF& Foreground color.
forml (MathTest.frm)
Option Explicit
Dirn vnt'Iemp As Vari ant'M u lti purpose/Tern porary Variable
Dim intCourrter As Integer
Dim blnlRAs Boolean
Private Sub Form_Load0
txtAnswer.Text: ",'
txtAnswer.ForeCo lor : RGB (7 l, 96, 220)
cmdNext Click
imgDiv.Visible: False
intCounter:0
blnlR: True
End Sub
'Addition
Private Function Sum(vntA As variant, vntB As variant) As Integer
Sum : Clnt(Val(vntA)) + Clnt(Val(vntB))
End Function
'Division
Private Function Remainder(vntA As variant, vntB As variant) As Double
If Clnt(rd(vntA)) o 0 Then
Remainder : C Int(Val(wtA)) / C In(Val(vntB))
End If
End Function
'Subtraction
Private Function Difference(vntA As variant, vntB As variant) As Integer
Difference : Clnt(Val(vntA) - Cln(Val(vntB))
End Function
'Multiplication
Private Function Product(vntA As variant, vntB As variant) As Integer
Product : Clnt(Val(vntA)) * Clnt(Val(vntB))
End Function
cmdChangeSign.Enabled : False
EIse
cmdChangeSign.Enabled : True
End If
End Sub
'Change Sign
Private Sub cmdChangeSign_Click0
imgDiv.Visible: False
Select Case (lblSign.Caption)
Case t'*"
lblSign.Caption: "-"
Case "-"
lblSign.Caption : "x"
Case "x"
lblSign.Caption: "/"
inrgDiv.Visible: True
IfchkRandomSign.Value o I Then
CallcmdNext Click
End If
Case "/"
IblSign.Caption : '+"
End Select
End Sub
'Number Buttons I
'GenerateNext Problem
Private Sub cmdNext_Click0
Dim vnfTemp As Integer
EnableButtons
t If chkRandomSign.Value: I Then Call cmdChangeSign_Click
DisplayMessage "Math Test", 71, 86,220
txtAnswer.Text: ""
'. Startloop:
" For vntTemp = 0 To Val(Right$(Time$,2))
lbNumberOne.Caption = Right$(Rnd(300), 2)
lblNumberTwo.Caption = Right$(Rnd(400), 2)
Next
If Val(lblNumberOne.Caption) < Va(lblNumberTwo.Capion) Then
vntTemp = Val(lblNumberOne.Caption)
il8 Saraswati lnformatics Practices (X!) r
lblNumberOne.Caption: lblNumberTwo.Caption
lblNumberTwo.Caption : vntTemp
EndIf
If lblSign: "/" Anci Val(lblNumberOne.Caption) _
Mod Val(lbNumberTu'o.Caption) <> 6 Then GoTo Startl,oop
IfVal(lblNumberTwo.Caption) < 3 Then GoTo Startloop
If lblNumberOne.Caption : lblNumberTwo.Caption Then GoTo Startloop
End Sub
'Display Answer
Private Sub cmdAnswer_Click0
DisableButtons
DisplayMessage "Math'I'est", 7, 86, 220
Select Case (lblS ign.Caption)
Case "*"
txtAnswer : Sum(lblNumberOne.Caption, IblNumberTwo.Caption)
Case "-"
txtAnswer : Difference(lblNumberOne.Caption, lblNumberTwo.Caption)
Case "x"
txtAnswer : Product(lblNumberOne.Cap\, lblNumberTwo.Caption)
Case "/"
txtAnswer = Remainder(lblNumberOne.Caption, IblNrrmberTwo.Caption)
End Select
End Sub
'Check Answer
Private Sub cmdCheckAnswer_Cl ickQ
DisplayMessage "Incoirect", 25 5, 0, 0
Select Case (lblSign.Caption)
Case "*"
If Val(xtAnswer.Text) + Sum(lbNumberOne.Caption, lblNumberTwo.Caption) Then
Exit Sub
Case "-"
IfVal(txtAnswer.Text) o pifference(lblNumberOne.Captio4,lblNumberTwo.Caption) Then
ExitSub
Case
t'x"
If Val(txtAnswer.Text) + Product(lblNumberOne.Caption, lblNumberTwo.Caption) Then
Exit Sub
Case "/"
I f Val(Left $(*tAnswer. Text, 5 )) a
'Check Enter
Private Sub txtAnswer_KeyPress(KeyAscii As Integer)
IfKeyAscii: l3 Then
KeyAscii:0
cmdCheckAnswer Click
EndIf
End Sub
'Display Messages
Private Sub DisplayMgssage(strMessage As String, colorRed As Integer,
eolorGreen As Integer, colorBlue Aqlnteger)
lblMessage.ForeColor = RGB(colorRed, colorGreen, colorBlue)
lblMessage.Caption : strMessage .
End Sub
Run the Math Test using Run >> Start or F5 function key. Thc follo',ving window will appear ;
.!.j,_J
SQL *Plus commands are entered one line at a time and are not stored in the SQL buffer. The listing shows to
modifo commands in an existing command.
Command Description
A[PPEND]rext Adds text to the end of the current line.
C[HANGE]/oldlnew Changes oldtextto new in the curent line.
C[HANGE]#extl Deletes /e-xl l]om the current line.
CLIEAR]BUFFIER] Deletes all lines fiom the SeL buffer.
DEL Deletes current line.
IINPUT] lnserts an indefinite number of lines.
IINPUT] rexr Inserts a line consisting of text.
L[ST] Lists all lines in the SeL buffer.
L[ST] n Lists one line (specified by n).
Lnttsr)mn
3"'#,ffiffi"i,1,1ilJ:#3, r0. starement in the buffer.
n text Replace line n with rerr.
0 text Inserls a line before line l.
Guidelines:
- If you press [Return] before completing a command, SQL *Plus prompts you u,ith a line number.
- You terminate the SQL buffer by either entering one of the terminator characters (semicolon or
slash) or pressing [Return] twice. You then see the SeL prompt.
Appendix B
SQL statements communicate with the Oracle Server. SQL +Plus commands control the environment format
query results and manage files. The following command is used to handle SQL commands as in file.
Command Description
SAYlElfilenamel.extl Saves current contents of SQL buffer to a file. Use APPEND to add to an
IREPILACE]APPIEND] existing file; use REPLACE to overurite an existing file. The default
extension is .sql.
GETfilenamef.extf Writes the contents of a previously saved file to the SQL buffer. The
default extension for the filename is .sql.
STA[RI]l/eramef.exlf Runs a previously saved command file.
@filename Runs a previously,saved command file (same as START).
ED[f[ Invokes the editor and saves the buffer contents to a file named afiedt.buf.
EDUTI lfilenamef.extl lnvokes editor to edit contents of a saved file.
SPO[O[,] ffilenamei.extfl Stores query results in a file OFF closes the spool file. OUT closes the
OFFIOUTI spool file and sends the file results to the system printer.
EXIT Leaves SQL *Plus
(651)