Anda di halaman 1dari 218

Chapter - 21

Common Diqlog Box Controls

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
:

D Common Dialog Control.


o DialogBoxes.
tr Custom Conffols.
o Imagelist Confrol.
o ImageCombo Contro.
o Toolbar Control.
. Status bar control.
D Medi4 Player Control.
To work with these controls in the Form, add them in the
Toolbox. To add,
D ClickProjectmenu.
D Choose Component option or click Components menu
option as
shown in Fig. 2l.l.The Components dialog box will appear
as shown
inFig.27.3.
G
D Right click on Toolbox and click on components from the context
menu as shown in Fig. 2l.2.The Components dialog box will
appear as
shown in Fig. 21.3.

Fig.21.1 Components in Project menu.

(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'--

Fi9.21.2 Components option in right click context menu.

. 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

: [4icrossft calenddr CDntrol 8,0


f,licrosoft Chort (ontrol 6.0 (oLEoB)
f4icrosoft Confi control 6,0

E':
Ebl'

J..:

Fi1.21.3 Gomponents dialog box.


From the above Fig. 2l .3, select the Controls tab and click the vertical scroll bar. Then,
O Select Microsoft Common Dialog Controls 6.0.
O Click on Apply or OK.
You will notice that the Microsoft Common Dialog Controls are added to the toolbox
as shown inFig.2l.4.
Fi1.21.4 Common controls in Toolbox.
21.2 Common Dialog Contro!
While creating an application you may want to open a file, print a file, change
itsw font style , etc.lnVisual Basic
this type of functionality in the application is created with commonDialog
control.
The CommonDialog control provides a standard set of dialog boxes for operations
such as opening and
saving fiies. setting print options, and selecting colors and fonts. The control also
has the ability to display
help by running the windows Help engine, i.e.,the windows DLL commandlg.dll.
The CommonDialog control can display the following dialogs using the specified
method as listed in
Listing 21.1.

Listing 21.1 CommonDialog methods.


Method Dialog Displayed
ShowOpen Show Open Dialog Box
ShorvSave Show Save As Dialog Bor
ShowColor Show Color Dialog Box
ShowFont Show Font Dialog Box
ShorvPrinter Shou, Print or Print Options Dialog Box
ShowHelp Invokes the Windows Help Engine
21.2.1ShowOpen & ShowSave Method
The CommonDialog control allows you to access existing files or save new files
through its CommonDialog
boxes.
The Open and Save As dialogs are displayed by using the ShowOpen and
ShowSave methods of the
CommonDialog control.
Both dialog boxes allow the user to speci! a drive, directory, filename extension,
and a filename. The Save
As dialog is identical to the open dialog in appearance, except forthe dialog's caption.
At run time, when the user chooses a fi[e and closes the dialog box, theiileliame property is
used to get
the selected filename.
You can set the Filter property so the dialog displays only certain
O?es of files, such as text files. The
Flags properly can be used to change various elements on the dialog as well
as prompt the user when certain
actions may occur, such as overwriting a file.
Before using ShowOpen and ShowSave method, add the RichTextBox control to
the ToolBox. To add
RichTextBox control,
D ClickProjectmenu.
tr Choose Component option or cl ick Components menu option (Fig. 2 I . 1) or right
click on Toolbox and
click on Components from the context menu (Fig. 2l .2).TheComponents dialog box will
appear as
shown in Fig. 21.3.

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

Fig.21.5 CommonDialog control with Filter type.


3. You can also set the InitDir property to specify which directory contents will be displayed by default.
4. Select the RichTextBoxl and add on the form in such a way that it covers the whole form. Set the
Visible property of the RichTextBoxl as False as shown inFig.2l.6.

fextBort RichText&t:

,ebr,*u*t'1 ,':;,.
dbirdex 0
nbrtoF Trae

RiehTExtRoxl
oelTipTExt
B

F,ire

Fig. 21.6 RichTextBox control with Filter type.


Now add a command button and change the caption as Open as shown inFig.2l.7 .
€e Saraswati lnformatics Practices (X!)

Fig.21-7 command button open for Showopen method (textFile.frm).


To illustrate the Showopen method set the object properlies as shown in listing 21.2.

Listing 21.2 Obj ect properties.


Object Icon Properf property setting Property description
form Name TextFile Identifies the form.
Caption NotePad Form title bar display.
CommonDialogl Name CommonDialogl Identfies the dialog.
Filter *.txt Opens only text files.
RichlbxtBoxl
ffi Name rfftxtBox Identifies the text box.
ScrollBars 2-rtfVertical Sets to scroll text.
Visibile False Visible for the user or not.
Open button ,;;f Name ondOpen Identifies Open button.
Caption Open Text that appears on button.
When you have finished designing, you have to a<Id code for the cmdOpen command button.. Ope;r the
code window or double click the Open button for writing the code. Here code is added for cmdOpen command
control in the Click( ) events as :
' Steps to open a .txt file
Private Sub cmdOpen_Click0
tfTextLox.Visible = True
' Set f,rlters.
CommonDialog I .Filter = "Text Files (,r.fi t) x.txt "
I

CommonDi alog LShowOpen


rfTextBox.LoadFile (CommonDialog l.FileNarne)
End Sub
Common Dialog Box Controls 439
After writing codes for Open command button, save the file (textFile.FRM) and press F5 or click start
button to run the CommonDialog control application. When you run the application, the output screen will
display a screen as shown in Fig. 21.8.

Fig. 21.8 Run time view of CommonDialog application.


From the above Fig. 21.8, click the Open button where the Open dialog box will be appear as shown in
Fig.2l.9.
# i*:t.

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

Fig.21.9 Open dialog box for ShowOpen method.


Here,
tr select a drive from the drop-down arrow
tr Click on a file.
D Press Open button.

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

Thaafoe P.T.M. will ba held on tle lasl Sd.urday ol evay month.

we reejest you to please sttend the P.T-M ae mentiMed

Fig. 21.10 Text file through ShowOpen method.


Similarly, to save a file with a specified name, add a Save button to the application. At run time you can save
the text file using the ShowSave method. Now, open the file and add a Save button as shown in Fig. 21.11.

Fig.21.11 Command bufton Save for ShowSave method.


Here, change the Name properties as cmdSave and Caption as Save. The ShowSave method displays the
Save dialog box and the syntax is as :

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

ThetBfore P T.M will be held on the last Saturdey ol every mcrnth

tequast you ro plea;e attend the P.T.M as menlioned.


'rve

Fig.21.12lnserted line after Iast line in Letter.txt file.


Now, press the Save button to save the changes made in Letter.txt file. When yop click the Save button the
Save As dialog box will be appear. Here, you can save the file with the same name or by giving some other name.

21.2.2 ShowFont & ShowColor Method


To provide the text formatting facility in the application you need to use rhe ShowFont method of the
CommonDialog control. Using this method you can change the font, size, style and color of the text. The syntax
of ShowFont method is as :
object.ShowFont
Before you use the ShowFont method, you must set the Flags propefiy of the ComrnonDialog control to
one of three constants or values: cdlCFBoth or &H3, cdlCFPrinterFonts or &H2, or cdlCFscreenFonts or
&Hl' If you don't set Flags, a message box is displayed advising you that "There are no fonts installed," and
a run-time eror occurs. The Flag property of ShowFont method retums or sets the options for the Font dialog
box. The syntax is as :

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.

Listing 21.3 Value settings for font dialog box.


Constant Value Description
cdlCMNSIOnly &H400 Specifies that the dialog box aliows only a selection of the fonts
that use the Windows character set. If this flag is set, the user
won't be able to select a font that contains only symbols.
odlCT'Apply &rr200 Enables the Apply button on the dialog box.
cdlCFBoth &r13 Causes the dialog box to list the available printer and screen
fonts. The hDC propeny identifies the device context associated
with the printer.
442 Saraswati lnformatics Practices (Xl)
cdlCFEffects &H100 Specifies that the dialog box enables strikethrough, underline.
and color effects.
cdlCF'FixedPitchOnly &H4000 Specifies that the dialog box selects only fixed-pitch fonts.
cdlCFForceFontExist &HI0000 Specifies that an error message bor is displayed if the user
attempts to select a- font or style that doesn't exist.
cdlcFHelpButton &H4 causes the dialog box to display a Help button.
cdlCFLimitSize &H2000 Specifies that the dialog box selects only font sizes within the
range specified by the n{in and Max properlies.
cdlCFNoFaceSel &H80000 No font name selected.
cdlCFNoSimulations &H1000 Specifies that the dialog box doesn't allow graphic device
interface (GDI) font simulations.
cdlCFNoSizcSel &H200000 No fonr size selected.
cdlCFNoStyleSel &H100000 No sryle was selected.
cdlCFNoVectorFonts&H800 Specifies that the dialog box doesn't allorv vector-font selections.
cdlCFPrinterFonts &l'12 Causes the box to list only the fonts supported by the
lr1rlo.q
printer, specifieciby the hDC propefty.
cdlCFScalableOnly &H20000 Specifies that the dialog box allows only the selection of fonts
that can be scaled.
cdlCFScrecnFonts &Ht Causes the dialog box to list only the screen fonts supported by
the svstenr.
cdlCFTl'Only &H40000 Specifies that the dialog box allows only the selection of
TrucType fonts.
cdICFWYSIWYG &H8000 Specifies that the dialog box allows only the selection of fonrs
that are available on both the printer and on screen. lfthis flag is
set, the cdlCFBoth and cdlCFscalableOnly flags should also be
sct.
For example.

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,

Common Dialogl .Flags : &1121 0&


'tb ilh'rstrate the ShowFont rnethods, open the plevious NotePad application'and add a cornmand button
Font. Set the Name properties as cmdFont and Caption as Font. You rvill see the fonn as shown in Fig. 21.l3
Common Dialog Box Controls M3

''*,-. . -','" .. .-., .j

Fig.21.13 ShowFont method in NotePad application (textFont.frm).


When you have hnished designing for Font command button. Open the code window or double click the
Font button for writing the code. Here code is added for cmdFont command control in the Click( ) events as :
' Steps to set ShowFont method
Private Sub cmdFont_Click0
CommonDialog I .Flags = cdlCFBoth Or cdlCFEffects
CommonDialog LShowFont
rtfTextBox.Visible = True
rffTextBox.SelFontName = CommonDialogl.FontName
rdlextBox.SelFontSize = CommonDialog l.FontSize
rtflextBox.SelBold = CommonDialog l.FontBold
rtfTextBox.Selltalic = CommonDialog l.Fontltalic
rtflextBox.SelUnderline = CommonDialogl.FontUnderline
rtflextBox.SelStrikeThru = CommonDialogl.FontStrikethru
rtflextBox.SelColor = CommonDialog LColor
End Sub
After writing codes for
Font commandbutton, press F5
or click start button to ruh the Ms a ateBt Fletrue to
CommonDialog control adiuoted to their chss
wd o
in lhei dassroom
application. Before click on the
we d know parants play a ke
Font button, open the previous inter8clioh and comrminl
Letter.Txt file and using mouse ollsung ArialNarrow
ArnoldBoeD
drag method select text or line herefoe P.T M will he held on Ariba Atrbe LEI
Ptrrowsl
and click the Font button. Like w6 rDquest ,(u tD dE6o" itk Atrows?
other application, a Font dialog "l(E i; . j
box will appear as shown in Fig. Public Schooll

2t.t4.

Fig. 21.14 Font dialog box using ;


ShowFont method.
Similarly, the showcolor method is used to display color
dialog box to change the forecolor and backcolor
of the text' AIso, you can set the custom color for the text.
The synL of showCotor method is as :
objeclShowColor
Here, the obiect refets to the CornmonDialog control
and Showcolor method displays the Color dialog
box' To invoke the color dialog, add a color command
button with Name properties cmdcolor and caption as
Color with previous application as shown in Fig. 2 I . 15

Fig. 21.15 command button coror for showcoror method.


After designing the color command button. open the code
window or double click the color button for
writing the code. Here code is added for cmdcolor command
control in the Click( ) events as :
' Steps to set ShowColor method
Private Sub cmdColor_Click0
CommonDialogl.ShowCoior
rtflextBox.selColor = CommonDialogl.Color
End Sub
After writing codes for Color
command button, press F5 or click
start button to run the
CommonDialog control
application. Before click on the
Color button. open the previous
Letter.Txt file and using mouse
drag method select text or line and ;

click the Color button. Like orher


;
application, a Color dialog box ,

Fig. 21.16 Golor diatog box using ShowCotor method.


Common Dla Box Controls

21.2.2 ShowPrinter & ShowHetp Method


When you create an application you also required to print it. So, when you
create an application by which the
user can create doucmnets, you should also provide the facility to print
it. The Showpiinter method provide
you the facility of printing. The syntax of Showprinter method is as :
object.ShowPrinter
To illustrate the ShowPrinte application and add a command button
Print. as
Set the Name properlies will see the form as shown i nFig.2l.l1

Fig. 21 -17 ShowPrinter method in NotePad apptication (textprint.frm).


When you have finished designing for Print command button. Open the code window
or double click the
Print button for writing the code. Here code is added for cmdPrintiommand control in the
Click( ) events
AS:

' Steps to set ShowPrinter method


Private Sub cmdPrint_Click0
rtrIextBox.Visible = True
CommonDialogl.Copies = 2
CommonDialog I Showprinter
.

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.

Fig.21.18 Print diatog box using Showprinter method.


446 Saraswati lnformatics Practices (Xl)

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.

Listing 21.4 Value settings for HclpCommantl.


Constant Value Description
cdlHelpCommand &H102& Executes a Flelp macro.
cdlHelpContents &l{3& Displays the Help contents topic as defined by the Contents
option in the [OPTION] section ofthe .hpj file. See Remarks
below for information on Help files created with Microsoft Help
Workshop 4.0X.
cdlHelpContext &H l& Displays Help for a particular context. When using this setting,
you must also specif, a context using the HelpContext property.
CdlHclfontextPopup &l 18& Displays in a pop-up window a particular Help topic identified by
a context number defined in the [MAP] section of the .hpj file.
cdlHelpForceFile &H9& Ensures WinHelp displays the correct Help file. If the correct
Help file is currently displayed, no action occurs. lf the incorrect
Help file is displayed, WinHelp opens the corect file. .
cdlHelpHelpOnHelp &H4& Displays Help for using the Help application itself.
cdlHelplndex &l-13& Displays the index ofthe specified Help file. An application should
use this value only for a Help file with a single index.
cdlHelpKey &H l0l& Display's Help for a particular keyword. When using this setting,
you must also specifu a keyword using the HelpKey property.
cdlHclpPartialKey &H105& Displays the topic found in the keyword list that matches the
' keyword passed in the dwData parameter if there is one exact
match. If more than one match exists, the Search dialog box with
the topics found listed in the Go To.list box is displayed. If no
match exists. the Search dialog box is displayed. To bring up the
Search dialog box without passing a keyword, use a long pointer
to an empty string.
cdlHclpQuit &ll2& Noti lles the Help application that the specified Help fi le is no
longer in use.
cdlHelpSetContents &H-5& Deterrnines which contents topic is displayed when a user presses
the F'l key.
cdlHelpSetlndex &l-15& Sets the context specified by the HelpContext property as the
current index for the Help file specified by the HelpFile property.
This index remains current until the user accesses a different
Help file. Use this value only for Help files with more than one
index.
Common Dialog Box Controls 447

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.

Fig. 21.19 ShowHelp method in NotePad application (textPrint.frm).


When you have f,rnished designing for Font command button. Open the code window or double click the
Font button for writing the code. Here code is added for cmdFont command control in the Click( ) events as :
'Steps to set ShowHelo method
Private Sub cmdHelp-Click0
rflextBox.Visible = True
CommonDialogl.HelpFile = "editor.hlp"
CommonDialog l.HelpCommand = cdlHelpContents
CommonDialog 1 ShowHelp
.

End Sub

21.3 Dialog Boxes


Adialog box is used to exchange information between the program and the user. It is a separate form that is
generally accessed in response to a selection from a menu or a list. Dialog boxes typically contain common
controls, i.e., labels, text boxes, option buttons, check boxes, command buttons, etc. to enter or display
information. A dialog box always open another form in an existing form. For that, the user must load a secondary
form into an existing project or application. The secondary form can be added to an active project through the
Load statement. The form of Load statement is as :
Loadobject
The object placeholder is the name of a Form object, MDIForm object, or control array element to load.
When Visual Basic loads a Form object, it sets form properties to their initial values and then performs the Load
event procedure. When an application starts, Visual Basic automatically loads and displays the application's
startup form.
Similarly, a fotm can be removed from an active project, which
fleeing up memory. The Unload statement is
used to remove a form from active project. The syntax is
as :
Unloadobject

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 ,,

Msg : Msg &,,and leave it invisible.,,


Answer: MsgBox(Msg, vbyesNo) . Get user response.
lf Answer: vbYes Then , Evaluate answer.
Show ' If Yes, show form.
Ese
LoadForml ' If No,just load it.
Msg = "pomI is now loaded. Choose OK to display it."
MsgBox Msg ' Display message.
Show ' Show form.
End If
End Sub
Loading a form into an active project does not in itself cause
the form to be visible. To make the form
visible, we use the Show rnethod; r. e.,
Form.Show
Or
Show
So, to use a dialog box application, create a menu with
with Continents, Text Color. The sub-menus ofthe
given menu's are as follows :

Continents Text Display


Africa Color...
Antarctica Font...
Asia
Australia
Europe
Norlh Arnerica
South America
Whenever you select any of the Continents, Text Display, it will ask you to enter its area in another form or
in another dialog box. Design the menu as shown in nig.
i t .-ZO.
....&Sfrirc
..'.4&nfantira
.'..4&5ia
',,.A&.ls*afia
.',.&E$opB
'...&l,lorth &merice
",,50u&th Amerira
IEYI Rirpla).

Fig.21.2O A simple menu for dialog box application (frmDialog.frm).


When the application is executed, the primary form will show a menu bar with two entries : Cgntinents and
Text Display. The primary form and the accompanying Continents menu is shown hFig.2l.2l.

F19.21.21A primary form with two menus.


After creating an application, it is now time to add new form for every menu options. Here, when we click
on Africa, it should be open another form for entering the area ofthe specihc option.
Visual Basic provides a variety of templates for creating common application components. Rather than
creating all the pieces of your application from scratch, you can customize an existing template. You can also
reuse custom components in multiple applications by creating your own templates.
You can open an existing ternplate by selecting its icon in the Add Object dialog box when you create a new
form, module, control, property page, or document. For example, Visual Basic provides builrin form templates
for crealing an About dialog box, options dialog box, or splash screen. To add a form,
O ClickProjectmenu.
tr ChooseAddForm.
Or
D Click Add Form icon from standard toolbar.
450 Saraswatilnformatics Practices (Xl)
After selecting the option, a Add Form dialog box will appear as shown in Fig" 21.22.

6ji :tfit 1. *>

Fig.21.22 Add Form dialog box to add a new form.


From the above figure, click on the Form icon and click Open button. A new form Forml will be appear as
shown in Fig. 21.23.

Flg. 21.23 A new form Forml on existing proiect.


In order to utilize the secondary form as a dialog box, we add a label, a text box and a command button, as
shown in Fig.2l.24 and Listing 21.5 shows the object properties.
Fig.21.24 Design screen of secondary form.
Listing 21.5 Object properties.
Object Ion hoperty Propertysetting Property description

form Name Forml Identifies the form.


Caption DialogBoxes Form title bar display.

Quit button ,:-i Name cmdQuit Identifies Quit button.


Caption Q'uit Text that appears on button.
form Name Form2 Identifies the form.
(hption ContinentArea Form title bar display.
Label ,i&1 Labell Labell Identifies the Label.
TextBox Name Texl1 Identifies TextBox.
*.bl'
Fmt Ms San Serif FontforTextBox.
0-LeftJustified Justifying text within textbox.
Close button cmdClose Identifies Close button.
Close Text that appears on button.

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

After writing codes, save the Forml with frmDialog.frm and


Form2 with frmDialogl.frm amd press F5 or
click start button to run the Dialog Boxes application. when you
run the application, the output screen will look
likeFig.21.25.

Fig. 21.25 Form2 dialog box under Forml dialog box.


rts3
Now let us turfl our attentions to the second of the two menus (l. e. Text
, Display) in the primary form and
its dialog boxes. For the second menu, we need to add two difJerent
forms line Colors and Fonts using dialog
boxes' Like adding Forms, dialog boxes can also be added to forms.
For that, we need to add two additiona
forms to our previous project. To add a dialog box,
D CJickProjectmenu.
O ChooseAddForm.
Or
D Click Add Form icon from standard toolbar.
After selecting the option, a Add Form dialog box will appear as shown in Fig.21.26.

.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.

Fi1.21.28 Form design window for Text Displays Colors... options.


Listing 21.6 Object properties.
Object Ion Property Property setting Property description
form Name Dialogl Identifies the form.
C-aption Colors Form title bar display.
tharne Name Framel Identifies the frame.
Caption TextColor Frame title bar display.
@ion tr Name Optionl Identifies the Optionl.
CaplioNl Rd Option value
Option Narne Option2 Identifies the Option2.
Caption Green Option value
Option Name Option3 Identifies the Option3.
Caption Yellow Option value
Frame Name Frame2 Identifies the frame.
Caption Background Color Frame title bar display.
Option 40' Name Optionl Identifies the Optionl.
Caption Rd Option value
Option Name Option2 Identifies the Option2.
Captirn Blue Option value
Option f# Nanrc Option3 Identifies the Option3.
Caption Grey Option value
OK button Name OKButton Identifies OK button.
Caption or( Text that appears on button.
Cancel button Name CancelButton Identifies Cancel button.
Caption Cancel Text that appears on button.
Common Dialog Box Controls 455

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.

@ion ni Name Optionl Identiires the Optionl.


Caption 8- Point Option value
Option ff:; Name Option2 Identihes the Option2.
Caption 10 - Point Option value
Qtion Name Option3 Identifies the Option3.
Caption 12 - Point Option value
OK button Name OI(Button Identifies OK button.
Caption OK Text that appears on button.
Cancel button Name CancelButton Identifies Cancel button.
Caption Cancel Text that appears on button.
Now let us consider the relationship between the primary form and these two dialog boxes. The Text
Display menu in the primary form has the following two event procedures associated with it.
Private Sub mnuTextColor_Click0
Dialogl.Show
End Sub
Private Sub mnuTextFont_Click0
Dialog2.Show
End Sub
The first event procedure causes the Colors dialog box to be displayed when the user selects Color from
the Text Display menu. Similarly, the second event procedure causes the Fonts dialog box to be displayed when
the user selects Font from the Text Display menu. The actions taken by the Colors dialog box are controlled by
the following event procedures, associated with the OK and Cancel command burtons. Visual Basic has
constant identifiers like vbRed, vbBlue, vbBlack, etc.thatrcpresent the colors red, blue, black, etc. respectively.
456 Saraswati lnformatics practices (Xl)
When you have finished designing, you have to add code for Text Disptay menus Colors... and Fonts...
options. Open the Dialogl tbrm and double click on OK command button to write codes for Colors... option.
' Steps for Colors option of Text Display menu
Private Sub OKButton_Click0
If Option l.Value : True Then
Form2.Label LForeColor : vbRed
Form2.Text I .ForeColor : vbRed
Elself Option2.Value: True Then
Form2.Label l.ForeColor : vbGreen
Form2.Text I .ForeColor : vbBlue
Elself Option3.Value: True Then
Form2.Label l.ForeColor : vbYellow
Form2.Text 1 .ForeColor : vbYellow
End If
If Option4.Value -- True Then
Form2.BackColor : vbRed
Form2.Label I .BackColor : vbRed
ElseIf Option5.Value: True Then
Forrn2.BackColor : vbBlue
' Form2.Label l.BackColor : vbBlue
Elself Option6.Value: True Then
Form2.BackColor : vbMenuBar
Form2.Label l.BackColor : vbMenuBar
End If
Dialogl.Hide
End Sub
Private Sub CancelButton_Click0
Dialogl.Hide
End Sub
The Font Size dialog box works the same way as the Colors dialog box. Open the Dialog2 form and double
click on OK conimand button to write codes for Fonts... option.

' Steps for Fonts option of Text Display menu


Private Sub OKButton_C I ick0
If Optionl.Value: True Then
Form2.Label l.FontSize : 8
Form2.Textl.FontSize : 8
EIself Optionl.Value : True Then
Form2.Label l.fontSize : 10
Form2.Textl.FontSize : l0
Elself Option I .Value : True Then
Form2.Label I .FontSize :20
Form2.Text I .FontSize : 20
End If
Dialog2.Hide
End Sub
Private Sub Cance lButton_C lick0
Dialog2.Hide
EndSub
ll.E7
_v,

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.

21.4 Custom Controls


Custom controls are interactive object mainly added in the form to increase the user interaction with the
application. There are various types of Custom Controls available in Visual Basic. In this section we will
discuss
some of the custom controls are as :

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

l,licrosolt ?dindowg ftrrnmorr lcntrols-) 6,rl


tr r*,
l'litrlsoft lrt/insrrrli C8rlltol 5 U
D Choose Component option or i,,t5Flex'Sr id 1r1.;r:ard
click Components menu irlSlnfo I'.15[A!i C;ieqori 66!11;
option. The Components i. r tl5lnfa t.l5liDROt"1 Category mudule
diaiog box will appear ii NStnf,: OLeReq Ca[egory mrdr:le
i-.ihutrnfo Prinl Caieqrr:, nodule
as shown in Fig. 21.30.
rexi
---fl
Caned, ll
''

,'I4i*66i3ft
.i i:'
'drindorvs rarnnxrri'i*r*ioti n,r: .",

\ffi r

Affii
I

Fig.21.30 Components dialog box.


From the above Fig. 21.30, select the Ccntrols tab and click the vefiicatr sci-oll bar. Then.
tr Select Microsoft Windows Common Controls 6.0.
A ClickonApplyorOK.
You will notice that the Microsoft Windows Common Controls are added to the toolbox as
shown in Fig. 2l .3 1.

Microsoft windows
common controls

Fig. 21.31 Commsn controls in Toolbox.


458 Saraswati lnformatics Practices (XI)

21.4"1 lmagelist Control


ActiveX control knagelist loads and stores a group of irnages for use by user controls. Imagelist ( ffi )is one
of several ActiveX controls that ,ire added to the project when Microsoft Windows Comrnon Controls 6.0 is
selected in the Components dialog.
Like Timers and Common Dialogs, Imagelist controls are visible only at design time. lb create an
Imagelist,
tr Sran with a nu'uv project.
tr Add an lmagel-ist control by double-clicking on it from the Toolbox. You can place the conffol
anywhere, because it is not visible at run time.
tr You can shift the coiltrol by dragging and dropping it at required location as shown inFig.2l.32.

Fig. 21.32 lmageList control at design time (frmlmage.FRMi.


O Right-clicking the Imagef-ist control displays a popup menu.
D Selecting Properties displays the Imagel-ist's Property Pages dialog box as shown in Fig. 21.33.
The Property Pages d.ialo-u bcx contains three tabs : General. Lnages and Color.

Loads and Loaded


rmages are
displayed here
Loads an image Tota.l number of
fir+rue
into the control rrnages

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.

Lrrric,.'i !:'ic!r:r,- i iraal;r tc,;r,t: f-

Fig. 21.35 intageList Property Pages dispEaying a toaded image.


Similarly, inserl another four images as
shown in Fig. 21"1i5. Each image was acided
individually h.i pressing Insent Picture....
;.16114; i*r*ger i :-3,.,;
Pressing OK (or Apply when it is enableC)
;i+.r**i!;*eg:
closes the Property Fages dialog.
' lade.t fi** i-l*:::

Fig. 21.36 lnmageList Property Pages dlsplaying six lmages.


450 Sarrswati !nformatics Practices (Xl)
The following options are rhe other properties of Pr:operty Pages :

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.

Fig.21.37 lmagelist Property Pages Color tab"


tl To change any of the color proper[y. select the color from the Color Palette and click on Apply. For
example to change the MaskColor propefty, select it and click a color like ToolTip irom Color Palette
box and click on Apply.
tr After you finish. click on OK ro close rhe Property pages dialog box.
21.4.2 lmageCombo Control
An ImageCombo control is similar to a standard Windows combo box control, with some important differences.
The most visible difference is the ability to include pictures with each item in the list portion of the conibo. By
using graphic images, you can make it easier for the user to identifv and choose items from a list of possible
selections.
A less vjsible though equally irnpoftant difference is the rvav the XmageCombo manages the list portion of
the control. Each item in the list is a Comboltem object, and the list itself is the Conlboltems collection of
objects. Tl-ris facilitates list management, rnaking it eas1, 1s access items individually or collectively, and assign
or change the properties thzrt Cetermine item content and appearance. This structure also rnakes it easier to deal
with the images assigned to list items.
Becatlse the items in the list are objects in a collection. certain properlies found in the standard combo box
(such as List. Listlndex. and ItemData) are no longer required. Therefore, these properties are not present in the
ImageCombo control.
Each item in an ImageCombo list can have two pictures associated s,ith it. The first picture, as specified by
the Irnage property, appears in the drop-down portion of ttLe control next to the text of the list item. The
Sellmage property specitles the list item's picture wtren it has lteen selected frorn the list. The Sellmage picture
appears next to the item in the edit portion of the combo box, as well as in the list poriion.
To manage the images used f'or the Ust items, the ImageCombo uses the Imagelist cornmon control.
Images are assigned to items in the ImageCombo through an index ol key value that references a picture stored
in the Imagelist control.
The IrnageCombo contrril also suppofls multiple levels of indentation. The amount of inclenration is a
property of the individual list item, so items mainta.in their level of indentation even if the list is reordered.
Having iterns indented at different levels makes it possible to ernphasize cer.tain parts of the list ol display
hierarchical relationshi ps.
461
'fo add an fmageCornbo,

n Open our previous exampie of Imagelist.


tr Add an tmagecombo ( ) control by double-clicking on it from the Toolbox as shown in Fie. l3g.

Fig.21.38 lmageCombo control at design time.


tr Click on Text property as "pictures,,.
D Now right-click on the ImageCorntro, click on Properties option to invoke the property pages
dialog
box. From the General rah, set the rmagelist as rmagelistl as shou,n inFig.
21 .39.

6enau rnnr
I i Ccdc,, I F,rr,re j

Fig. 21.39 property pages dialog of lmageConlbo.


O After setting the options 1br Property Pages click on Apply or OK to ciose the dialog box.
To display the images, add Label controi arrcl Image control with the following
as given in Fig. 21.40.
"462 Saraswati lnformatics Practices (Xl)

Fig. 21.40 Form designing window lmageCombo. {frmlmComb.frrn).


The image items are added at iun tinie using the Add rnethod of Comboltems. the fonnat is as :

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.

Listing 21.8 Comboltems Add method.


Part Description
object An object expression thai evaluates to an object in the Applies To list.
Index Optionatr. The position within the collection to create the new object.
Key Optional. A unique string which identifies the item within the collection, May be used in
place of Index Io designate the object.
Text Optional. The text of the item. as it wiil appear in the list and text portions of the combo box.
Innage Optionai. An index or key into an Imagelist control that identifies the pictureto use with the
listitem.
Sellntage Optional. An index or key inio an Imagelist control that identifies the picture to use with the
list item when it is selected.
Indentation Optional. The level of indentation that will be applied to the item. The amount of space
applied to each level of indentation is determined by the Indentation property.
Comboltem A reference to the new Comboltem object returned as a result of the successful completion
of the function.
When you have finished designing, you have to add code for the Form_Load0 and ImageCombo. Open
the code window or double click on the forrnfor writing the code. Here code is added for form in the Load0
events as :

Private Sub Form_LoadQ


Set ImageCombol.Imagelist = Imagelistl
Dim picture As Comboltem
Setpicture = ImageCombol.Comboltems.Arid(1., "Cat", 1, 1, 1)
Set picture = ImageCombol,Comboltems.Add(2, , "Duck", 2.3,1)
Setpicture = ImageCombol .Comboltems.Add(3, , "Dogs", 3,3, 1)
Set picture = ImageCombol.Comboltems.Add(4, . "Swan ',4,4, 1)
Set picture = ImageCombo I .Comboltems.Add(5. , "Camel", 5, 5, l)
End Sub
Private Su.b lmageCombo I _Ciiek()
If Ima_reCombo LSeiecterlltem. lniJex = 1 Then
hnage l.picture = LoatiPiciure(',H:\vbcl i I \cat.bmp',)
EndIf
If ImageCombol.Selectedirem.Index = 2 Then
Iinage l .picture = LoadPicrure(',H:Wbcl l I \duck.bmp,' )
End If
If IrnageCombol.selectedltem.trndex = 3 Then
Imagei.pictrrre = Lo;rdpicture("H;\i,'bcll l\ciogs.bmp")
EndIf
If ImageCombo i.Selectedlter.lr.Index = 4 Then
Image l .picture = L,oadPicturel "H :W bcl I l \s wan.brnp,, )
EndIf
If ImageCombol.selectedltem.Index = 5 Then
Image I .pi ctui'e = LoadPicture( " H Wbcl I 1 \c am ei.bnrp " )
:

EndIf
Enci Sub

After writing codes for for the


Form_Load0 and ImageCombo. save the
frle (frmImComb"FRM) andpress F5. The
Picture is set as the Comboltem and then
all the pictures are added in IxnageCombol"
Thcn in Ciick$ evenr of ImageCombol,
the picttrres are loaded according to t!:e
index of selected item. For example, when
you select Dogs from the fmageCombol,
then Dogs picture gets loaded in tmagel
as shorvn in Fig.21.4l andFig.2l.42.

Fig.21.4f Run time view of lmageCombo items.

Fig. 21.42 Run time view of lrnageCcmho itenis in lmagel box.


464 Saraswati lnformatics Practices (Xl)

21.4.3 Toolbar Control


A Toolhar control contains a collection of Button objects used to create a toolbar that is associated u,ith an
application.
Typically, a toolbar contains buttons that ccrrespond to items in an application's menu, providing a
graphic interface for the user to access an application's most frequently used functions and commands.
The Toolhar control allows you to create toolbars by adding Button objects to a Buttons collection. Each
Button object can have optionai text or an image, or both, supplied by an associated Imagelist control. You
czur display an image on a button with the Image propefiy, or d,spiay text,with the Caption property. orboth, for
eaoh Button object. At design time, you can add Button olrjects to the control using the Properties Page of the
Toolbar control. At run time, you can add or remove buttons from the Buttons collection using the Add and
Remove methods.
To program the Toolbar. add code to the ButtonClick event to respond to the selected button. You can also
determine the behavior and appearance of each Button object using the Style properl),. For example, if four
buttons are assigned the ButionGroup style, only one button can be pressed at any time and at least one
button is ahvays pressed.
You can create space for other controls on the toolbar by assigning a Rutton object the PlaceHolder style,
then positioning a control over the placeholder. For example, to place a drop-dovrn combo hox on a toolbar at
design time, add a Button object with the PlaceHolder style and size it as wide as a ComboBox control. Then
place a ComboBox control on the placeholder.
Double cJicking a toolbar at run time invokes the Customize Toolbar dialog box, which allows the user to
hide, display, or realrange toolbar bLrttons. To enable or disable the dialog box, use the AllowCustomize
propefiy. You can also invoke the Customize Toolbar dialog box using the Customize method. If you wish to
save and restore the state of a toolbar, or alJow the user to do so, two methods are provided: lhe SaveToolbar
and RestoreToolbar methods. The Change evert, generated when a toolbar is altered, is typically used to
invoke the SaveToolbar melhod.

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.

Fig. 2't "43 lnitia! controls'for Toolbar control.


Common Dialog Box eontrols 465

D Right-clicking the Imagelist controi displays a popup rnenu.


tr Selecting Properties displays the trmagelist's Property Pages dialog box as shown inFig.2l-44.
The Property Pages dialog box corrtains three tabs : General, Images and Color.

Fig. 21.44 lmagelist Property Pages dialog box.


In General tab you have to specify the image size. In the Images tab, you have to insert the picture for the
control. To insert pictures, click on Images tab and

tr Click on Insert Picture button. The Select pictnre dialog box will he appear as shown inFig.21.45.

sxarng-ies Farle Undo


Nel$r:ape Frani*tr* drnaldll
Nee&t Fint. dartald03
0itp fiedrr do*aldt{4
pslnnts ,rtr doneld0S
Vbcll1 Spell 1f donatdlun

Fi1.21.45 lmagelist Propcrty Pages displaying a loaded image.


Here, navigate the directory stlucture, which provides proper image hles (here we take the pictures from H:
drive) and press Open. After pressing Open the Select picture dialog box closes emd the image is then loaded
into the Imagelist conffol. Por example, If ciick on Open.bmp, then the image will be inserted into the Property
Pages as shown in Fig.21.46. The figure shows the results of adding one image to the fmagelist control and
name the Key value as Open or any. The irnage is assigned an index of 1.
Similarly. insert another tluee images as shown inFig.2l.46. Each image was added individually with its
Key value by pressing Insert Picture.... Pressing OK (or Apply when it is enabled) closes the Property Pages
diaiog.
Saraswati lnforrnatics Pracilces {X

Fig. 21.46 rmagelist property pages dispraying four !mages.


m Add an Toolbar ( i*I )controi by doubre-clicking on it frorn the Tooibox.
Note' After double-clicking on the the Toolbar control, the control gets pcsitioned
at the top of the foryn
automaticaliv.
tr Now right-click on tbe Toolbar conuol
as shown in Fig. 21.47.
E Aiier that, the Toolbar prooerties pages
will be displayed with three tabs : General.
Buttons, Pictures.
fi ClickontheGeneralTab.
D From l-he Imagelist propert,,, select
Inragelistl as shown inFig. 2 1.4g
You can also change other properties form
the General tab. After that,

D Click on Buttons tab.

Fig. 21.47 Right-click menu for setting


its lmageList propefty.

Fig. 21.48 Toolbar Property paEes with


General tab.
Common Dialog Box Controls 467

E Click on Inserl Button.


D Set the Key propen-v a-c Open.
tr ToolTip Tex[ as Gpen
D Image as I as showninFrg.2l .49.
Simiiarly add another three buttons with Keys
Save, Print and Help. The Index l,altres v'"'ill
automatically assigned as 2, 3, 4 respectir,ely.
5 Finally press Appll' button or OK
button to clcse Lhe Proi:erty Pages
dialog box.

Fig. 21.49 First button for Toolbar icr lnsert Butten.


You wiil be see that the tooibar has four buttons as sirorvn in Fig. 2 i .50.

Fig. 21.50 lrnage iesns on the Toolbar contro!.


When you have finished designiirg, you have to add code for the Toolbar icons. Don't worry about the
code, because we have already witten codes for command trutton Open, Save, e/c. Just double ciick on the
Toolbar button, a Toolbarl_ButtonClick( " . . ) event procedure will appear. \\rrite the similar codes as we write
in ShowOpen, ShowSave, ShowPrint, ShorvHelp methods. Flere code is as :
Dim mess As String
Private Sub Toolbar l _ButtonCiick(ByVal B uttcn As MSComctll-ib.tsution)
mess = Button.Key
Select Case mess
Case Is = "Open"
' Steps to open a .txt file
rfTextBox.Visible = True
' Set filters.
CommonDi alog 1 .Filter = "Text Fil es ( *.txt) x.txr "
I

CommonDialog 1 Show Open


.

rfTbxrBox.LoadFile (CommonDialog l.FiieNaLrne)


Case Is = "Save"
rdTextB ox.Visibie = True
' Set filtcrs.
CommonDialogl .Filter = "Text Files (*.txt)l*.rxt,,
CommonDiaiog l. ShowS ave
rtflextBox.SaveFile (CommonDialogl
"FileName)
Case Is = "Print"
' Steps to set Showprinter method
rrflextBox.Visible = True
CommonDialogl.Copies = 2
CornmonDialog 1. Showprinter
Case Is = "print,,
'Steps to set ShowHelp method
CommonDialog l.HelpFile =',editor.hlp"
CommonDialogl.HelpCommand = cdlHelpContents
CommonDialog l.ShowHelp
End Select
End Sub
After writing codes for for the Tlrclbarl ButtonClick0, save the file (frmToolbar.FRM)
and press F5. The
NotePad application will be appear with four toolbar buttons as shown
in F ig. 21 .Sl.From the Fig. 2l .5 I , if you
will click on the open button ( ) an open dialog box will be appear as like our previous application. Here,
you can open any .txt f,rle to utilize the Save, print and Help
methods.

Fig. 21.51 Run time \riew o, Toolbar icon.


21.4.4 StatusBar Control
A StatusBar control provides a wirtdow, usually at the bottom of a parent form, through
which an application
can display various kinds of status data. In Visual Basic you
can a,ld the statusbar on your form which can be
used for :

o Showing the database information sucir as number of records.


A Attribute of the text tlisplayed in the RichTextBor.
l, Current status of the key like Cpas Lock and Num Lock.
Common Dialog Box Controls 469

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 :

tr Start with a new project.


3 Add a StatusBar control ( fi )by double-clicking
on it from the Toolbox. The StatusBar will appear
on the buttom of the tbrm as shown in Fig 21 .52.
tr Right click on the StatusBar to invoke the
t;

property dialog bix as shown in Fig2l.53.

Fig. 21.52 Status bar at design time.

tt,...| :.,. :4..'i.:f .'t-, ",,.n:1i a:! ?+j.


?'d*irqrit]'ren*ltl rlirir;.:l rur*rl

Fig.21.53 Property Pages dialog box for ?;

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.

Fig.21.55 Pane! tab with insert paneltext and width.


tr Similarly, add another panel as time by clicking orr the Inseft Panel and setting the Style property
as
sbrTime.
o click on Apply and then press oK. you will see rhe form will looks like Fig. 21.56.

Fig. 21.5G Design window of StatusBar control.


When you have finished designing, you cat execute the StatusBar application.
While executing, you will
notice that the system time will change automaticall;,
Common Dialog Box Controls 471

21.5 Media Player Control


People are rushing to equip their computers for multimedia. Most new compurers are being sold "Multimeda
ready" with CD-ROM drives, audio boards and sometimes with special video capabilities.
Among those users who want graphics. two-dimensional graphics no longer suff,rce. Now many people
want three-dintensional, high-resolution, color graphics. The Media Control Intertace (MCI) provides a
convenient, common API that ciient applications oan use for controlling all multimedia hardware.
Multimedia MCI consisis of a set of highJevel, device-independent commands that control audio and
visual peripherais. The first MCI command you issue is the Open comrnand. This conrmand opens the specilied
MCI device and identifies the file that will play on the device or be recorded by the device" Some devices, such
as CDAudio. VCR, and videodisc, do not use files and do not require file names.
Once the device is open, you can issue any of the other MCI cornmands (Prev, Next, Pause, and so on). The
Close command is the last MCI command you issue for the device, returmng it to the available pool of system
resources. The Close command also cioses the data file associated with the device.
The Multimedia MCI control manages the recordin-e and playback of multimedia files on Media Control
Interface (MCI) devices. Conceptuall,ru, this control is a set of push buttons that issues MCI commands to
devices such as audio boards, MIDI sequencers, CD-ROM drives, audio CD players, videodisc players, and
videotape recorders and players. The MCI control also supports the playback of Video for Windows (*.avi)
hles.
When you add the Multimedia MCI control to a form at design time, the control appears on the form as
follows:
The buttons are defrned as Prev, Next, Play, Pause. Back, Step, Stop, Record, and Eject, respectively, as
shown in Fig. 21.57.

Previous Next Play Back Step Stop Record Eject


Fig.21.57 A MCI button to play with CD-ROM drive.
Your application should already have the MCI device open and the appropriate buttons in the Multimedia
I\ICI control enabled before the user is allowed to choose a button from the Multimedia N{CI control. In Visual
Basic, place the MCI Open command in the Form_Load event.
When you intend to record audio with the Multimedia lVtrCI control, open a new tlle. This action ensures
that the data file containing the recoriied sound will be in a format compatible with your system's recording
capabilities. Also, issue the MCI Save command before closing the MCI device to store the recorderl data in the
file.
Thc Nlultimedia MCI control is programmable in several ways :
tr The control can be visible or invisible at run time.
tr You can augment or completely redefine the functionality of the butions in the controi.
II Ybu can control multiple devices in a form.
If you want to use the buttons in the Multirnedia MCI control, set the Visible and Enabled properties tc
Tlue. If you do not want to use the buttons in the control, but want to use the Multimedia MCI control for its
multimedia functionality, set the Visible and Enabled properties to False. An application can control MCI
devices with or u,ithout user rnteraution.
The events (button definitions.; of the Multimedia MCI contiol are prograrnmable. You can augment or
completely redefine the iunciionality of these buttons by de.,eloping code for the button events.
The MCI extensions support rnultiple instances of the Multimedia MCI control in a single form to provide
concuueni control of severai MCI devices. You use one control per device. The listing 21.10 shows key
properlies and events of Multimedia MCI control.
472 Sar
Listing 21.10 Key features of the Multimedia MCI contro!.
Property or event Descriptiou
Conrmand A string that specifies
the cornmand to execute. possibie values are open, close,
Flay, Pause, Stop, Bac( Prev. Next, Seek, Record, Eject, Sound and Saye.
Device'Ilpe A string that specifies the gpe of device. possible values are AVIVideo, CDAudio,
DAT, DigitalVideo, MMMovie, Othcr, Over!ay, Scanner, Sequencer, VCR.,
VideoDisc and Wavedudio.
Notify when set to Fa lse, th is property disables notification of when the next MCI command
cornpletes. Subsequent MCI commands ig,nore this properly until it is assigned
another valuc.
Shareable Determines if the device can be shared betvreen applications (True) or should be
exclusive to one application (False).
Track Specifies the current track.
Trackl-ength Detennines the length ofthe current track specified by properfy Track.
'fracks Specifies the total number of tracks.
Updatelnterval Specifies the nulnber of milliseconds between calls to the statusUpdate event
procedure.
Wait Determines if the next I\4cl cornmand should complete bef<rre returning control to
the application (True) or if control can be returned before the command completes
(False),
ButtonUnabled Determines if a button on the control is enabled (True) or disabled (False). Button
is one cf Open, Close, Play, Pause, Stop, Back, prev, hlext, Seek, Record, Eject,
Sound and Save.
ButtonYisible Determines if a button on the control is visible (True) or not visible (False). Button
is one of Open, Close, PIay, Pause, Stop, Back, prev, Next, Seek, Record, Eject,
Sound and Save.
Error Specifies the error code retumed fi.om the last MCI command.
ErrorMessage Message for the Error returned from the last MCI command.
Length Specifies the lengh of the meciia opened by the MCI control"
TimeFormdt specifies tire format in rvhich the time infomation is stored for each of the time-
related properlies of the MCI control.
l'rames Number of Frames to move fbr commands Step and Back.
Mode Specifies the mode of the MCI device at execution time. possible values are
mciModeNotopen. mciModestop, rnciModeplay, mciMocleRecord, mciModeseelq
mciModePa use and mciModeReady.
Position Specifies the current position of an open MCt device.
TrackPosition Specifies the current position of the cunent Track.
StafusUpdate called at fixed intervals specified by the Updatelnterval property to allow an
application to update the display and inform the user about the status ofthe
cunent MCI device. Status information can be obtained from properties such as
Position, Length, TrackPosition, TrackLength and Mode.
ButlonClick called when a button on the MCt control is clicked. Builon is one of open, close,
Play, Pause, Stop, Back, Prev, Next, Seek, Record, Eject, Sound and Save.
ButtonCompleted called when a command issued by clicking a button on the MCI control completes.
Button is one ofOpen, Close, Play, Pause, Stop, Back, prev, Next, Seek, Record,
Eject, Sound and Save.
Common Dialog Box Controls 473

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.

21.5.1A Multimedia MCI Csntrol eD Flayer


When the user loads an audio CD into the computer's CD-ROM device, the MCtr Control autornatically enables
the buttons on the MCI control that can be used with auciio CDs. For a standard CD-R.OM containing an audio
CD, the Back, Step and Record buttons are always disabled on the MCI Controi.
To use the llrultirnedia MCI Control, it must hrst be addeci to the toolbox by selecting Cornponents. . . froin
the Project menu to display the Components dialog box. In the dialog box, scroll down and select the option
Microsoft N{ultimedia Control 6.0 as shown in Fig. 21.58. When selected properiy, a small check rnark appears
in the box to the left of the option. Click the OK button when you are done to dismiss the dialog box. The icon
for the Multimedia MCI Control ( ) will be at the bottom of the toolbox.

Donrds Desrg;rers I lnsatable rJ b,;ecls I


I

-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

i'l hliir,rsofi [etulliFi e-dta [1:tLs


i l'{irrasoll l.JetShour Fleyrrr
.iMirrnsofi Of fire \i;'eb Compsnents B.[t
-.l ftcr o!dt cutlifl e
(ontrol
-.lFli':ro:$Fi tutl.-'ui1 E)ipress 5 DT /9t Litr,ir'!
M(ro5i'[t PitlureClig, Contr ol 6.0

LKi

Fig. 21.58 Cornponents dialog box with Microscft Multimedia Control.


To work with Ml\{Control ( ffi ),
tr Start with a New project.
tr Add a N[MControl by clicking on it from the Toolbox and click and drag on the Form. You will bo
noticed that a MCI button placed with Prev, Next, Play, Pause, Back, Step, Stop, Record, and Eject,
respectively.
To illustrate the Multimedia MCI Control. create a project form named CD Flayer with the following
required MMControl, labels and text boxes as given in Fig. 21.59 and the object propelties listing 21.11.
474 Saraswatilnformatics practices (X!)

Fig. 21.59 Forn designing window of Muttimedia MC! controt. (frmGD.frm).


Listing 21.11 Objeet properties.
Object Icon Property Property setting Property description
form Name frrnCD Identifies the form.
Caption CDPlayer Form title bar display.
MMControl Name MMControll Identifies the control.
Lahel A, Labell lblCurrentT[ack Identifies the Labell.
Caption CurrentTfack: Text Label displays.
Label A Labd2 lblTracklength Identifies the Label2.
Caption Track Length : Text Label displays.
Label A Label3 lblTotalTracks Identifies the Label3.
Captiort Total Tracks: Text Label displays.
TextBox Name brtCurrentTlack Identifies TextBox.
TerilBox frbi Name brtT[ackl.ength Identifres TextBox.
TextBox Narne t(TotalThack Identifies TextBox.
When vou have finished designing, you have to add code for the Form_Load event procedure. Open the
code window or double clickin-s on the form as :
' Using the Microsoft Multimedia MCI Control as an audio CD player.
OptionExplicit
Private Sub Form_Load0
MMControll,Notify = False
MMControll.Wait = True
MMControli .Shiueable = False
MMControl I .DeviceType = "CDArrdio"
MMControll.Command = "Open"
txtTotalTracks. Tex t = Formatg (MMControl I Tracks,
. " 00 " )
End Sub
Private Sub Form_Unload(Cancel As Integer)
MMcontrol l.Command : "Stop"
MMControll.Command = "C1ose"
End Sub
Private Sub MMControl l_NextCompleted(Errorcode As Long)
Call Updatelnformation
End Sub
Private Sub MMControl l_prevCompleted(Errorcode As Long)
Call Updatelnformation
End Sub

Private Sub MMControl l_statusUpdare0


Call Updatelnformation
End Sub

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.

Fig. 21.60 Playing an audio CD player


wath CD-ROM Drive.
Solved Exercises

Ql. How will you add CommonDialog Controls on the tocrlbar ?


Ans. To add ConrmonDialog Controls on the Form the following steps is to
be followed :
Click Project menu.
- Choose Componerrt option or click Components menu option. The Components
dialog box will
appeal'.
Select Microsoft Corlmcn Dialog Controls 6.0.
- ClickonAppl.vorOK.
Q2. What is CornmorrDialog Control ?
Ans" The ComrnonDialog control provides a standard set of dialog boxes for operations such
as opening and
saving files, setting print options, and selecting colors and fonts. The control also has
the ability to
display help by running the Wirdows Help engine, l. e., the Windows DLL Cornmandlg
dll.
Q3. List the ComrnonDialog Control methods.
Ans. Following are the ltomrnonDialog methods :

Methorl Dialog Displayed


ShowOpen Show Open Dialog Box
ShowSave Show Save As Dialog Box
ShowColor Show Color Dialog Box
ShorvFont Show Font Dialog Box
ShowPrinter Show Print or Print Options Dialog Box
ShowHelp Invokes the Windorvs FIelp Engine
Q,l. What is dialog Boxes ?
Ans' A dialog box is used to exchange information between the program and the user. It is a separate
form that
is generally accessed in response to a selection liom a *"n, o. a list. Dialog boxes typically contain
common controls, r. e. , labels, text boxes, option buttons, check boxes, command
buttoni, etc. to enter or
display information. A dialog box always open another form in an existing form.
Q5. What is the purpose of Custolx Controls ?
Ans' Custom controls are interactive object mainlv added in the form to increase the user interaction
with the
application.
Q6. What is lmageControl ?
Ans' ActiveX control hragel-ist Ioads and stores a group of images for use by user controls. Imagelist
is one
of several ActiveX controls that are added to the project when Microsoft Windows
Common Conhols
6.0 is selected in the Components dialog.
Q7. What is ImageCornbo Control ?
Ans' An LnageCombo control is similar to a standard Windor,vs combo box control, with some
important
differences. -[he most visible difference is the ability to include pictures with each item
in the tist portion
of the combo' By using graphic irna-qes, vou can make it easier for the user to identi$r
an6 choose items
from a list of possible selections.
Q8. What is1-oolbar Control ?
Ans' A Toolbar control contains a collection of Button objects used to create a toolbar that is associated with
an application.
Typically, a toolbar contains buttons that correspond to items in an application,s
menu, providing a
graphic interface for the user to access an application's most trequently
used functions
andtommands.
The Toolbar control allows lzou to create toolbars by adding Button objects to
a Buttons collection.
Each Button object can have optional text or an image, or both, supplied by
an associated lmagelist
contro I.
Q9. What is StatusBar control ?
Ans. A StatusBar control provides a window, usually at the boltom of a parent form.
through which an
application can display rrarious kinds of staius data. In Visual Basic you can add
the statusbar on your
form which can be used for :
- Showing the database infonnation such as number of records.
Attribute of the text display ed in the RichTextBox.
- Current status of the key like Cpas Lock and Num Lock.
Ql 0. What is RichTextBox Control ?
Ans' A RichrertBox control is a powerful ActiveX control for rnanipulat^ng tert.
Qll" What is the difference between l-oad and Show ?
Ans. Method Load loads a fi'om into mernory but does not display it. N4ethod Show loads a florm into memory
it is is not alreadl, loaded and displays the form
Ql2. What is the difference between Visible: False and Unload ?
Ans. SettingtheVisiblepropeftytoFalsehidestheform,butthefonnstillresidesinmemory,Unloadremoves
the formlrom memory.
Q13. What is the purpose of Multirnedia MCI control ?
Ans. The Multimedia MCI control manages the recording and playback of multimedia fi les on Media Control
interface (lvlCl) devices. Conceptually, this control is a set of push buttons that issues MCI
commands
to devices such as audio boards, MIDI sequencers, CD-ROM drives, audio CD players, videodisc
players, and videotape recorders and players. The MCI control also supporls the playback
of Video for
Windows (x.avi) files.

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

Dqtobqse Concepts ond ADO Controls

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.

22.2File Systems and Associated Problems


Most data processing svsten'ts exists today. especially in India, use files for storing, accessing and manipulating
data. Files are stored typically on magnetic tapes and disks, Nlost o{'the problems with files arise out olthe facr
that files are specific to an application. eg,, a set of files may be desired for the sales analysis system of a
company.
Programs ofthe same application system can use these files. However, if some other nerv application needs
source data ftom this system, there may be difficulties. Therefore, in many cases, new files, with considc-rable
data in common with the existing files, may have to be designed for the new applications.
Therefore. as applications proliferate, the total uumber of cornputerised files grows considerable. Also, as
the number of actual users of the computer grows, the number of appiications increases, in turn resulting in an
increase in the number of files.
A large number of files give rise to the following problerns :
tr Files involve a high level of reciundancy in data. As we lrave mentioned above, proliferation of files,
results in the saine data itent being stored at tnany different places.
C Redundancy in data olten results in inconsistency,of data. The same data itern being used by different
applications may'exist in different versions What is it may exist in different stages of update at
"vorse,
different places aird thus rnay have different valLres ? This may ultimately result in inconsistericies
amongst reports generated by the two application systetxs.
D individual files are not amenabie a rapid changes, especially with respect to the way the data items are
structured within the fi le. If an application wants data from an existing file but slructured differently, it
cannot be provided quickll'and easily, For this purpose, either conversion programs have to be
written or new files have to be createcl.
O Because of the intlexibilitv of flles. rrany ad hoc queries cannot be answered.
f, Yet another consequence of the inflexibility r-,f files is that it is usually expensive to make changes to

(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

22.4 Disadvantages of DBIUIS


The main disadvantages of datalrase systein are :

f, Because of the int'lexibility of files, rnany ad hoc queries cannot be answered"


tr The most signlticant disadvqntage of the DBMS is cost.
n Expensive hardrvare and software rvquit'eme'.tt.
O To implement security'. integrity and sharing of data causes a degradation of the response and
throughput tirnes"
tr The lack of duplication re rliires tiiat the database be adequately backe d-up so tha.t in case of failure
the data oan i:e recovered.
n Centralized control means that the data is aQcessible from a singlq source, naii-rely the database, This
increases the poterrtial severity ofsecurity breaches and disruption ofthe operations ofthg organization
because of downtimes and failures.

22.5 Components of Database


The main components of a databasc managcment system are database users, database administrator and
application programs,
Any person who ean acce ss the database directly using a DBMS is called database user.
Database administrator. t hc DBA rnust be a lnanager, rnore than a technician - seeking to meet the needs
of people lvho use data. Since many users mav share the same data resources, the DBA must be prepared to
mediate conflicting needs and objectives.
Application programs are processes executed by machine.

Query/Prograrr
Process

Storage Access

Application

Database User

Fig. 22.1 Components of DBMS.


22.6ThreeViews of Data
DBMS is a collection ot'reiated information stored which is available to many users. A major purpose of a
database system is to provide users with an atrstract view ofdata. There are three levels ofdata abstraction at
which tlre database mali !s vier,ved.
(a) External view. This is tiic higl-iest level of alrstraction which is seen by the user. This levei of abstraction
describes cnly thcse porli<.rns of the database, u,hich concern with the user or application pl'ogram,
Any number of user vier.r,s rnay exists for a given oonceptual view.
(D) Conceptual view. This is the next higher level of data abstraction. This level describes what data are
stored actually in the database. This level gives information about the entire database. It includes all
the database entil ies and the relationship among them. The description of data at this level is a format
independent ofits physical renresentation. It includes the features whicll perform checks on the data
to maintain integrity and consistency.
482

(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

Iuternal Level Internal View

Fig.21.2 Three Level of DtsMS.


22.7 Data tndependence
As we have.iust seen, files give rise to several problems because they
are application specific. Consequently,
the applications become data dependent. i.e., they depend upon the organizationand
access rnethod for the
data on the secondary storage. This happerrs, because rvith conventional
application development tools such
as CoBoL, the application logic incorporates the i<nowledge of data
organization and acc..r r.ihodr. Therefore,
most changes in data organizations or access methods affect the application
logic substantially. If probtems
arising due to this fact are to be avoided, the data organization ttre a...ess
land strategy) and the application
logic have to be made independent of each other. Data base systems do precisely
this.
The first step towards this goal is to distinguish between data as it actually
stored (called as the physical
representation ofdata) and data as is presented to an individual user (cailed
as the logical representation of
data).
There are two types ofdata independence. They are :

al Logical data independence


tr Physical data independence
(a) Logical data independence' Logical data independence means that the structure
ofdata at logical level
is changed without changing the appiication program. T'he change must
not remove any of the data of
the application program uses.
(6) Fhysical data independence. Physical data independence means that the physicalstructure
ofthc data
may be changed without changing the overall Iogicat structure of the data oithe
application program.
22.8 Dilterent Data Models
A database model allows the capturing of the property of the data structure. So, the data
model describes the
entities and their reiationship. It is a tool to represent the conceptural organizatiorr
of data. The conceptual
model is a communication tool between the various users of data.
The three data models are used for database management system. These
are :
O Relational Data Model
D Hierarchical Data Model
D Netrvork Data model
Database Concepts and ADO Contrels 483

22.8.1The Relational Data fvlodel


The relational model is porverftrl, sirnple, both flexible and natrlral. Data is stored in cr:rnceptual tabies in which
rows are instances anrJ colunrirs are fields. E. F. Codd of the IBM pt'oposed the relaiional model. A relaticlnal
database can contain one ore more tables.
The relational databases have following prope(ies ;
O A relational dafabase appears as a collection oftables (relatious) to user"
tl There is a set of operators for partitioning and combinirig,
. The connections are made on the basis of the data.
tr The user does not need to knorv how the Cata is stored physicatly.
D There is a full data independence.
Let us take a samole cialabase of three tables :

Teacher Studellt
Tno# Tneme Course Title Sno# Sname AEe
T01 Ramaya Clomputer s0l R"onny 17

m2 V.Kr.imar Math s02 \livek l5


T03 iVI. iohn P [t,,'s ic s s03 Sudhakar t'l
TM S. Ghosh Chc'mistiy SM Puneet l8
T05 P. Mafiin Math s05 Kumar 116

Couse

Tno# Sno# Classes

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

FiE.22.3 Relationa! Data Model.


In above tables y'ou have seen that every teacher has unique teacher number and also each student has
been assigned a unique student number and the third table shows that which teacher teaches which student.
So, a relationship is built betrveen the three tables.
As shown above the records in the database are stored in the form oftables. The relationalmodels mean the
processes ofa branch ofuraihematics known as relational algebra. There are some concepts to grasp relational
model. These are :

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.

22.1 1.1 Functional Dependency


An attribute B is functionally dependent on attribute A if every value of A uniquely determines the values of
B. The notation fi'om this functional dependent is
A-+ B
Functional dependency is not necessarily symmetnc
i.e., ifA-+B does not necessarjly imply B A
Consider the following table :

TNo# TName Course Title


m1 Mr. Nayak Computer
TU Mr, Govind Maths
T04 Ms. Meeta Physics
m_5 Mr. Krishna Chemistry

Fig. 22.24 Teachers Table.


Each row in above table represents the particular of the teacher. The primary key in above table is TNo#.
Given any TNo# the value of TName is determined. So, TName is functionally dependent on TNo#. Similarly,
course Title is also functionally dependent on TNo#.

i.e., TName ----- TNo#


Course title ____; TNo#
486 Saraswati lnformatics Practices (Xt)

22.11.2 First Ntormal Form


l he normalization process start rvith first nonral form. A table is in first normal form if
O No t.,vo rows are identical and
A Each table entry is single valued.
If the table contains the repeating group then the relational model becornes complicated. Consider the
following table, which shows the information about student. teacher and their subjects.
Organisation( Studeni- no, Student__name, Course_ no, Course_title, Teacher__name, Grade)

SNo# SName CI\o# Course Title TName T'N(# Grade


Tbpic Subject
s0l Ronny c0r Visual Basic Computer Ramaya T0l A
s02 Vivek CA Optics Physics M. John T03 B
s03 Sudhakar c03 Calculus Maths V. Kurnar TU A
s04 Puneet c'03 Geornetry Maths V.Kumar T02 A
s05 Kumar c03 Algebr-a Maths V. Kumar TA2 A
F ig. 22.4 Organ ization table.
The above table is said to unnormalised because each row contains multiple set of values for some of the
columns. This relation can be nonnalized as shown in the figure given below :

SNo# SName CNo# CTopic CSubject TName TNor+ Grade


s01 RorLny c0r Visual Basic Conrputer Ramaya mi A
s02 Vivek CM Opiics Physiss M. John m3 B
s03 Sudhakar c03 Calculus Maths V. Kumar 7\2 A
SM Puneet c0i Geornetry Maihs V Kumar T02 A
s0s Kumar' c03 Algebra Maths V. Kumar T02 A
Fig.22.51NF Table.
The above table is in first normal fonn. But above relation still suffer some problems :

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.

21.11.3 Second Normal Form


A table is said to be in second normal form if
A lt is in first ncnnai form and
tr Each non - key attribute is functionally dependent on the entire key.
So, to solve the problem associated with the relation given in Fig.22.5 we decompose the relation into three
relations.

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 :

Course(CNo#, CSubj ect)


Teaches(Tno#, CNo#, CTopic)
So, the normalization involve the step wlrich are shown in Fig. given below :

Normalised & Unnormalised relations

INF relations

2NF relations

3NF relations

Fig.22.6 Steps in normalization.


488 Saraswa't! lnformatics Practices (Xl)

22.12 Frsrnt End


A Front EnrI is traditionaliy f6rr65 based. A frlrm being used to capture and validate user data. But it will not
provide the method to store the data entered by the user. Visual Basic is one of the commercial application's
front end. The other application which can be used as a licnt end are : Oracle Developer, Visual Basic,Visual
C++, Power Builder, Delphi etc.

22.13 Back End


As you know that the database is managed by a software package known as database management system.
The database management systenr is generally used to store the data which are provided by the user through
the Front End.'l'he commonly available comrnercially Available back ends are : Oracle, MS-SQL Server, DB2,
MySQL, Sybase, INGRES :

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).

22.15 Microsoft ADO Data Control and Mocrosoft DataGrid Control


Visual Basic provides a variety of data-aware controls for displaying and manipulating data in databases. The
data-aware controls each contain several key properties. In fhis section, we illustrate how simple it can be to
create data-aware applications in Visual Basic. For this purpose, we u,it1 use two controls--the ADO (ActiveX
Data Object) Data Control and the DataGrid control.
The ADO Data Control allows you to quickly create a connection to a database using Microsoft ActiveX
Data Objects (ADO)
At design time, you can create a connection by setting the ConnectionString properly to a valid connection
string, then set the R.ecordSource properfy to a statement appropriatc to the datahase manager. You can a.lso
set the ConnectionString propefty to the narne of a file that defines a connection; the file is generated by a Data
Link dialog box, which appears u,hen you c!ick ConnectionString on the Properties window and then select or
create a Data Link file.
Connect the ADO Data Control to a data-bound control such as the DataGrid, DataCombo, or Datalist
control by setting the DataSource property to the ADO Data Control.
At run time, you can dynamically set the ConnectionString and RecordSource properties to change the
database. Altematively, you can sei ihe Recordset property directly to a previously-opened recordset.
Wheras the DataGrid control disp!ays and enables ciata manipuia.tion of a :ieries of rows and colunms
representing records and fields lrom a Recordset object.
The data-aware DataGri,l control appears similar to the Grid controi; hcwever, you can set the DataGrid
control's DataSource propcrfy to a Data control so that the control is automatically filled and its column
headers set automatically from a Data control's Recordset object. The DataGrid control is really a fixed collection
of columns, each with an indeterminate number of rows.
Each celI of a DataGrid control can hold text values, but not linked or embedded objects. You can specifli
the current celI in code, or the user can change it at run time using the mouse or the arrow keys. Cells can be
edited interactively, by typing into the cell, or programrnatically. Cells can be selected individually or by row.
If a cell's text is too long to be disptayeC in the cell, the text wraps to the next line within the same cell. To
display the wrapped text, you must increase the cell's Column object's Width propefty andior the DataGrid
control's RowHeight property. At design time, you can change the column width interactively by resizing the
column or by changing the column's width in the Colurnn object's propertv page.
a-

AOO
!qv

Use the DaiaGrid control's Columns collection's Count properly and


the R.ecordset object,s RecordCount
propefty to determine the number of columns and rows in the control. A DataGrid
control can have as many
rows as the system resources can support and up to 32767 columns.
When you select a celi, the Collndex propefty is set, thus selecting one of the Cotrumn
objects in the
DataGrid object's Columns collection. The Text and Value properties of the Column object reference
the
contents of the current cell. The data in the current row can be accessed using the Bookmarir
pr.operty, which
provicies access to the underlying Recordset object's record. Each column
of the DataGrid control has its own
font, border, word wrap, and other attributes that can be set without legard to other columns.
At design time,
you can set the column width and row height and establish columns that ere noi r.isible
to the user. you can also
prevent users from changing the formatting at run time
The ADO Data Control manages the connection between an application and a database and
allows the
data-aware controls to view and manipulate the dala in a database. The DataGrid control provides
easy access
to the contents of a Recordset tbr both viewing and editing the data in the database. In this exarnple,
rve
disabled the user's ability to edit the data by setting the AllowUpdate properly of the DataGrid
to False.
When a DataGrid is attached to ADO Data Controt, the DataGrid automatically displays
the rows,
columns and field names for the table attached to the ADO Data Control. Let us now
assemble the program.
The ADO Data Control and the DataGrid control are not intrinsic controls displayed
in the Visual Basic
toolbox, so they must be added. To add these controls to the toolbox,
D Select Components... from the Project menu to display the Components dialo_e box.
fI In the Components..- dialog box, scroll down and select the option Microsoft ADO
Data Control 6.0
as shown in Fig. 21.7.
When the cption is selected, a small check mark appears in the trox to the left of the option.
?
tr Next, scroll down and select the option Microsoft DataGrid Control 6.0 as shown in Fig. 21.7.
Ctick
the OK button when you are done to dismiss the dialog box.

l- L:):1,t1

" : l4irrosolt A.ti\.,elr!ov,e ConlrDl


.: l.licr.roft Artr,,e)i Plugrn
..r, i,'ii(r,rrsrrf I ADO L'ii:n aonf rst 6.0 (O!EDE) J
't
, l'4icr.rsr1'l Aqent iont:rni ?,U

. ; hlirrosrfl: CalenCar Carrtrnl 8.I .l :t*"^


--
I 1."- t
Iuliresof( '-!,;rr: Contror 6.U (r]LEDp)
L-P
I l4icr'lsoit aontor aonlrr{ 6,n

. l',jlcrlsofl Comn:n Dialog Contrnl 6,0


..
11 I lu-d;l
.. -; tticras*fu trats Eu:urrd 6rid Control s.l-l {ip:i)

, . flirre*of[ DEta E8und Lisl (unir+ls O,t)

tli'l osolt []ai:Litt f*ntrrls 6,0 {OLEt!B)


OE.r;..il. I

il
F$frdss[LOnt6€rid Cr'niro]6.ndCL€$S) 1:
-,
to,:1,o0:. {:ir1,iN*o\,s;\IysT::r:rdsflRD.sfi(
-

I--q*I-.>.] ....r:, I rpp,,,1


Fi$.22.7 Components dialog box with Microsoft ADO Data and DataGrid Controls.
The ADO Data Control (
S, ) and the DataGrid Control (,ri|i ) q,ill be rhe iast two conrrols in the toolbox.
Note that when you position the mouse over the ADO Data Control, a tool tip containing Adodc
will appear.
490 Saraswati lnformatics Practices (Xl)

22.15"1 Accessing Database Using ADO


To access the database using the ADO Data Control, we must create a connection to the database. The
database can reside either on the same computer as the program or on the network. To access the database
perform the following steps :
tr Add one ADO Data Control (automatically named Adodcl).
D Now you have to specifv the data source from where it will retrieve the data. So to specify the data
source right click on the ADO Data control. And click on the ADODC Properlies option from the
popup menu. The property page will appear as shown in Fig. 22.8.

Fi1.22.8 Propefi pages of ADO Data Control.


o In the General tab ofthe property page you
will find three options, which can be use to rti:cil*r
create a link with the database. We will select fcolnecllari | *arxrc*o | *it

the Usc Connection String first. So, click on $deel-1he .{aia3ou r.+drt ls tq6r Bt to:

Use Connection String and press Build DLE ltB Fnui$aftl


button. The Data Link Properlies dialog box
f"lir:r,:rofllel 4 D 0t-E 0B Frovidar
appear as shown inFig.22.9. f',Jiciotolt LILE DE Proi,ider lnt lrternel Publi:hrng
tr From the Fig. 22.9, select the Microsoft iet i,frcrosofl fiLE OE Pro,,ida fo DDEC lrrvar:
h.lioor:+ll BLE DE Frovider ltr DLTIP 5errita:
3.51 OLE DB Provider and click on the i{icrorr.ll !lLE DE Provider f,:r tlraule
Connection t"ab. t,1r,:r.r,rtt liLE CtE Prqvider lor 5DL 5er,,er
['lirnsofl 0LE D0 5in'rp]e Fovider
i,l9 Fi*rrrrrle
pr rLidLdrr duE
ilL[ DB l-rc,:ider l':,rr l',1icro;ofl Direclory !ier,..icer

Fi1.22.9 Data Link Properties page.


Database Concepts and ADO Controls 491

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

Fi1.22.10 Data Link Properties Connection tab to select a database'


D From the above Fig. 22.10. cUck on the (.. .) three dots on the right siCe of the option l. Select or enter
a datalrase name where the Select Access Database dialog box will appear as shown tnFig.22.11 .

'r
Lool.in trl

Flle iaffier !Sihli.,

Filal rl lppe j ldirrr:srft A,-^rtss DalaE rtas (- nrdt,l

. oper r as lead-only

Fig.22.11 Select access dialog box for selecting a database.


D Select the database you want tc access from the Select Access Database dialog box (Here, we select
Biblio.mdb) and click Opcn button. And finally click on the OK button ro close the Data Link
Properties dialog box.
Saraswati !nformatics practices
o From the Properly Pages dialo_e box, select the RecordSource
tab.
D Click on Command Type ComboBox and select 2-adCmciTable
, to specify that a table in the database
will be the source of the data as shown inFis.22.12.

fiar,na:li ,4u ** lf"m i


-fte*ord$oflsb -*- -*
S*r*rllend T l

t"
I
I

Fig. 22.12 Selecting a commad type for record source.


fI Now' select Authors from the Thble or Stored Procedure
Name comboBox to specify that the data will
be retrieved specifically from the Authors table in
the database as shown in Fie. 22.I 3.

Fi$.22.13 Serecting a tabre from Bibrio.rndb database.


Note' These propefiies can also be set programmatically to allow
the ADo Data Control to manipulate different
tables at execution time.
D Again click on the General tab and the build button. click
on the Test connection button to determine
' If the c.nnecti.n is successfur, a diarog box appears with the message
') as shown inFrg.22.rr. click the oK burton to aismiss the message. If
the preceding steps.
ntrols 493

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.

Fig. 22.15 Design window to access data from Auther tabre.


c Click on the drop down an'ow of Datasource property of all the 3 three text
box and Select ADODCI .
tr Now select the textBox I and click on the drop down arrow of the DataField properly
and select Au_ID.
Similarly select TextBox2 arrd in the Datalrield property select Author and in TextBox3
select year Bom
as shcwn inFig,22.16.
494 Saraswati lnforrnatics Practices (XI)

,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

Fi1.22.16 Setting fields with the text boxes.


Atter setting all the properlies, save the file (frmADO.FRM) and press F5 or click start button to run the
ADOCD1 application. When you run the application, the output screen will display the firs'i record from
Author's table as shown in Fig.22J7 .If you will clickthe right arrow, thenit wili dispiay next record. Repeat the
same process in the runtime window to see remaining records.

Ad*dcl

Fig.22.17 First record from Author's table.


22.15.2 DataGrid Control
As you know that the DataGrid display the fields value in the tabular form. Each row in the table represents the
record an<l each colur.tn represents the field. The column Headers of the DataGrid control automatically displays
the columns of the data source. You can add modify and delete the records using the DataGrid Control. To view
the records using the DataGrid control,

tr Create a New project.


tr Add the DataGrid control and the ADO control as shown in Fig' 22. 18.
O Connect the database using the ADO control as we have discussed earlier using the Connection
String or ODBC Data Source.
O Set the RecordSource propefiy of ADODCl.
l--

Database Goncepts and ADO Controls 495

Fig" 22.18 DataGrid and ADO control in a new proiect.


D To bind the DataGrid control set the DataSource propefly of DataGndl as ADODC1.

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.

Fi1.22.19 Author table record using Datacrid control.


22.16 DataList and DataCombo Control
Ihe Datalist control is a data-bound list box that is tiutomadcally 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 :

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,

Select components... fiom the pro.lect menu to


display the components crialog box.
D
= In the components'.' dialo-e bux. scioli down una
..t..i the option Microsoft ADo Data control 6.0
as shown in Fi-s. 22.7.
D When the option is selected, a small check mark appears
in the box ro the ieft of the option.
D Next, scroll down and select the option ]\Iicrosort patatist
Control 6.0 as shown inFig.22.2a. Cl.lck
the OK button when you are doue to dismiss the diaiog
box.

lc,nirdr Desiqt:a: lru*ri;hie


I I i-Jb,jucil
I
l4icrnsoft ActireX pluqin
ry-;hii.rosrfl AnO Dsta aDnlrol E.D (OLEDE)
Mirrosoft nqent Conlpal 7 6
1"1

- .ll,li';rqsoft lalendar fonlrcl A.O


-J -{J.r.,il
j l,lcros.rlt Chart ,:ontrol i,
0 (OLEDB)
,i, p':: ;3;e
r
I :F,tirr,:soft iomm f nr(rrl 6,0
--; i"li.|otnif (an-*n*n Dialog aonlr(rl 6.0
tr'r* *
-'l l.'lrrros,:f t ftata Bound rlid tentrll 8.0 (5F_1] , L=i @l
" l,lirrr,soft Data E*und Lisi Crrrtrolr o,rl
:.f''lirrosrftD rql
,q F1i*,:rsuft D rls
'-l
i llcr,rsof t D
t Cr EDB)

t-r<etir,m f r[4,1t1*]Wf{5lSrypaiy61Ey3.*,

Fig' 22'2a Components dialog box with Microsoft


ADo Data and Datalist controls.
Database Concepts and ADO Gontrois 497

The ADO Data Control (


6, i, the Datalist Csntrol ( ) and DataCombo controi ( )will be the last
three controls in the toolbox.
To access the database using th.e Datalist and DataCornbo perfoim the following steps :

tr Add one ADO Data Control (automatically named Adodcl)


n Add one Datalist and DataCornho on _v_'our. form as shown in Fig" 22.21.

Fig.22.21 Form with ADO Data, Datalist and DataConnbo controls.


tr Now you have to specify the data source frcm where it will retrieve the data. So to specify the data
source right click on the ;\DrJ Data control and ciick on tlre ADODC Properries optioil from the popup
menu. The Property Page as shou,n in Fig. 22.8.
o In the General tab of the property page yoll rvill finci three options, whicli can be use to create a link
with the database. This time we will select the Use ODBC Data Source Name and then click New
button as shown in Fig.22.22.

Fig.22.22 Selecting a data source from ODBC conneetion.


O After clicking on New..., the Create New Data Source wizard will appear as shown in Fig. 22.23.
Saraswati lnformatics Practices

S!*rcl a ir&c a, daia .#ie.


r $le il,$; S;r*,>* il,i4chflp&,j'?fB-!denti
a
li

'l: Crrcal

Fig.22.23 ODBC data connection wizard.


tr Froin the above Fig. 22.23, selecr
the System Data Source and click
on the Next. The tbllowing Fig.
22.24willappear:
4 UU.J/11
t',1iDio$Dlt dBale BrivEr l" ,Jbfl 4 rt.371',r ns
ir'iicro:olt dErsr VFP ttriver [' dbij E Dr:r 842S 00
l'4icto;oft Ercel 0ruer f.-rleJ 4 lD 37i1 t?,
lvl irrosrrlt ForFro Drirrer [' dbl) 4 r-rD .t71 1 0E
hlicroroit ForPrailFP 0riuer [" dbf] 6 il0 8428 C0
l,y'icrosrll CDBiI for Dracle 2 5I3 37r trD
l'.lrcrssqll Fatador: Dri.zer (" db )
-
hJicrosoft Text Driver l" l*lj rsyl

i[::::"l:i",:,ii-

Fi1.22.24 Selecting a driver i,, . < E.B*


for data source.

D In the next step you have the


select a Driver. Here, we select tire *€ts
Th< l,at
"Microsoft Access Driver
(*.mdb)" and click on Next. The
final screen will appear as shown
inPig.22.25.

Fig.22.25 Final step to


select a driver.
--
Database Concepts and ADO Gontrols 499

tr From Fig. 22.23, clic,k nn rhi) Finish button. The ODBC b{icrosoft Acsess Settip elialog appears as

shown in Fig. 22.26.

n,gJ$oiinqp $ar,rs,

0e;al#iira

Fig.22.26 ODBC Microsoft Access Setup.


f From the above Fig. 22.26, enter
the Data Source Nanie as "ADO
Data". And click on the Seiect
button to select the database as
shown in Fig. 22.27.

Fi1.22.27 Select Database diatog


for selecting a database.
D From the database list, select the BIBLIO MDB database and click OK.
tr Now the Database name with its path appeai ;lext to the Database in the ODBC Microsoft access
Setup dialog. click OK to close the dialog as shorvtt
;nFig' 22'28'

i-..
I "'.._J)

1 ,. ' 'l ,

.1 .",,. . i:r

Fig.22.28 Database with its Path.


500
Saras
D The Properly dialog box wili appear again. Select ihe DSN as "ADO Dara,,as
shown in Fig. 22.29 and,
clickAppiy.

Usa UUUL Uaia s.ri;ee NAne

Fiq.22.29 Setecting the DSN.


tr Property Pages dialog box and select 2- adCmdTable
from the
'12'
tr shorvn in Fig.22.t3.
? Finary click on Appry and rhen oK ,"':ll:"TjiTljlf* ^
o After settin-e the properties of the ADo Data control. n"ext step is to bind the Datalist and DataCombo
with ADO Data Control.
o click on the Datalist control and speicfy the Rowsource property
as ADOCD I and to set the ListField
property from the drop down list as Author to display
tfre uuttor rr. ".
rvSource property as ADOCDl and to ser the ListField
the author name.
List.FRM) and press F5 or click starl button to run the
When you run the application, the output screen will
o box. To see the records ru vsluvv,'uL' box.
in DataCombo u( click the
drop-down arrow as shown in Fig.22.29.

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

Ql. What is DBMS ?


Ans' The database is managed by a software pacl<age knowrr as database management
system.
Q2. List all possible attribute for a student entity.
Ans. Name. Rollno, Marks, Address, phone no. Date of birth.
Q3. what is the ditference between loeical and physical data independence ?
Ans' Logical data independence. Logical data independence means that the structure ofdata at logical leveI is
changed without changing the application prograln. The change must not remove
any of the data of the
appl ication program users.
Physicaldataindependence. Physical daia independence means that the physical structure ofthe clata
may be changed without charrging the overall logical structure of the data or the application program.
Q4. What is relation ? What is the difference between tuple and an attribute ? fDelhi t 99g)
Aus. A relation is like a table in rvhich data are arranged in the form of row and column.
The rows of a table are called tuples.
The column of a table is called attributes.
Q5. What is candidate key ?
Ans. The keys that can be serve as primary key is called candidate key.
Q6. Consider the following relation :

seller ten-r rate


D. Ray colgate %
S. Sharma oil 100
K. Lal nce 345

Which of the following is trLre?


(i) seller -> rate.
(ii) seller-> item
(ili) item rate.
->
(rv) item->seller.
(r) rate item
(ui) rate -> seiler
Ans. (i) True ->
(il) True (til) True (rv) False (v) True (vi) False
Q7. A database is storing the inforrnation about teacher and its related topic. If the foltowing teacher are n
the school :

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)

Teacher ics Class


Topic Subject Tname Tooic Classes
Sunran t,AN St man LAN
Ajav DtsMS Ajav DBIvIS
S. Ray Themal S.Ray Thermal
P Lal Organics P.I.al Organics
M.Singh Algebra M.Singh Algebra

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

Ql2. When is a relation said to he in second normal form ?


Ans. A relation is said to be in second normal form if it is in lNF and each non-key attribute is functionall.r"
dependent on the entire key.
Ql3. What is relation ? Define the relational data tnodei.
Ans. Relation. A relation is two-dimensional table.
Database Concepts and ADO Controls 503

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 ?

6. Explain the relational operations on database.


7. Define :

(a) I(ey (b) Primary key (c) Alternate key


504
Saraswati Inf ormatics Practices
8" Definenormalization.
9. What is the main funciion of DBA ?
l0' What is meant by functional dependency ? Give example of functional dependencies.
I l. Given the two relations :

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.

23.2 ClienUServer System


Oracle applicatious may run on the same computer as the Oracle Server. Alternatively, you can rttn applications
on a system local to the user and r.rn the Oracle Server on another system (client-server architecture). In this
client-server environment. a wide range of computing resources can be used. For example, a form-based airlines
reservation application can run on a client personal computer vn'hile accessing flight data that is conveniently
managed by the Oracie Server on a central computer.
lvlany of the examples in this book- focus on the use of SQL u'ithing the database. The examples assume
that you can log in directly to an Oracle database or that you are usiing a client-based tool that allows you to
enter commancis into a database. With the introduction of Web-based technologies, your ability to interact
with the database has been augmented by new cptions.
The comple4ity of the environment may be dauntin-q at first. Consider a simple architecture, shown in
Fig.23.\,in which two cornputers are in',,olved in the application - a client and a server. The database resides
on the server ard the user interacts tvith the server via the client. The client and the server rely on thtr
underlying network for their contmunications and each runs a version of Oracle's NetS tool. The server listens
for Net8 requests issued by the client
Client Server

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.

23.2.2 Th ree-Tier Systems


Now consider a three-tier architecture, shown in Fig.23.2. A three-tier architecture has three separate components
: a client, an appiication server and a database server. In implementing a three-tier architecture. you have many
more choices available than you have in the traditional client-server architecture. The communication protocol
used to communicate between the client and the application sen er can be different from that used to communicate
between the application server and the database server. The workload distribution among the tree components
can vary widely across applications. The perfcrmance and reliability of the components in both stand-alone
and networed mode can incluence the success of failure of the application.
Application Database
Client Seruer Seruer

+-->
(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.

23.4 Oracle lnternet platfornn


Oracle oflers a comprehensive high-performance lnternet latiorrri for e-commerce and
pT
dara rvarehousing. This
integrated platrofin includes everything needed to develop, deploy and manage
Internet applications. The
Oracle Intemet Fiatfor:r is built on three core pieces :
O Browser-based clients to process presentation.
Application servers to execute besiness Iogic and serve presentation logic to browers-based clients.
D Database to execute database-intensi,re business lo,qic and serv: data.

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 :

O Execute SQL statements.


O Format, perform calculations on, and print query results in the form ofreports.
D Create script files to store SQL statements tbr future references.

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'

23.8 Users, Roles and Privileges


Each Oracle user has a name and password, and he or she is the owner of any tables, and other resources taht
is created by his or her. An Oracle is a set of privileges. \bu can grant or withdraw specifc privileges to
appropriate users.
Database system privileges let you execute specific sets of commands. The CREATE TABLE privilege lets
you cretae tables. We will discuss the GRAN'f command in detail later on to grant different types of privileges
to the user.

Solved Exercises

Ql. What is client server architecture ?

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

Stsrling with SQt

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

24.3 Features of SGL


The SQL commands aie dealt with three issues :

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)"

24.5 Starting SQL


With the Strucrure Query Language or SQL, you tell Oracle which information you \4,ant to select, inseft, update
or deleie. In thct, these four verbs are ihe primary words you v,,ill use to gi.,,e f)racie instructions.
ln this chapter vou will leam how to intcract with SQL *PLUS, a porverful Ol'acie product that can take your
instructiotls fbr Oracle, check thenr for corrlectness. subrnit them to Oracie, anci then modifo or reformat the
response Oracle gives. Ii niay be a littlc coni'Llsing at first to unelerstand the difllrrence between whal SeL
xPl US is doir:g and rvhat Oracle is cioing, especially since
the error messages that Oracle proclucts are sirnply
passed on to ;vou by SQl, *PLUS. but vor-r will see as you work through the commands rvhere the difference lie.
As you get started, just think of SQL *PI-US as a coworker - an assistant rvho follou,s your instruction and
helps you do y,our work more quickl_v. Ybu interaei *,ith this corvorker by typing on your keyboard.
As explained in previous cirapter, if vou vrant tc rL:n SQL *FLUS from your desktop client machine,
E Select the sQL Plus pl'ograin in -r,cui oracle program group as shown in Fig. 24.1.

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

24.1 Starting SQL.PLUS.


tr After pressing Enter key, the Log On screen will be appear as shown inFig.24.2.
512 Saraswati lnformatics Practiees (Xl)

iii* l,ii

{! I

24.2 Oracle SQL .PLUS log on screen.


tr Enter tl-re user name as scott and password as tiger. Because the standard SQL Plus has predefined
databases which is accessed by a[ user using the same user name and password.
Note. Enter the passrvord only in lor.vercase ietters without any extra character.
This starls SQL *PLUS. Since Oracie is careful to guard'uvho can access the data it stores, it always
requires that you enter an ID and password to connect to it. After entering the user name and password press
OK button. SQL PLUS wiil announce that you are connected to Oracle and then will display SQL prompt as
shown in Fig.24.3.

Efe Edt Seach Helh :i. ,...t


Optiohs . ,. . .

SQL*P1us: Belease 8.1 "5-6"0 - Production on Tue Jun 3 08:53:17


(c) Copgright 1999 0racIe Corporation. Atl rights reserued -

: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.3 Oracle SQL .PLUS prompt.


You are now in SQL Plus and it awaits your instructions. If the command faiis. it means one of the four
things:
lJ you are not on the proper subdirectory to use Oracle.
tr Oracle is not in your path.
l--

tr you are not author;zed to use SQL Plus.


tr Oracle has not been installed prcperly an your computer.

24.6 Rules for SQL Commands


When writing SQL commancls, it is irnportant to remember a few simple rules and guidelines in order to
construct valid statements. Using the following mles y,ou can construct valid statements that are both easy to
read and easy to edit :
tr SQL statements ale not case sensitive (unless indicated otherwise)'
ft SQL statements can i;e on oile or mcre lines'
tr Ke.vwords cannct be abbreviated or split across lines.
tr Clauses are usually placed on separate lines.
tl Tabs and indents are used tc enhance readability'
tr Keywords are generally entered in the Uppercase.
U Only one staternent can be current at any tim: within the buffer. and it can be run in continuous line
by placing a semi-colon (;) at the end of last ciause.
tr Write a command either full or frrst four character

24.7 Executing SQI- Staternents


You can execute the SQL statements by using these metho<is :

tr Place a semicolon at the end of the last clause.


tr Place a slash on the last line in the buffer.
tr Place a slash at the SQL Prompt.
tr Issue a SQL*Pius RUN coinmand atthe SQL prompt.

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 :

tr Table. A table is used to store the data.


tr View. A view is the temporary table created using a Origiual Table. You can say it is a subset of one
or niore table.
D Sequence. Sequences are used to generate the irirnary Key values'
tr Index. They are used to improve the performance of some queries'
tr Synonym. They give alternative names to objects'

24"9 Database Obiect Naming Rules


limited to
The object rnust be maximum 30 characters long(except the datbase nam.es which are
8
O
characters.
O The object name should not contaiu the quotation mark'
tr The name must staft with letter.
tr The use of $ and # is discouraged in the object name'
O A name must not be a reserved word'
,,24.10 Data Definition Language (DEL)
Those commands which are used to create and maintain database are grouped into the class called data
clefinition language (DDL). The table has follorving properties :

tr Table can be created at anY time


tr There is no need to specifl the size oftable.
sl4 Saraswati lgrformatics Practiees (Xl)
tr Table structures can be nrodifiec! at any time.
tr l
abies may acquire mcre space automaticalry if the initial size is filled up.
Rules to name a Table :
E The name must begin with a tetter A -Z or a-2,
tr it may contairr letters . digits
and special characte r underscore ( _ ) , $ and # but the use of $ and # is
always discouraged.
rJ You can use either uppercase or lowercase letters both are same.
tr The length of table name is uptc 30 characters.
U The name rnust not [:e a SeL reserved word.

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--

Starting with SQL 515

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.

5e*ich 0otin'rs . Helc , ,,1.1:!rr::.;.jj


_ -]

SQL*PIuS: ftelease 8.1 "5 " 0- B - Producticn on T$e Ju$

(c) Copgright 199c 0rEcle Corporation" f,11 ri4hts

: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

SqL> CREAT€ TASLE TEfiCHFfi


, 2 (TNo CIiAR(4),
, 3 THfil'iE CH$B(38),
4 TADDBESS CHAR(25},
' 5 SAL0B? NIJnEEB(7,2),
. 6 DEPT_H0 Cl{RR(r+),
, 7 DOJ DATEi;

Tabl€ created.
SQL> I

24.4 CREATE command in SQL.PLUS prompt.


24.13 Describing the Structure of theTable
In SQL *PLUS,.you can specifl the structure of a table using the DESCzuBE command. The result of the
command is to see the cclumn narnes and data types as rvell as whether a column lnust contain data. Also, the
DESCRIBE command is used to show the attributes of the table with the constraintNULL/NOTNULL.
The syntax is as :

DESCRIBE table name;


&
DESCtable name;
For example, to dispiay the TEACHER table's structure, nrite

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)

Frf: Edk , Sesctr Endonr lieli.,


SqL> OESCRIBE TfACTIEfi
ilarne NUIl?
rht0 cHAR ( ir)
TI{AI4E cHsB (2 0)
TiIDDRESS cr{fifr ( 25 )
SfiI-f,R'i Nut48tfl(7,2)
OEPT NO cr{oR ( {)
DOJ DATE

S QL>

24.5 TEACHER table structure.


The above example displays the information about the structure of the TEACHER table. In the result :

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"

24.14Tables in the Oracle Database


The Oracle contains two type of table. first one is the USER table, which is created by the user, such as Teacher
as we have created above. The second one is the tables and viervs in the Oracle database known as the data
dictionary. This collection is created and maintained by the Oracle Server and contains information about the
database. All data dictionary tables are owned by the SYS user. Information stored in the data dictionary
include names of the Oracle Server users, privileges granted to users, database ob.ject names, table constraints
and auditing information. There are four categories of data dictionary views : eao,, .rategory has a distinct prefix
which reflects their intended use:
Prefix Description
USER These views contain infromation about objects owned by the user.
ALL These views contain information about all the tables accessible to the user.
DBA These views are restricted views. These view can be accessed by the DBA only.
V$ These views contain information about dynamic perfromance views, d-.tabase server
perfromance and locking.

24.15 Querying the Data Dictionary


You can query the data dictionary table to view various database objects created by you. The data dictionary
tables frequently used are these :
tr USER TABLES
tr USER OBJECTS
tr USER CATAI-OG
Example SEI-ECT * FROM user tables;
The above query describe tables owned by the user.

Example SELECTDISTINCTobject_type FROM user objects;


The above query is used to view distinct object types owned by the user.

Example SELECT * FROM user_catalog;


Starting with SQL 517

The above querv is used to view tables, views. synonyrns and sequences owned by the user scott as
shown in Fig. 24.6.

''..1 r: atii {rrp. Ig,i u)


'17': i .,^ ld-r: ,iot,. /.d
'ilr 1'lo ro- r...
SQL} SEL€ET * f8014 user _eataloq;

T*BLE ilRME Tf,8LE TYPE

BOHUS Tfi8L E
DEPT TftBLE
EhP TRSLE
SALGRRT}€ TABLE
-TEACHEfi TABLE

'sQt-> I

Fig. 24.6 Tables, views and synonyms an user_catalog.


24.16The lntegrity Constraints
SQL allows integrity constraints to be defined for tabies 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 inavlid data entry into tables. Constraints can be defined at one of
two levels :
tr Column level. Refrences to a single column; can be defined any type of integrity constraint.
tr 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.

24.16.1 Constraint Guidelines


Ali constraints are stored in the data dictionary. You must give meaningful names to the constraints. Constrairl
must follow the standard object-naming rules. If you do not name the constraint, Oracle generates a name with
the fbrmar SYS_Cn, where n is an integer to create a unique corstraint nalne. Constraints can be dehned at ttre
time of creation of a table or after the table has been created. You can view the constraints defined for a specific
by looking at the USER_CONSTRAINTS data dictionary table.

24^16-2The NOT NIjLL Constraints


This constraints ensures that the null values (ernpty values) are not pennitted for a specified colurnn. This
constraint can be defined at the column level not at the table level.
Example CREATETABLETEACHER
(TNOCHAR(4)NOTNULL.
TNAMECHAR(20),
TADDRESSCHAR(25),
SALARYNITttsER(7,2),
DEPT_NOCHAR(4),
DOJDATE);
The above example define TNO to be NOT NULL. So , the TNO does not accept empty values. In the above
example the constraints are unnamed, the Orcale server will create names for them. You can view the constraint
defined tbr a specific table by looking at the USER_CONSTRAINTS data dictionary table is as :
518 Sara
SELECT CGNSTRAINT NAME, CONSTRAINT_TYPE FROVI USER-CONSTRAINTS:
From the above commarrd, sQL pLUS will display the output screen as showo
in Frg.24.7.

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

Fig.24.7 Constraints names and their types.


From the above figr.rre, oracie generates a CoNSTRAINT_NAME sys_co0gl0 in
the
USER-CONSTRAINTS table. The NoT NULL constraint can be specified only
at the column level, not at the
table level. The above example specifies the NoT NULL conshaint to
the TNo of the TEACHER table. Because
these constraints are unnamecl, the Oracle Server will create names for
them. you can specify the names of the
constraint while specifying the constraint as :

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.

sql> sELf[I CO}IST8N IfiI


. .'"1. ":.',t i;.
FBO14 USEB_OOHSTRAIilTS;

CBHSTRfiIHT Hf,NE

'p( nrpr P
iPT ENP
.FI{ P
DEPINO R
iT HUH&ER f,

sql> I

24,8 Narned constralnts T_NUMBER.


24.16.3 The DEFAULT Constraint
A column may be given a default value through DEFAULI option. This prevents nulls from occurring if a row
is inserted without a value for the column. The DEFAULT values can be a literal, an expression or a SeL
function, such as SYSDATE as defined below in the Teacher table.
Example CREAIETABLETEACHER
(TNO CHAR(4) CONSTRAINT T NUMBERNOTNULL,
TNAMECHAR(20),
TADDR-ESS CHAR(25),
SALARYNUMBtsR(7,2),
DEPT NOCHAR(4),
DOJ DATE DEFAULT SYSDATE);
Note. The default expression must match the datatype of the column.
24.16.4The UNIQUE Constraint
A UNIQUE key integrity constraint forces every value in a column or set of columne be unique- that is no two
,
rows in the table can have the same value for that key. Ifthe UNIQUE key comprises more than one column, that
group of columns is said to be a composite unique key. Unique key allow the inputs of nulls until you also
define NOT NULL constraints for the same columns. A null in a column always satisfies a UNIeIJE key
constraint.
Example CREATETABLETEACHER
(TNO CHAR(4) CONSTRAINT T NUMBER UNIQUE NOT NULL,
TNAMECHAR(20),
TADDRESS CHAR(25),
SALARYNUMBEKT.2),
DEPT_NOCHAR(4),
DOJ DAIE DEFAULT SYSDATE);
The above example defines that the TNO should not be NULL and have unique values r.e., the two rows
do not contain the same values.
24.16"5 The PRIMARY KEY Constraint
As with UN IQUE key, PRIMARY KEY is also used to enforce uniqueness. There is only one PRIMARY KEy
per table is allowed. The PRIIIARY KEY constraints is a column or set of columns that uniquely identifies each
row in a tble. This constraint enforces uniqueness ofthe column or column combination. A composite PRIMARY
KEY is created by using the table Ievel definition.
Exawple CREATETABLETEACHER
(TNO CHAR(4) PRTMARY KEY NOT NULL,
TNAMECHAR(2O).
TADDRESS CHAR(25),
SALARYNUMBER(7,2),
DEPT_NOCHAR(4),
DOJ DATE DEFAULI SYSDATE);
The primary key does not accept NU LL values. So, the constraint NOT NULL must be used with primary
key.

24.16.6 The CHECK Constraint


The check constraint explicitly defines a condition that each row must satisry. A single column can have
multiple CHECK constraints that reference the coulmn in its definition. There is no limit to the number of
CHECK eonstraints that you can define on a column,
520 Saraswati lnforrnatics Practices (Xl)
Exunple CREATETAtsLETEACHER.
(TNO CHAR(4) PRTMARY KEY NOT NULL,
TNAMECHAR(2o),
TADDRESS CHAR(25),
S.ALARY N UMBER(7,2) CHECK (SALARY BETWEEN s000 AND I 0000),
DEPT_NOCHAR(4),
DOJ DATE DEFAULT SYSDATE);

Here, the column SALARY can accept value between 5000 and 10000 (including 5000 and 10000 also).

24.16.7 The FOREIGN KEY Constraint


The FOREIGN KEY or referential integrity constraint, represents a column or combination of columns as a
foreign key and establishes a relationship between prirnary key or a unique key in the same table or a different
table.
Example CREATETABLETEACHER
GNO CHAR(4) PRIMARY KEY NOT NULL,
TNAMECHAR(2O),
TADDRESSCHAR(25),
SALARY N UM BER(7,2) CHECK (SALARY BETWEEN 5000 AND I 0000),
DEPT-NO CHAR(4) CONSTRAINT TEACH DEPT REFERENCES DEPARTMENT(DEPT-NO),
DOJ DATE DEFAU tjf SYSDATE);
E.uample CREAIETABLEDEPARTMENT
(DEPT_]{O CHAR(4) PRr]\4ARY KEY
DEPTNAMECHAR(20));
In the above example Dept_no in the Teacher table is defined as the FOREfGN KEY, which is the
PRIMARY KEY of the table Department. The name of the constraint is Teach_Dept. The Teacher table in the
above example is the called the child table and the Department Table is called as the Parent Table. The foreign
key is defined in the child table and the table containing the ref-erenced column is the parent table. The fbreign
key is defined using a combination of the following keywords :
tr FOREIGN KEY. It is used to define the column in the child table.
tr REFERENCES. Is identifies the table and column in the parent table.
tr ON DELETE CASCADE. lt indicates that when the row in the parerrt table is deleted, the dependent
rows in the child table wiil also be deleted.
Without the ON DELETE CASCADE option, the rorv in the parent table cannot be deleted if it is referenced
in the child table.

Note. Before using the Foreign Key constraint, create the parent table rvhere the tbreign key treated as primary
key.

24.1 6.8 The Table Constraints


When a constraint is applied on a group of columns of the table, it is called table constraint.
Example CRE,{TETABLETEACHER
(TNO CHAR(4) PRTMARY KEY NOT N ULL,
TNAMECHAR(2O),
TADDRESS CHAR(25),
SALARY NLTMBER(7,2) CHECK (SALARY B ETWEEN s000 AND I 0000),
DEPI_NO CHAR(4) CONSTRAINT TEACH DEPT REFER.ENCES DEPARTMENT(DEPT-NO),
DOJ DATE DEEAULT SYSDAIE,
UNTQUE(TNO,TNAME));
Startins wath SQL 521

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

Fig. 24.9 Reference constraints in another table.


The table constraint always appear in the end.
Example CREATETABLETEACHER
(TNO CHAR(4) PRIMARY KEY NOT NULL,
TNAMECHAR(2O),
TADDRESSCHAR(25),
SALARY NUMBER(7,2) CI{ECK (SALARY BETWEEN 5OOO AND IOMO),
DEPT-NOCHAR(4),
DOJ DATE DEFAULI SYSDATE.
CONSTRAINTTEACH DEPIFOREIGN KEY (DEPI_NO) REFERENCES
DEPARTMENT@EPT_NO));
The abobe example shows the FOREIGN KEY at the table level.

24.17 Viewing Constraints


The SELECT statement is used to view the constraints. To view all constraints on your table, query the
USER CONSTR.AINTS table. Constraints that are not named by the table owner receive tir; s}'stem assigned
constraint name. Now modify the table TEACHER and create with ditTerent constraints as given below :

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));

To view ali the constraints, wirte the SeL statement as :

Example, SELECT constraint_name, constraint_type, search_condition


FROM user constraints
Where table_name = "Teacher"
From the above command, SQL PLUS will display the output screen as shown in Fig.24.10.

)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) |

Fig.24.10 Different constraints in TEAGHER tabte.


From the above figure, C stand for CHECK, P for PRIMARY KEX R for referential integrity and U for
UNIQUEkey.
Note. You cannot verify the NOT NULL constraint. In the above example notice that the NOT NULL
constraint
is really a CHECK constraint.

24.17-l viewing the columns Associated with constraints


You can view the columns associated with the constraints by querying the USER_CONS_COLUMNS
data
dictionary view.
Example, SELECT consffaint_name,column_name
FROM user_cons_columns
Where table_name = "TEACHER,,

From the above command, SQL PLUS will display the output screen as shown in Fig.24.ll.
Starting with SQL 523

SQL> SETEGT trim(constraint_na.Ee), trin(colunn_nans )


2 FB0il user cons f,olumns
3 \lhere table name = 'TEBCIIEB'
4;
TB I H( C0NSTBor NT_ilRr{E )

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>

Fig.24.11 Constraints with associate column names.


24.18 Adding a Constraint
You can add or drop the constraint in a table but you cannot modify a constraint. The command used to add a
consffaint is ALTER TABLE with the ADD clause. The syntax is :
ALTERTABLEtablename
ADD ICONSTRAINT constraint] type (column):
The constraint name is optional. Where,

table is the name of the table


constraint is the name of the consffaint
type is the constraint type
column is the name of the column on which constraint is to be applied.
Example ALIERTABLETEACIIER
ADD CONSTRAINT TEAC}IER-CONS
FOREIGN KEY(DEPT-NO) REFERENCES DEPARIMENT(DEPI-NO) ;

Where TEACHER CONS is the name of the constraint.

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.

24.20 Disabling Constraint


You can disable a constraint without dropping it. You can use the ALTER TLBLE statement with the DISABLE
clause to disable a constraint. The syntax is :

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

24.22.1The ADD Clause


Using ADD clause we can add new column into the table. For example if we have to add a new column for
PH_NO into a table Teacher table then we have to write :
Example AIjIERTABLETEACHER
ADD (PH_NO number(7, 0));
To add a table constraint we can also use ADD clause. From the above command, SQL PLUS will display
the output screen as shown in Fi1.24.12.

6 Yol,ti selected"
SqL> TRELE TERCHER
AOD (PH H0 nunberdT,8));
t 2 'LTEF
.Table altered-

Fig.24.12 Adding column into TEACHER table.

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

; THO }IOT HULL CHAR(q)


) THnilE clrAR (20)
. If,DDRESS c[RB ( 25 )
SRLRNV M[{8EB(7,2)
DEPT HO DHfiR (4)
t3J DNIE
PH M] NUtttEEB(7)

SQL>

i,:1. I

Fig. 24.13 New column PH NO in TEACHER table.


24.22.2 The MODIFY Clause
Use the modify keyword ro modify the definition of an existing column. The form is as :

ALIERTABLE table name


MODIFY(column datatype) ;

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 \\

isQL) nLTER TfiBLE TE0ct{EB


i40DIFY (pH_flo runber(9,0)) ;

,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

Fi1.24.14 Modified cotumn PH_NO in TEACHER tabte.


There are four changes that are not allowed to make :

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 .

24.22.3 Dropping a Column


To remove a column which is no longer required for your table you can use an ALTER
TABLE statement with
the DROP COLUMN clause.

Note. This feature is available from Oracle8i onward.


Example ALTERTABLETEACHER
. DROPCOLUMNPH-NO;
When you see the stucture of dropped column with DESCRIBE TEACHERcommand
at SeL plus command
prompt, the following screen Fig. 24.15 will appear.

lsQL> RLTEn T.RBLE TEAcHEn


2 DflOP COLUI,IN PH-H0;
lTablp alterpd-

'SqL> DESCBIsE TEAGHEIT;


'Hame N|III? rgpe
J fflo Mrr )ruLL GHRR(4)
TNf,NE
clttR (2 6)
TRDDRESS
8ilRB ( 25 )
I snlnRv mrmER(7,2)
' 0EPT l{0 cflen(4)
DOJ
ONTE
I
,SQT)

Fig.24.15 Dropped cotumn PH_NO in TEACHER tabte.


Starting with SQL 527

24.23 Drop Table Command


To remove the table physically we use DROP TABLE command. The form is as :

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.

24.24.1The INSERT INTO ,


This command adds a new record to the end of an existing database. The new record includes data specified
with the INSERT INTO command. The form is as :

INSERTINTO table name


[(<column name l>[, <column name2>[, ...]])]
VALLTES (<exprl>[, <expr2>[, ...]l) /

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

Fig.24.16lnserting a record into TEACHER tabte.


Similarly, insert the following records in the TEACHER rable :

T(2 Jugal Mittal 34, Ramesh Nagar DM w2 03-JUI-199


T03 SharmilaKaur D-3l,AshokVlhar 20m0 DOl 0GJLTN-2000
TM Kaushik Mc-32,ShalimarBagh 15mO
Sandeep D03 08-AUG-2m1
m5 Sangeeta Vats G-35, MalviyaNagar 8900 DO5 2GFEB-2I/J]_
T06 RameshKumar Bc-42,ShalimarBagh l4m0 Dm $-fin -1s9.7
m7 Shyam Arora 50, MIG FLATS. Rohini r20m w2 15-AUG-1998
T08 ShivOm R-44,KirtiNagar l30m w2 22-SFP-2CfL
T09 VivekRawat E-33/27,Sec-1, Rohini l00m D01 r2-OCT-2Nt
Tl0 RajestVerma D-11/130, Sec-5, Dwaraka 56m DOl 07-NOV-2000
Tl1 Ashok Singhal F-1/65, East Patel Ngr 7500 w2 11-AUG-1999
T12 Chetan Shukla C-IOs,l0thCross
34m w2 l3-JUN-2m1
T13 Reeria Mehta 120, DDA Colony
55m D03 I8-JUL-2000
T14 Bhwanalamba E-t40,SwastikApptt.,DlF 45m DOl l6JUL2ml
T15 Jagjit Singh A-24D, Printers Apptt. 6500 DOl 1I-JUL-198
Note' The name of TNo - T10 was given as "Rajest Verma". So, that later on student can modify the same name
using UPDATE command.

24.25The Delete Command


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
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 :

DELETE FROM table_name;


Example DELETEFROMTEACIIER;
The above statement delete all the rows from a table student.
Starting with SQL 529

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 :

FieldName Data Type Constraints


PNo Numbe(a) Primarykey
Name Char(20) UNIQUE
Age Number(2)
Department Char( l5) Default:"OPD"
Dateofadm Date DefaultSYSDAIE
Charges Numbe(7,2) check> 100
Sex Char(l)
(r) Insert the following data into the above table
I Arprit A Surgery 2ll0l98 300 M
2 Zarina D ENT l2ll2l97 250 F
3 Kareem 32 Orthopaedic 19102198 2N M
4 Arun 12 Surgery 1l/01/98 300 M
5 Zubir. 30 ENT I2ICIDS ?50 M
6 Ketaki 16 ENT 24102198 2s0 F
7 Ankita D Cardiology 20lDD8 800 F

8 Zareen 45 Cynaecology 22102198 300 F


9 Kush 19 Cardiology 13101198 800 M
l0 Shilpa B NuclearMedicine 2l/02198 400 F

(il) Write a command to describe the structure of the above table.


(iir) Write the command to view the constraints of the table Hospitalalong with the column names.
(rv) Add aForeign key constraint on the field Department. Assuming the reference key as DEPT_NO in
tableDEPT.
(v) Disable the constraint on the field Department.
(vl) Enable the constraint on the field Department.
(vil) Drop the constraint in the field Department.
(vin) Write a command to describe the structure of the above table.
Starting with SQL 531
(,i) Add one more column in the above table as Address of type char(20).
(x) Modifo the the column Address as char(25).
(xi) Drop the column Address.
(xll) Delete all the rows ofthe table Hospital.
Ans. The command used to create a table is :

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 :

FieldName FieldTlpe Constraint


EMPNO Number(4) NOTNULL PRIMARYKEY
ENAME Varchar2(20)
JOB Varchar2(9)
MGR Numbe(a)
HIREDATE Date
SAL Numbe(7,2)
COMM Number(7,2)
DEPTNO Numbe(2) Foreign key
532 Saraswati lnformatics Practices (Xl)

Create another table named as DEPTM with the following structure :

FieldName FieldType Constraint


DEPTNO Number(2) NOTNULLPRIMARYKEY
DNAME Varchar2(14)
toc Varchar2(l 3)

Insert the following records into the EMPLOYEE table :

7369 Sunita Sharma CLERK 7%2 I7-DFC-80 2800 n


749E Ashok Singhal SALESMAN 7698 20-FEB-81 3600 300 30

7521 Rohit Rana SALESMAN 7698 22-FEB-81 5250 -s00 30

7566 JyotiLamba MANAGER 1839 02-APR-81 4975 20

7654 Martin S. SALESMAN 7698 28-SEP-81 6250 1400 30

7698 Binod Goel MANAGER 1839 0I-MAY-81 5850 30

77f2 Chetan Gupta MANAGER 7839 09-JUN-81 24s0 IO

7788 Sudhir Rdwat ANALYST 1566 19-APR-87 5000 n


7839 Kavita Sharma PRESIDENT 17-NOV-81 5000 l0
7844 TusharTiwari SALESMAN 7698 08-SEP-81 4s00 0 30

7876 Anand Rathi CLERK 7788 23-MAY-87 6100 n


79m Jagdeep Rana CLERK 7698 03-DEC-81 4950 30

7W2 SumitVats ANALYST 7566 03-DEC-81 3500 3600 n


7934 Manoj Kaushik CLERK 77C2 23-JAN-82 5300 l0

Insert the following records into the DEPARTMENT table :

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)

(rv) Disable the constraints CHECK on the field no of bk.


(v) Enable the constraint again.
(vr) Drop the PRIMARY KEY constraint.
(vil) Delete the column mem_add.
(viil) Delete all the rows of a table.
(x) Drop the table.
18, Create database named as EMPLOYEE using SQL command of following structure :

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

(r) Inseft the following data into the EMPLOYEE table :

I KESHARSTORE 4OOOO WEST 45 C CML


2 KIRTI ARTS 35OOO SOUTH 38 A ELEC
3 KzuPPLE 6OOOO NORTH 9 B CIVL
4 ARYAN STALL 38OOO NORTH D B CML
5 SAMSONS 42MO EAST 35 A COMP
6 BISWAL 29OOO SOUTH A A MECH
(il) Drop the constraint NOT NULL.
(lr, Add one more column as Address with 20 characters.
(rv) Describe thc atructure of the table.
(v) Add a foreign key on the field Dept. Assuming it a Primary key in the table Department with field
name as Dept_no.
(vi) Disable the foreign key constraint.
(vir) Enable the foreign key constraint.
(vlli) Write the command to view all the constraints on the table EMPLOYEE.
(rx) Insert a new row with Name as NULL.
19. Create database named as TOY_SHOPPE using SQL command of following structure :
FieldName FieldTlpe Width Dec Constraint
Sno Number 2 NOTNULL
Toy_name Character n LTNIQUE
Category Character n
Price Number 6 1 Check> 250
Quantity Number 3

Starting_Age Number 2 Check> 0


Ending_Age Number 2 Check < 15
(l) lnsert the follwing data into the TOY_SHOPPE table :

I Popeye StuffToy 450 12 0 I


2 Rapid Fire Two Player 600 25 5 7

3 Teddy Bear StuffToy 300 40 I 5


Starting with SQL 535
4 Creative Mind Blocks
Building g00 lg 5 8
5 Ping Pong Two Player 500 53 5 9
6 Race-Trace Mechanical 1800 17 9 t2
(ll) write a command to describe the structure of the above table.
(iil) s/rite the cornmand to view the constraints of the table along with the column names.
(rv) Disable rhe constraint on the field Ending_Age.
(vi) Enable rhe constraint on the field Ending_Age.
(vil) Drop the constraint in the field Ending_Age.
(vlir) Add one more column in the above table as Discount of type Number(4, l).
(rx) Modifu the the column price as char(S,2).
(x) Drop the column Starring_Age.
(xl) Delete all the rows of the table.
20. Create database named as LIBRARY with appropriate data type using SeL command of following
structure :

No, Title, Autho6 Subject, publisher, euantity, price


(i) Insert the following data into the LIBRARY table :

I Data Structure Lipschute DS McGraw 4 217.W


2 DOS Guide NORTRON OS pHI 3 175.00
3 Turboc C++ Rcbort Lafore prcg Galgotia 5 270.m
4 Dbase Dummies palrner DBMS pusrakM 7 130.00
5 Mastering Windows Cowart OS BpB I 225.m
6 cornputer studies French FND Galgotia 2 75.N
7 COBOL Stern prog JohnW 4 1000.00
8 Guide Nehryork Freed NET Zpress 3 200.00
9 Basic for Beginners Norton prog BpB 3 210.00
l0 Advanced Pascal Schirdt prog McGraw 4 350.00
(ii) Apply the appropriate constraints on the fields.
(iii) After applying the constraint view them from the data dictionary.
(rv) Disable any of the constraints and view the data dictionary again.
(v) Enable the constraint and check in the data dictionary
(vr) Drop all the constraints.
(vil) Drop the column euantity.
(viii) Delete all the rows of a table.
(rx) Drop the table.
21. Create database named as CLUB with appropriate data type using SQL command of following
structure :

COACH-ID, COACHNAME, AGE, SPORTS, DATEOFAPR PAY, SEX


Insert the follwoing data into the CLUB table .

I KUKREJA 35 KARATE 27/03/1996 1000 M


2 RAVINA Y KARATE 2010U1998 12ffi F
3 KARAN A SQUASH 19102/1998 2000 M
4 TARUN 33 BASKETBALL 0U01/1998 r5m M
5 ZUBIN 36 SWIMMING l2/0y1998 750 M
6 KETAKI 36 S\I/IMMING 24/A/1998 800 F
Try all the commands disscussed in the chapter.
536 Saraswati lnf ormatics miaes(Xt)
22. Create database named as LAB with appropriate data types and constraints using SQL command of
following structure :

Nq ItemName, CostPerltem, Quantity, DateolPurchase, Warranty, Operational


23. Create database named as FAI\{ILY using SQL command of following structure :
No, Name, Fema leMembers, MalelVlembers, Income
(r) Insert the following data into the table
I Mishra 3 2 7000 service
2 Gupta 4 I 50000 business
3 Khan 6 3 8000 mixed
4 Chaddha 2 2 25Cf0 busirtess
(r) Add a new field name as Occupation oftype 20 characters.
Chapter - 25

SQL SELECT Stqtement

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.

25.2 Making A Query


As we know that the the full form of the SQL is Structured Query Language. As the name suggest the main
function of the SQL is to make the Query. A query is a command you give your database program that tells it to
produce specific information ffom the tables in its memory. This information or the result of the query is
generally sent directly to the computer screen but it is also possible to sent the result to the printer or as a input
to the other command.
Queries are the part of the DML. Queries in SQL are all constructed flom a single command. The main
command which is used to create the query is called SELECT.

25.3 SELECT Command


With the SQL SELECT command. \ ou can retriele information frorr one or more databases. You pose a query
rvith the SELECT command. Because of the basic nature of SQL. it makes sense that the most powerful SQL
command is the one that selects data to satisf a query-the SELECT command. ln its simplest form, a SELECT

SELECT IDISI'INCT] {*, column [alias], .....]


FROM table_name;
tr A SELECT clause, which specifies or lists one or more columns to be displayed.
tr A FORM clause, which specifies the table containing the columns listed in the SELECT clause.
tr DISTINCT supresses duplicates"
tr * selects all coiumns.
tr column, rvhich selects the named column,
tr alias, which gives selected colutrns defferent headings.
tr FROM iable specifies the table containing the columns,
As we have already created a TEACHER table in our previoLrs chapter and we inserted 15 records. In this
chapter we willdiscuss the SELECT command with diffbrent clauses, keywords and statements using TEACF{ER
table. For example, when we write a SELECT statement, it will follow the words like keyword, clause and
statements. These are :

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.

So, to display the column value or rows of TEACHER table, write

(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.

Iik Edi Sex


SQL> SELENI *
8@
FBOI4 TEBCilER;
'' , ';,

TNo TNAl,lE TgDORESS SOLARV SEPT DOJ

T01 R.kesh Sharna 245-t(aluigd flagEr 5600 DAE


-12-0EC-Bl
T02 Jugal hittal 34, Eaoesh I'tagar 1200s D82 0$-JUL-99
T03 Sharrila Kaur D-31 nshok Uihal. 2C60[ D51 B6-JUll- 00
T0q Sand€ep fiaushik " Shalimar
IIG-32, Baqh 1s000 D03 0B-nuG- 01
ISE Sangeeta Uats G-35, l.lal{igs ilaqar 8900 005 2 0-FE8- 00
TU6 Ranesh l{umar BG-42, Shalinaf Bagh 14008 003 83-JUL_97
TSZ Shyan Rrora 58, t4IG FL0TS, Sohini 12000 D02 1 5- AUG-98
T08 Shiu on R-tq, (irti llagar 13000 D02 22-SEP- 01
T69 Uiuek Rauat E-33/21, Sec-l, Rohini 1000s D0f 1 2-0CT- S1
11S fi:jest UEFma D-1111?5, Sec-5, D({araka 5606 D94 07-N0u- B9
T11 Bshol Singhal F-1165, East Patel Ngr 75s8 Dsz 1'r- RUG-99
1'12 Chetan shukla C-105, 1otn CrDss 3400 002 1 3-JUN- 01
I13 Reena tlehtd 128, DDft Colony 5509 D03 18-JUL- 66
T14 Bhlrana Lainba E-140, Suestik Rpptt-, DLF 4508 D04 16-JUL- 01
T1s Jagjit Singh A-.240, Printers Epptt_ 6500 D0& 1'1 -JUL-98

15 roros selected-
SQL> I

Fig. 25.1 Using SELECT command in SeL.


Note' The name of TNO - Tl0 was given as "Rajest Verma". So, that later on student can modifl, 1[s same name
using UPDAIE command.
25.3.1 FROM Clause
The required FROM clause specifies the tables or views that are used to retrieve values.
In its simplest form, it must include:
tr SELECT clause - A kevword that tells the database this command is a query. All queries begin with
this word. It
lists the columns to be displaved i.e., it is essentially a PROJECTION.
tr FROM clause - This is also a keyword. It is followed by a space and then the name of the database
being used as the source of the information.
Note. The SELECT command begins with the keyword SELEC! followed by a blank. Aiter rhis comes a list of
all the names of the columns which you want to display, seperated by commas( or x if you want to display all
the columns). The keyword FROM is next, followed by a space and the name of the table that is being queried.
Finally, a sernicolon(;) must be used to end the query.
tr For retrieving all the column. If you want to
see e\rery column of a table the asterisk (+) is a
convenient shorlhand that means all columns. So , for retrieving all the columns the form is as :
SELECT * FROM tablename;
Example SELECT * FROM TEACIIER;
The above statement retrieves the all the columns of all the teachers from the table TEACHER as a shown
in Fig, 25.1 .
tr For retrieving specific columns. If you want to see parlicular columns of a table then the form is
AS:
SELECT column_namel, column_name2, ... FROM table name;
Example SELECT TNO,TNAME FROM TEACFIER:
539
SOL SELECT Statement

The above statement retrieves the TNo and TNAME of'all the teachers from the table TEACHER
as

shown in Fig. 25.2.

.
l"teh l !,+ l:.: a'. ,?.. t6 '-? :h

T01 Rrkesh shirna


TB2 Jugal t'lith&l
T&3 Sha,"ni1a Naur
I04 saEdBtp Haushik
T05 Sangeeta Uats
T06 Ramesh l(unar
Tg7 Shyin nrorts
TBg Shiu oltt
T09 Uiuek Rasrat
T10 Bajest Uerna
T11 Rshok Singhal
f1Z Chetafi Snukla
T13 Beena l4ehta
T14 thuana Lanba
Jagjit Singh
.T15
15 ror,rs selected-
,SQL> I

Fig.25.2 Retrieving specific column values from TEACHER table.


order. It is nol
O Column Reordering. In SELECT statement it is possible to display the column in any
iri the order they are defined in the table. You can put them in
necessary to display the column same
any order You want.
Example SELECT TNAME,TNO FROM TEACFIER;
TEACHER
The above statemenr retrieves the TNO and TNAME of all tbe teachers from the table
as

shown in Fig. 25.3.

'.Eb Ed[ '$*erch l.i .a

1S0L> 1ELECT IHENE. TIiO f ROI'I TEftCHER;

I HE}IE THI)

Bakesh Sh€rma T01


'JugB1 t4ittel 7e2
shar.,lila t(aur T03
'Sarldeep Kaushik T 61.
Sangeeta Uats r65
RarDestt Hunar T$6
Shyam Rrot'* T87
,Sniu om r68
Lliuek Bairat T09
,Raiest Uerna T18
nshok Sinqhal T1'l
,chetan shukla T12
BBena l4eFlta T-13

'Ehr,lana Lar*ba
.Jagjit Tl ra

Slngh Tis
115 ,'ourr serected.
.SQL>
I

Fig.25.3 Reording column values from TEACHER iable'


25.3.2 WHEHE Ctause
As you insert more values in the table the tabie tend to get very large. Sometime
it is required to select certain
rows' SQL enables you to define the criteris to determine which iows are selected
for output. The WHERE
clause of the SELECT command ajlows 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. You can use anv ofthe comparison operators (Operators are
<! >, (=, )=, =, <>, and #). The search
condition can use any valid expression. Include parentheses as needed to achieve
the desired result. The form
isas:
SELECT colurnn namel, column name 2,.....
FROM table name
IWHERE condition];
The square brackets in WHERE clause means that this clause is optional i.e. you can use
SELECT statement
without using this clause. The WHERE clause may compare values in columns. literal values.
arithmetic
expressions or function. The WHERE clause expects 3 elements :

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

Fig.25.4 Using WHERE ctause in TEACHER tabte.


tr Relational Operators. The mathematical operators which are used to perform certain
type of
comparision bettl'een two variables are called relational operators. Given below
is the list of the
relational operator present in the SeL :
Operator Meaning
Equal to
Graeter than
Less than
>- Greater than or equal to
Less than or equal to
o Not equal to
SQL SELECT Statement 541

Suppose you want tcr display the naine and salary of the teachers getting saiary more than 12000. Then the
statemet will be :

Example SFr ECT TN-AN,{E,SALARY


FROMTEACHER
WHERESALARY> IOOff);
From the above command, SQL PLUS will display the TNAME and SALARY rorvs rvhose SALARY more
than 10000 as shorvn in Fio 'r5 5

Seetth s,]i4
STL SELECI IHFI,IE , SALAS f J^t
2 r80tt TEsCHER
tilHEBE SNLRBY > 106BO;
)
TN*TIE S*L*RY

,JugaI ilittal 120G0


Sharmile l(aur 2 8SE0
rsandeep Kaushik 1s0sB
,Rafiesh Kumar 1 4086
.Shyarnerora 12 0{10
.Shiu 0n 130$0

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

T6II Sandeep l,laushik


T06 Ran?sh Kuflar

SQL> I

Fig. 25.6 Using WIIERE clause with boolean operator AND in TEACHER table.
542 Saraswati Informatics Practices (Xl)

Example SELECT TNO,TNAME FROM TEACHER


WHERE (TNAME ='Rakesh Sharma'OR TNAME ='Jugal N{ittal');
The above example displayed the details of the teacher having name Rakesh Sharma OR Jugal Mittal as
shown in Fig. 25.7.

file fdir Seach lpU,rns Help


SQL} SELECT THfl, TNf ],IE FRO].I TEBf IIER
2 I',HEEE (TNfiilE = 'Bakesh Sharna' 0R TN0],iE = 'Jugal flittel') ;

T}IO TNfi}.IE

Tg, Eakpsh Sharma

SQL>

Fi1.25.7 Using WHERE clause with boolean operator OR in TEACHER table.


Example SELECT *
FROM TEACMR
WHERE (NOT SAI-ARY = 10000);
The above exarnple displayed the details of all the teachers whose SALARY are not 10000 as shown in Fig.
25.8.

";:__. *,.;iti
sQL) SELEEI
2 FB0tl TENCHER
I+H ERE (NOI SRLARV

Tflo T ADD BESS SALABV DEPT DOJ

T0'l Rakesh Sharna 245-l4aluiga Nagar 5600 009 12 -D EC- 6'1


T82 Jugal Nittal 34, Ramesh Nagar 't2800 D62 03-JUL-99
T03 Sharmila ilaur D-31, hshok Uihar 20000 001 06-JUN- 0 0
T64 Sandeep Kaushik [G-32, Shalimar Bagh 15060 D0s 68-RUc- 01
T05 Sangeeta Uats c-35, Haluiga ilagar 3q00 D05 2O-FEB_ BO
T06 Raro€sh Rumar EG-42, Shalinar Eagh 14060 003 63-JUL-97
Tg7 Shyah Arora 50, IIIG FLSTS, Rohini 12000 002 15-nUG-98
T08 Shiu 0m n-t4, l(irti Nagar 13000 D62 22-SEP- 61
I't 6 Raj€st UerDa o-111188, sec-s, Duraraka 5600 D04 07-H0u-00
T11 Ashok Singhal F-1165, East Patel ilgr 7500 002 11 -AUG- 99
112 C[etan Shukla C-105,1otn Cross a400 D02 1 3-JU[t- 01
T13 Beena l,lehta 120, DDA CoIonU 5500 D03 IB-JUL. OO
T-,l4 Bhr{ana Lamba E-14e, Sl]ristik Apptt-, DLF 4580 Dotr 1 6-JuL- 01
T1s Jagjit sinqh e-24D, Pri.nters Apptt- 6500 084 1 J _JUL_ 9B

1g roes selected.
sQr> I

Fig.25.B Using WHERE clause with boolean operator NOT in TEACHER table.

Example SELECT TNO, TN,{ME


FROM TEAC}MR
WHERE NOT TNAME = 'Rakesh Sharma' OR TNAME = 'Jugal Mittal';
In the above example the NOT is applied to first TNAME only, i.e., Rakesh Sharma. SQL will apply NOT
only to the Boolean expression immediately following it.
SOL SELECT Statement 543

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 :

Example SELECT T].{O.TNAME


FROM TEACMR
WHERE NOT (TNAME ='Rakesh Sharma'OR TNAME ='Jugal Mittal );

In the above example parentheses indicate that everything inside it will be evaluated first and treated as a
single expression by everything outside them.

25.4 Using Special Operators in Conditions


SQL uses some specail operators like : IN, BETWEEN, LIKE, DISTINCT and IS NULL in addition to the
relational and Boolean operators.
25.4.1The lS NULL Clause
When we have to search the column whose value is NULL ( NULL indicates the missing values) in the table
then we use NLILL clause. The form is as :
SELECT column namel, cotumn name2,...
FROI\{ table name
WHERE columnname IS NULL:
Before using IS NULL clause. rnsert at least two records without SALARY. The NSERT INTO command is
AS:
INSERTINTOTEACHER
(TNO, TNAME, TADDRESS, DEPI_NO, DOJ)
VALUES('T16', 'Dinesh Goel', 'A2l-Ttiveni Appt. , 'D04', '12-Oct-2000');
INSERTINTOTEACHER
(TNO, TNAME, TADDRESS, DEPT-NO, DOJ)
VALUES('T l7','Lokesh Rathore','C- 1 1, MIG Flaf ,'D03',' I 7-Jul- 1 999') ;
After inserting two records. use the SELECT command to display all records as shown in Fig. 25.10.
SELECT * FROM TEAC}IER:

EdB EdE $eacl: gpthr+ i{9, i ''l .. ,ii , 11' 'I ,


SqL> S€IICI * F80]i T[fiefiEfl; ra,ji. ral-\

INO TNAI.II TffDDRESS Sf,LfiRf BEPT DOJ

.TS1 Bakesh sharrtla 2!r5-Ne1uig3 Naqar 5600 D05 1 2-D€s- 01


T02 Jugal ttittal 34, fiamesh Hagar 12000 002 03-JUL-99
T03 Sharnila Ka$r D-31, Asttok Uihar 26886 00r g&-JUN- 00
-I04 Snnd.ep l{aushik t4G-32, Shalinar Eaqh .I5BOB
DBS 08:AUG- 81
I05 Sanqeeta Uats E-35, llalrriga llagar 8904 D0s 2 O.FEB- OB
T66 Banpsh Humar BG-{z, Sha}inar BBgh 14800 D03 [3-JUL-97
T07 Sttgrl|l Srora 90, ltiG FLfiTS, Rohini ,2800 D02 15-ArrG-98
TB8 Shiu 0m R-44- Hirti Nsgar 13808 D02 22-SEP- 01
,IS, Uiuek Ri$at E-33/2?, Sec-1, fiohini 10G00 DBl 2-0CT- 01
'T10 faJest Uerma A-11/135, SeL-5" Dr{iraaa 5600 00t{
1
B7-t{0u- 60
T11 fishok Singhil F-1/65, East Patel I'lgr 7568 002 1 1 -fiUE-99
112 Chet.n Shufrl* C-1G5, ''l 0th Cross 3llBO DB2 1 3-JUlr- 81
T13 8€ena tlehta 120, DDC Co10n! 5508 D03 1 B-JUL- O6
T1{ Bhfrana LJnba E-14Q, Sr,rastik Fpptt., DLF 11500 D04 .t
6-JUL- 0.t
!T15 Jigjit Singh fi-ztiD, Printers 6pptt- 6560 D04 1.' -JUL_98
iI16 0inesh Goal 421-Trlueni HFptt- 004 't 2-0cI- BB
T1V Lokpsh Rdthor€ e-11, t{IE Flat 803 '17-JUL-99
-17 ro{rs splected.
SAL> I

tl l

Fig.25.10 Rows in TEACHEB table inctuding NULL vatues.


Example SELECT *
FROM TEACHER
WHERE SALARYISNULLI
The above example displays the rovis u,ho,(e SALARY is NLILL frorn TEACHER table as shown
in Fig.
25.11.

sQr> SELECT *
2 FROI4 TERGHER
3 II}IERE SNLRBY IS NULL;
TNt) IHNI{E IA}DBESS SBLRRY OEPT DOJ

T't6 Dinesh Goel 421-Triueni 0pFt - D 0lr -t2-0cT-08


I17 Lokesh iiatncre C-11, r,lIG FIat D83 1 7-JUL-99
s0t>

tl i
.i#..--
Fig.25.11 Rows whose SALARY is NULL.
You could obtain another result with this cortmand :

25.4.2 The DISTINCT CIause


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. The form is as ;
SOL SELECT Statement 545

SELECT DISTINCT coiurnnname


FROM tabie name;
Example SELECT DISTINCT SALARY
FROM TEACF{ER;
From the above comrnand, only the distinct salaries are displayed on the screen as shown inFig.25.12

$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

1& ro{'rs selPcted.

5QL>

Fig. 25.12 Distinct salaries in Teacher table.


The DISTINCT clause can be specified only once in a given SELECT clause. If the clause is to apply on
multiple fields, DISTINCT elemiirates rows where all of the selected frelds are identical. Rows in which some
values are the same and some different wili be retained.
25.4.3 The ALL Clause
The ALL clause is same as that when you do not specify DISTINCT .The ALL clause retains the duplicate
rows. The tbrm is as :
SELECT Al-I-columnnarne
FROM table name;
Example SELECT ALL SALARY
FROM TEACFIER:
25.4.4 The BETWEEN Clause
When you have to specify the range of the column then you have to use the BETWEEN clause. BETWEEN is
sensitive to order, and the first value in the clause must be first in apla.hbetic or numeric order. The form is as :
SELECT column name], coluurr name2,.....
FROM table name
WHERE columnnameBETWEEN valuel AND vahrc2i
Example SELECT TNO, TNAME
FR.OM TEACI#R
WHERE SALARY BETWEEN 1OOOOAND 150@;
546 Saraswati lnformatics practices (XD
Note. The tsETwEEN operator is inclusive, i.e., values present on the boundry are also including in the result.
The above statement displayed the TNO and'INAME of all the teachers whose SALARy lies
betrveen
10000to15i)00(t0000and15000isincludingintheresult) asshowninFig.25.13.

EJIB dfil.uS""31ri,
sqL SELECT TNO, THOHE
2 FROII TEfiCHEH
I,'HENE SRLRBY BET!'EEN i0006 RHD 'r5660;

TNO YMlfif

I &2 Jugil t'tittal


TBlr Sandeep ltaushik
T 06 fianesh l(utrar
,T87 Shgam nrori
T08 Shiu [o
T Il9 lriuelr Bauat

6 rotrs selected-
s0L>

Fi9.25.13 UsinE BETWEEN ctause with SELECT.


25.4.5The lN Clause
The IN clause is used to specify condition based on a list. The IN operator selects values that matches any
value present in the list of values. The form is as :

SELECT column namel, column name2......


FROM table name
WHERE column name IN( valuel,value2,......,value n);
IN defines a set by explicitly naimg the members of the set in parentheses, separated by commas.
Example SELECTTNO,TNAME
FROM TEAC}IER
WHERE TNO IN (T01",T03','T05)
So, only those rows are selected whose TNO are T01 , T03, and T05 as shown in Fig. 25.14.

Ed.B &eoieh"r9stmr* !:etp


sql) s€tEcI rHB, INAnE
2 FRO]'I TEAEHE&
3 UHERE TNo rH (.T01"

{H0 THf,l'lE

,IB5 Sangeet€ uats


rT63 Sharmila l(aur
:T01 Rakesh Shdf[ra
SQL>

Fig.25.14 Using IN clause with SELECT.


547
SOL SELECT Statement

25.4.6The LIKE elause


SeL provides a string matching pattern. LIKE can be applied to only CHAR and CARCHAR fields' The LIKE
searches a character field to sie if part of it matches a string. To do this SQL provides two wiidcards
characters :

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 :

SELECT columrt namel, column name2,...


FROM table name
WIIERE columnnarne LII{E '7o';

Example SELECT TNO, TNAME


FROM TEACHER
WHERE TNAME LIKE,'R%O' ;

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.

{1h' [dit, leamh E!'iens HdS.


.sQL) S€LECT I }IO, TNA$IE
2 FflOr,t trEAIHER
. 3 T,HERE TII*HI LIKE

iror Rakesh shar&a


:T06 Ramesh l(umar
tro Raj"st uerna
iT13 Reena lfehta

isqu I

Fig.25.15 Using LIKE clause with SELECT command'


The name may contain any number of characters.

SELECT colurrrn narnel, column name2,...


FROM table name
WI{ERE columnname LIKE "-";

Example SELECT TNO, TNAME


FROM TEACHER
WFIERE TNAME LII(F'
-aak'
From the above statement, the % and -symbols can be used in any combination with literal
characters'

The above statement displayed the name of all the teachers whose name has an
"a" as the second character as

shown in Fig. 25.16.


Saraswati Informatics practices

fliie _(dir: i,-S Eer6h: r{+


xqr"> SELECI rHA, THRI,IE
2 FR0tt TE6SHEtI
& liir[EF rNf,I,!E LIRE
rilo IhtAltE

,T01 Rakesh Sharfld


I8t Sa$dee$ I(dushik
f85 Snnqe?ti U.tg
106 BamL.sh l(uoar
T10 Bajest trerna
I15 Jngjit sinqh
6 rGr{rg selected-
sQt) i

Fig.25.1G Using LtKE ctause with SELECT command.


25.4.7 using NOT with Speciat Operators
The spccial operator we have covered can be immediately preceded
by the Boolean Nor.
Example SELECT TNO, TNA*ME
FRON,I TEAC}IER
WHERE TNO NOT IN ('T0 i T05'):
Example SELECT x "'T03,.
FROM TEACFIER
WHERE SALARY IS NOTNULL;
Example SELECT TNO, TNAME, SALARY
FR.OM TEACTMR
WHERE SALARY NOT BETWEEN 1OOOO AND I5OOO.
The above statement displayed the TNo, TNAME and SALARy
of all the teachers whose SALARy not
lies between 10000 to 15000 ( 10000 and 15000 is including in the resulr)
as shown in Fi g.25.17.

sQr) SELECT TNO, TI{HHE,


2 FR{II.I TEAItIEB
3 t,,HERE SALfiBY NOT EETltEElt 180s0 0t{D 15008;

TNO TNNI{F SALf,B?

.T81 Rtskesh Sharna 96 00


T03 Sharnila ltaur 2 0000
T85 sangepta tJats 89 00
T1$ Bajest Uerfta 56 0&
T1't &shok singhal ;/586
;{12 ghetan Shu*li 3rr0u
T'l g Reena tlehts 5560
T14 Bhruana Laftba 450$
I15 Jagjit Singh 6500
I ro[r9 selectEd-
SQL> I

Fig.25.17 Using NOT BETWEEN clause with SELECT.


SQL SELECT Statement 549

25.4.8 Deflning a Golumn Alias


When displaying the result of query, SQL *PLUS normally uses the name of the selected column as the column
heading. ln many cases, this heading may not be descriptive and hence is diffrcult 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. If the alias contains spaces, special characters (suchs as + or $), or is case sensitive,
enclose the alias in double quotation marks (" "). The syntax is as :

SELECT column_namel AS alias_namel, column_namel AS alias_namel, ....


FROM table_name;
Exumple SELECT TNAME AS name, SALARY sal
FROM TEACHER:
In the above example, the name and the salary of all the employees get displayed on the screen. Notice that
the aliases, name and salary, in lowercase, whereas the result of the query displays the column headings in
uppercase as shown in Fig.25.18.

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)

fii: idrt telt}l Hpip, s:;.'"1,1;:": ':"


SQL> SETECT TN0 "Yeacher TNANE "TEachEr SALARY*12 "QnDual Salary" il
2 FB0t! TEACHEft:

Teat Teachir Nane gnnilal Salsry


181 RaI(Esh Sharma 6Z2sB
lB2 Jugal Hittal 18rrt&0
T33 Snarrxila Kaur 240000
T04 Sandeep Haushik 1 I00G0
T05 Sangeeta Uat5 1 068 08
l86 Raftesh l(uma)' 't 68BS0
'T07 Shlam ftrora 14!r088
T08 Shiu BrD 156 U0B
I09 Ui.uek Raorat 12 0Str0
,T10 fiajest Uerllld 67200
t't1 A5hok singhal 90s06
T12 Chetan Shukla Ir0B 0g
T13 ReeDi Hehta 66000
I1r, thuana l-anba 5lr!00
;T19 Jagjit singh 78 000
,T16 0inesh Coel
I17 Lokesh Rathore
17 rolrs selected.
SQL> I

Fig. 25.19 Using space column alias wiih SELECT.


The syntax is as :

SELECT columr 1 llcolumn2 FROM table narne:


Example SELECT TNAMEIIDOJ AS "Teachers"
FROMTEACTIER;
In the above example, TNAME and DOJ are concatenated and they are given as alias Teachers. Notice that
the Teacher name and DOJ make a single output column asshown inFig.25.20. The AS keyrvord before the
alias name makes the SELECT clause easier to lead.

f& Eiii SP"trafi Qptiors :r' ,H&


SQL> SELECT INRtlEllD0J AS "Teachers"
2 FBOTI TEECHEB;

Teachers

,Rakesh sharma 12-DED-01


jJu-qal fiitt€l frI-JUL-99
'Sharmila l(aur 66- JUN- 60
isandeep Kaushik 0B-euG- 01
Sangeeta Uats 2 0-FES- 06
Rar$esh l(um;tr 03- JUL- 97
Shyam ft)'ora -RUC-98
1 5
.shiv t m 22- SEP- 61
,Uivek Rat at 'I Z-0Gr- 01
jRaJest Uerna 07- H0u- 0 0
6shok Singhal 1 I -AU0-{9
Chetan Shukla 1A-JUH- 61
{Reena
l,lehta 1 8-JUL- 6 0
Ahrlana Lanba I 6 -JUL- 01
JagJit singh 1't - JUL-90
,0inesh Goel 't 2 -0cT- o0
!Lokesh Bathore 1 7-JUL-99
117 -0lrs selected.
lsqL>

Fig. 25.20 Using concatenation operator with columns.


SOL SELECT Statement 551

25.6 The 1JPDATE Command


If you need to change the value of the table, you can do it using UPDME command. The UPDAIE commancl
is used to update rows and we can also use WHERE clause with UPDATE comman{. The form is as :
UPDATE table name
SET column=valuel
IWHERE column=value]
The WHERE clause is optional. As we know that the name of TNO - T10 was given as "Rajest Verma". So,
to correct the name from Rajest to Rajesh, the UPDATE command should be used.
Example UPDATETEACffiR
SET TNAME ='Rajesh Verma'
WHERE TNAME ='Rajest Verma' ;

The above example changes the name Rajest Verma with the name Rajesh Verma. To see the changes, use
the SELECTcommand as

SELECT TNO, TNAME FROM TEACMR


WHERETNO='T10':
From the above example, you will see that the name of Rajest Verma has been changed as shown in Fig.
25.21.

SQL UPDNTE TERCIIEfl


2 SEI TNfitlE = 'Rajesh Uerna'
t ttl{ERE TNAHE = 'Rajest Uerna';
1rrou updated.
ISQL> SELECI IHBI,IE FBOI'I TEEGHER
' 2 I4HERE 'Tl 0' ;

TNO TNAI,IE

]rfs Bajesh Uerna

'sQr-> I

Fig.25.21 Changing the column value using UPDATE command.


25.6.1 Using Expression in UPDATE
Scalar expression can be used in the UPDATE commandi.e.,you can also set all the rows of a particular column
with the single value. For example, the management gives an increment of Rs. 200 for aii the teachers. So, to
implement the changes, write the command as :
UPDAIETEAC}IER
SET SALARY - SALARY + 200:

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;

R3kesh sh6rn3 5890


Jugal I'littal 12269
:harftile l(aur 2020e
sdndeep *aaoshik 15268
SanE€eta Uais 91rrs
Ramesh Hunaa' ttrzS0
:Shgaa firora 122fio
,Shiu 0r' 13200
,uiuek fialrat I020c
'Rajesh Uerma 58 00
Ashok Singhal 77 gA
:Chatarr ShukLa 36 00
Reena llehta 57 CtO
Bho,iana Lamba 1.7 00
Jagjit Singh 67 0D
Dinesh GopL
rLokesn Bathore

117 ro$s selected.


:sQL) |

Fig. 25.22 Changing all the rows with single value.


25.6.2 UPDATE with Muttiple Column
We can update more than one column using update command.

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

SELECT TNO, TNAME, DEPT-NO FROM TEAC}IER


WHERE TNAME = 'John Ray';
as shown in Fig. 25.23.

trle Edl Saenti' gdid?" Ldh


SQL) UPDATE TERCHEB
2 SET TllCtlE = 'John DEPT }IO
3 NHEBE THf,NE = 'Shiu

1 rord updated-
SQL> SELEUT INO, IT{EHE, DEPT HO FBOI4 IEACHER
2 +,]iERE THAttE = John Rai,;
T1IO TTIRKE DEPT

T08 Johft Bay D03

sqL>

Fig. 25.23 Updating multiple columns.


SOL SELECT Statement 553

25.6.3 UPDATE with NULL Clause


We can also enter NULL values using update command. Suppose, vou want to assign NULL value to a
SALARYcolumn of the teacher whose Tno is 'T02'.
Example UPDATETEACI{ER
SETSALARY=NULL
WHERETNO='T02':
When the above command will be executed, ttre SALARY column of T02 teacher number become NULL.
Apply a SELECT command as shown in Fig. 25.24 to display the changes made with TEACHER table.

-Fie'Edt Seaieh Do*tr Hek)'


SQL> TIPDATE IENCHEB
t 2 SET S*1f,8? = Mll-L
3 t,llERE rHo - 'T$2' ;
11 rou updated-
SqL> SELECT * FROfi TERGHEB;

IHO INf,NE TAODRESS SRTRRV DEPT DOJ

iT 01 Rakesh Sharna 2tl5-l,lal,uiga Nagar 5800 065 12-DED- 0'l


;r oz JugaI NittaI 3t, Bane5h l{agar D02 03-JUL-99
;T 03 Sharnila l{aur D-3'1, ftshok Uihar 20200 D91 06-JUN- 00
lr 04 Sandeep Kaushik l,lc-32, shaliFrar Bagh 15200 D03 08-nuG- 0'l
T05 Sanqeeta Uats G-35, Haluiya tlagar 9't 00 D 05 20-FE8-00
iT s6 Ranesh l(unrr BG-42, shaunar 8a9h 14200 D03 83_JUL_97
lr sz ShIao Rrora 50, I'lI8 FLeIS, Bohini 12200 082 15-eUG-98
:r 08 John Rag F-tr4, Xirti tlagar 1S260 D03 22-SEP- 01
lr 09 Uiuek Rar,rat E-31/27, Sec-1, Bohini 10200 Dt't t 2-0cT- 01
rT1
0 najesh Uerna D-11./130, Sec-s, Duaraka 5860 004 g7-ilou- 09
jT1't
f,shok Singhal F-1165, East Patel Hgr 770A D82 11-HUG-99
rT t2 Ghetan Shukla C-105,1oth Cross 3600 002 1 3-J UN- 01
;T13 Reena l,lehta 120, Doa Colony 5700 003 18-JUL- 00
,T14 thtrana Lanba E-1rr0, Stastik Apptt., DLF 4709 004 16 -JUL- 01
,T15 Jagjit singh A-240, Printers epptt. 6700 D04 11-JUL-98
:r16 Dinesh coel e21-Triueni ftpptt. 004 {2-0cT- 00
r17 !-okesh Rathore c-1''t, nIG Flat 003 -1
7-JUL"C9

17 rous selected.
SQL> [
jl J

Fig.25.24 Setting a NULL value to a row.


25.7 The Group Functions
The aggregate functions are group functions. they return result based on groups of rows, retber 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 :
tr AVGo
tr couNTo
D MAxo
tr MrNo
tr sr-rMo
Aggregate functions take field llames as arguments. Only numeric fields can be used for SUM and AVG.
For COUNT, MAX and IVIIN, numeric or character fields can be used. l'he ASCII equivalent of the character
fields are used in the MAX and MIN function.
25.7.1The AVG Function
This function is used to calculate the average
,SQL> SELECI 0u8( SALeRY)
of a specified column. Forexample, to select ' 2 FRUII
the average salary of the employees :
.AU[ ( Sf,LnRV)
Example SFr FCT AVG(SALAmI
FROM TEACTIER;
When you will press enter the following
output screen Fig.25.25 will displayed.

Fig. 25.25 Using aggregate function AVG.

25.7.2The MAX Function


This function is used to find the maximum
SQL> SELECI
value of the column. To find the maximum 2 FBot't
salary entered in rhe table TEACHER :
flex ( sRLeRy )
E xample SELECT MAX(SALARY)
FROM TEACFIER;
When you will press enterthe following
output screen Fig.25.26 will be displayed.

Fig. 25.26 Using aggregate function MAX.


25.7.3The MIN Function
This function is usod to find the minimum
value of the column. To find the minimum
salary entered in the table TEACHER :

Example SELECT MIN(SALAru)


FROM TEACHER;
When youwill press enterthe following
output screen Fi1.25.27 will be displayed.

Fig.25.27 Using aggregate function MlN.


25.7.4The SUM Function
When you have to add the value of column
sum( snLAfiy)
then you have to use SUl,{ function. TECCHEE;
Suppose, we have to find the sum of salary
:sUt((seLe RV )
then,
Example SFI FCT SLM(SALARY)
FROM TEACTIER;
When you will press enter the following
output screen Fig.25.28 will be displayed.
Fi1.25.28 Using aggregate function SUM.
SQL SELECT Statement 555

25.7.5 The COUNT Function


The COLINT function is used to count the
number of values in a given column, or
number of rows in a table. To count how couNT ( Tlrfil,tE)
TERCHEB;
many teacher are there in the table
TEAC}IER:
E xample SELECT COUNT(TNAME)
FROM TEACIIER;
When you will press enter the following
output screen Fig. 25.29 will be displayed.

Fig.25.29 Using aggregate function COUNT.


25.7.6 Restricting DISTINCT clause with Function
To count the total number of rows in a table, use the COUNT function with an asterisk in place of the field name
COUNT with the asterisk includes both
NULL and duplicates rows. DISTINCT has
been elimiuated for COUNT(*), because it Ib
SQL>
should have no effect in a well-designed 2
and maintained database.
C0UNI ( *)
Example SELECT COUNT(*)
FROM TEACHER;
When you willpress enterthe following
output screen Fig. 25.30 will be displayed.

Fig. 25.30 Restricting DISTINCT in aggregate function COUNT.


25.7.7 Aggregate Function in Expression
Until you have seen that the aggregate
functions with single fields as an argument.
You can also use the aggregate functions E<lp
SELETT HAx(sALtRY*12)
with the arguments which contain the FRBI,I TERCHEB;
expression. But if you do this the DISTINCT
iHnX (SfiLnRVi12)
clause is not allowed.

Example SELECT MAX(SALARY* I 2)


FROM TEAC}IER;
When you will press enter the following
output screen Fig.25.3l will be displayed.
Fig. 25.31 Expression in aggregate function.

25.7.8 Using NVL Function with Group Functions


All the groups functions except coUNT igonre the NULL values in the column.

E xample SELECT AVG(SALARY)


FROM TEACTIER;
When the above command executed, the AVG function will find the average of 14 records out of 17 records.
The average of the salary is given as 9592.851L,which is calculated as the sum cf the SALARY column divided
by 14. So, the AVG function does not inclued the NLILL values.
If you want to include the NULL values in the group function you have to use the NVL function. The ryVL
function forces group functions to include NULL values.
E xample SELECT AVC}(NV(SALARX 0)
FROM TEAC}IER;
r.k "tiiir Eeb:i; ',;, ',';' i.
In the above example, the average is
calculated based on all rows in the table
regardless of whether NULL values are 1CUG (trUL ( S6LARV , 0) )

stored in the SALARY column. The average


is calculated as total salary divided by the
total number of teachers l. e. . I 7 and the result
is shown in Fi9.25.32.

Fig.25.32 NVL function with aggregate function.


25.8 The GROUP BY Ctause
The GROUP BY clause groups the rows in the result table by columns that have the same values, so that each
group is reduced to a single row. The GROUP BY column does not have to be irr the SELECT clause.
Each
column is separated by a comma. The syntax is as :
SELECT columnnamel , columnname 2,.....
FRON{ table name
IGROUPBY columnname];
Example
SELECT DEPT_No, l'tSX(SHLRRV)
SELECTDEPI_NO, MAX(SALAR\a) FROh TESCI{ER
FROMTEACHER 8R8UP BY DEPT-HO;
GROUPBYDEPI-NO; DEPT I'r*B(SALnSY)
The above staternent displal,s the
maximum salaries for each department
(DEPT_NO) wirhout displaying the
respective departmer:t numbers. Without
department numbers, however, the results
do not look meaningfui as shorvn in Fig.
25.33.
Fig" 25.33 Using GROUP BY clause with SELECT.
tr Grouping by rnore than one column. GROUP BY applies the aggregate functions independently to a
series of groups that are defined by having a field value in common.It is also possible to use GROUp
BY with multiple fieids.
Before applying into more than one column, let us insert two records with same depafiment number and
same joining date (DOJ), l.e.,
INSERTINTOTEACF{ER
VALUES('Ti8', 'Akash Rarhi','A-52, Sansad Marg',5700,'D03','18_JLIL_2000');
INSERTINTOTEACI{ER
VALUES(T19','sirnran Chawta','D-t/12O,Sec-5, Rohini' ,47m,,DM,,'16_JIIL_2001');
After irserting the above two records, use a SELECT command to display all the records as shown in
Fig.25.34.
SQL SELECT Statement 557

; ii-; + a I,.#r :,i+-]ii "tff 1:m. ':'jt'.ii;j


-y.r.t
;SQL> SELECT * FR0l4 TEBUTIER;

;TM TNAilE rR00nEss SNLNRV DEPT DOJ

iT01 Sakesh Sharma 245-t4aluiya $agar 5800 005 12^DEC- 61


rT62 Jugil tlittal 34, Ra[esh H3gar D02 03-JUL-99
,T63 Sharmila l(aur D-S1, Rshok Uihar 20200 001 06-JUH- 06
,IB4 sandeep l(aushik tlB-32- Shalinar Bagh 152S0 D03 08-AUG- 0-l
,IB5 Sangeeta Uats g-35, l4aluiya ilagar 9100 005 2O-FEB- BO
T&6 Rrnesh l($nar BG-II2, Shaliltlar Bagh 0B D [llt
1r+2 0s-JUL-97
T07 Shlam nrore 50, t'ltG FLRTS, Eohi.)i 12299 D02 I5-ilUG-98
T68 Jchn Ray R-q4, Nirti Nagar 13208 003 22-StP- 01
T$9 Ui.uek Rar,rat E-33/P7, Sec-1, Rohini 10200 001 12-0CT- 01
S flajesh UerlDa
T1 Sec-5, D(,raraka
D-11.1-130, 5800 D04 97-N0u- 00
T11 e5hok singhal
'I12 F-1/65, East Patel Ngr 7700 002 11 -0t B-99
ChetEn Shukla C-105,16th eross 3680 D02 13-JUlt- 01
'I-13 f ePr!a $lehte 120, DDn f,olong 57{r0 003 1 8-J0L- SS
'I'tI th$dna Lamba E-1q0, Stqastik Apptt., DLr {700 DoIr 16 _JIJL- B1
'Tt5 Jagjit singh fi-?4D, Prlnters fipptt, 6700 D0,r 11 -JUL-9 I
T16 Dinesh SoPl 421-Triueni ApFtt- D OIT 12-[8T-0B
T17 Lokesh Rathore c-11, flIt Flat 003 17-JUL- 99
T18 ekash Rathi ft-52. Sansad l4arg 5706 D03 18-JUL- 00
T19 Sinran 0haula D-l1129, Spc-g" Rohini 4706 D04 16-JUL- 01

19 rovrs selected.

Fig.25.34 Records in TEACHER table.


From the above figure, Akash Rathi joined in department no. D03 and Simran Chawla in department no. D4.
Also, the joining date (DOJ) become same in both the cases. To apply a GROUP BY clause for calculating the
sum of salaries using more than one column, the DEPT-NO and DOJ grouped.

Example SELECT DEPI_NO, DOJ, SlrM(SALAna)


FROMTEAC}MR EK Ed
GROUPBYDEPT NO.DOJ: s QL) SELEf,T DEPT-I{o, DOJ, SUiI( SALARY )
z FROT4 TENCHEB
When the above query executed, the grouping of the 3 GBOUP BY DTPT NO,

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

i17 rolrs selected-

SQL>

Fig. 25.35 Grouping by more than one column.


558 Saraswatilnformatics Practices (Xl)

25.9 The HAVING Clause


,.j ;;r'i.&,
The HAVING clause restricts grouped rows that appear rsQL) S€L€CT C0UNI(*1, SftLRBV
in the result table. Groups are specified with the GROUP 2 FBOI( TEgCITER
BY clause. You can combine search conditions with the : 3 GR0UP Bt SALRRT
4 flEUING SRLAEY > 4SOO;
AND/OR NOT operation. The form is as :
C0UtlT(*) SRLABV
SELECT column namel , column name 2,.....
FROM table name 2
2
4700
5760
GROIIPBY columnname 2 58q0
HAVING condition; 6768
7700
Example SELECT COLINT(*), SALARY 91 0B
t 0206
FROMTEACHER 12289
GROI-]PBY SALARY 1 A200
14290
HAVINGSALARY>4OOO;
15298
282AS
The above statement done the grouping of
SALARY and displayed the data of only those teachers '12 roros selPcted -
whose salary is greater than 4000 as shown in Fig 25.36.
sqt>

Fig.25.36 Using HAVING clause with SELECT.


tr Illegal queries with GROUP BY clause. The WHERE clause cannot be used to restrict groups. For
example,

SELECT DEPT-NO, AVG(SALARY)


FROMTEACHER
WHEREAVqSALAR!>5m0
GROTIPBYDEPT-NO;
causes an error because it uses the WHERE clause to restrict the display of average salaries of those
depaftments that have an average salary greater than 5000 as shown inFig.25.37.

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.

sql> sELEcT DfPT_}r0,


2 FfiO],I TEhDHEE
3 GROUP 8V SEPT Nt}
4 HAUING !|RX{S6L0BV) > 10600;
HAK(S0tARY )

20200
122US
15290

Fig. 25.38 Excluding group results in TEACHER table.


25.10 Nesting Group Functions :

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

The above query shows the maximum


average salary of department as shown in the
Fi9.25.39.
Fig.25.39 Excluding group results in TEACHER table.
25.11 Ordering the Database
The ORDER BY clause determines the order of rows in the result table. Data is placed in the rows in ascending
(ASC, the default) order or descending (DESC) order. The order of the columns in the result table is determined
by the <order-item> values. The syntax is as :
SELECT column namel, column name 2,.....
FROM table name
ORDER BY order-item [DESC];
Example SELECT x
FROM TEACHER
ORDERBY TNAME;
From the above command, all the columns of TEACtIERi'table is displayed in the ascending order of
column TNAME as shown in Fig. 25.40,
560 Saraswati lnformatics practices (Xt)

air, 'OJ.'.f+' lnr r+ii'li l


SQL> SELECI *
2 FBOII TEIICHEB
3 OBDEfl BY THRIE;

TI{O TNd t,IE IADOBESS SALABV NEPT DOJ

Tlg Akash Rathi A-5?, Sansed Harg s700 D03 1 8-JUL - OD


Tf1 Rshok Sinqhal F-1165, East Patel Ngr 7790 Dgz 11 - 0UC-99
T14 0htuana LalJtba E-140, Swastik Apptt-, DtF {700 D04 6-JUL-
1 01
jT12 Dhetan Shukla C-'105,10th Cross e600 D02 13-JUN- 01
;T16 Dinpsh coel R21-Triueri fipptt- D 0Il 12-0CI-00
115 Jagjit Singh A-240, Printers tpptt- 6700 D0Ir 1 1 -JUL -C8
T08 John Ray R-{q, [irti Hagar 't9200 D03 22-SEP-01
:tA2 Jugal I'tittet 31., Rariesh Hagar D02 03-JUL-99
'l'17 Lokesh Rathore C-'t1, NIc Flat D03 17-Jt L-99
.I1 0 Rajesh Uerra D--11./f30, SPc-s, Dwarake SSO0 DOlr 07-Hlu- 00
T01 Ba|(esh sharna 2d5-l4aluiga Hagrr 5800 005 1 2-DEC-01
T06 Banesh Kunar BG-{z, Shalimar Bagh -14290 D03 0s-JuL-97
I13 Reend l4phta 128, DDA Colony 5700 D03 18-JUr - lr0
T04 SandeEp kaushik Ht-32, Shalinar Bagh 'r9s00 0s3 68- AUG- 01
'T65 Sarqeeta Uats G-35, llaluiya Hagar 9'r 00 D05 20-FE8- 60
T03 Shernila Nlur D-31, Ashok Uihar 20200 D01 06-JUN-60
T67 Shuan f,rora 56, tllG FLtTS, Bohini 12200 D02 I 5-RUG -98
T19 Simran Chaute i-11129, Sec-5, nohini 4700 Dot 16-JUL- 01
I09 UiuPk Bauat E-3X127 , Sec-1. Bohini 1 82 00 r)0, 12-OeT- 5'l
19 rc$s selected.
SQL> 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

THO TNA}IE T AD DBESS SALERV DEPT DOJ

T09 Uiuek Rarrat E-33/27, Sec-1, Rohini 10200 001 1 2-0CT - 01


T19 Sinran Char,,1a D-1t12O, Sec-s, Rohini 4700 D04 16-JUL- 0r
:T07 Shgan Arora 50, I'lIG FLATS, Bohini 12258 DOz 15-nUG-98
,T03 shafmila l(aur D-31, nshok uinar 20200 001 06-JUN-06
_lg5 Sanqpeta Uats E-35, l4aluiya tlagar 91 00 005 2O.FEB-OB
iT0q Sandeep Hausnik ilc-32, Shalimr gagh 15200 D03 08 -euG- 01
I13 Reena IlFhtr 120, DDA Colonlf 9706 D03 18-JUL- 00
T06 Bamesh NuDar BG-[2, Shatinar Bagh 14200 D03 08*JUr -97
T01 Rakesh Shrrme 2q5-ila1!iqa llagar 9800 n09 I 2- DEC- 01
,I1 0 fiajEsn Uerna D-1'1./130, sec-s, D$araka 5800 D04 07-Mtu- 00
,T17 Lokesh Rathore C-11, HtG FIat D03 1 7-JUL-99
.102 Jugal Hittal 3q, Banesh t{agar D02 03-JUL-99
T00 John Rag B-:lq, xirti Hagar 13200 003 22-SEP- 01
T15 Jagjit Singh e-2r.D, Printers epptt- 6700 00lr 1 1 -JUr -98
,T16 DinEsh Eoel 421-Triueni Appt- D04 I 2-00r - 60
T12 Chetan Shukla G-'165, 1oth Cross 3600 D02 '!s-JUil-fi
I14 Bhrrana Lamba E-'140, Suastik Rpptt-, DLF Ir700 D04 't 6-JUL- 01
iT11 Ashok Singhal F-1/65, East Patel ilgr 77gg DOz 11-AUC-9S
,I18 fikash Rathi n-52, Sensad l{arg 5700 003 18-JUL - OB

,'19 rours selected.


isor-> I

Fi$.25.41 Records are arranged in descending order wise of rNAME cotumn.


SQL SELECT Statement 561

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;

::frp S{ryoh CBkll"*


,sQL> S€r-ECr *
' 2 FRoht T€frTHEB
. 3 ORDES BV T}IA}IE DESD, TADDRESS;

TNO IHN}IE TfiBD8E SS SRLARV DEPI DOJ

iT09 Uiuek RauBt E-39/27 , Sec-1, Rohini 10200 001 'r2-0cT - 61


1T19 Simran thatrrla D-ll12g, Sec-S, Bohini 47 0S D0'{ I 6-JUr-01
,107 Shuam 0rora 50, illG FLRTS, *onini 12200 002 1 5-RUG-98
'T03 Sharnila Kaur 0:31, oshDk uihar 28200 061 E6,.JU}I*BO
T65 SiflgPeta Uatg E*35, Naluiya Nagar s1B0 085 2C-FEB- BO
,T0I SandFep Haushik t4G-?2, Shalinar Eagh 1528& DB3 88-AUt- 61
;T13 Reena )lehtd 120, DDfi Colong 5700 D03 I8-JUL_86
:T06 Raflesh l{umar 8G-42, Shalinar Bagh 1lr20S D03 83-JUL-97
:T01
'T10 Rakesh sharrna 245-HaLuiga Nagar 58 00 Dg-E 12-DEC- 6t
Rajesh Uerma D-'11/130, Sec-s, Druaraka 58 BO D BII 87-H{lU- 80
'117 Lokesh Bathore D-11, 14IG FIat D03 1 7-JUL-9 0
T02 J{gal nittal 3q, Baillesh Hagar o02 03-JUL-90
T08 John Ray B-trq, l(lrti Hagar 13200 D03 22-\EP- Bl
I15 Jagjit sinqh n-240, Printers fipptt- 6760 D0Ir 11-JUL-98
.T16 Dinash 8oe1 n21 -Triueni npptt . D04 12-OGr-00
,112 thetan Shukla e-1S5, 1oth sross s600 062 '! s-JUN-01
rf14 Bhlrana Lanba E-140, Suaslik Apptt-, DtF ETBO DO4 1 6-JUL- Sl
ifll ftshok SinEhaL F-1165, East PatPl Ngr 7700 002 1 1-RUG-99
:T18 Rka5h Bathl ft-52, Sansad Harg 5700 D[3 18-JUL-00
,19 rous selpcted-

rsQL>

Fi1.25.42 ORDER BY with multiple columns.


O ORDERBY with aggregate groups. The ORDERBY clause can alsobe used with GROLIPBY to order
groups. If you are using fhe ORDER BY clause with the GROUP BY clause then ORDER BY always
comes last.
Example SELECT *
FROM TEACMR
GROUPBYDept_no
ORDERBY TNAME;
D ORDER BY with column number. In the ORDER BY clause you can use the column number in place
of the column name. These numbers will not the order of the columns in the table but the order in the
output.
Example SELECT TNAME,ADDRESS
FROM TEACHER
ORDERBY 2DESC;
In the above example the 2 refer to the field ADDRESS in the SELECT statement.
562 Saraswati lnformatics Practices fi l)
Note. If there is NULL values in a fields then they will either follow or precede every other value in the freld.

ll ORDER BY with column alias. You can use a column alias in the ORDER BY clause.

Example SELECT TNO, TNAME, TADDRESS, SALARY*I2AS Annual


FROM TEACHER
ORDERBY Annual;
From the above command, the TEACHER table records will be displayed after ordering with the column
alias Annual as shown inFig.25.43.

.tttt Sctrort
,sQL) SELECT TNO, THRl,lE,
j 2 FRril,l IERCI{EB
3 ORDER B? finnual;
:TNO TNONE TRDDRESS AIINUAT
j

'r12 Chetan Shuk1a C-'l 05 , -l oth Bross 432 00


lrr + thtuana Lamba E-'140, Slrastik ApFtt-, DLF 56q00
lrr c Sinra* Dhaula D-1/120, Sec-s, Bohini 56408
T13 R?ena netta 128, DDA Colony 681100
,T18 Akash fiathi A-52, Sansad Narg 6648S
TE1
Itlo Bakesh Sharma 245-1'laluiga Hagar 69600
Rajesh Uerma 0-11/136, Sec-s" Duraraka 69668
lTl s Jagjit singh fi*240, Printers hpptt- 801'00
iT11 oshok singhal F-1165, East Patel tlgr 92400
IE9 Sangeeta Uats G-35, Haluiga Nagar 109200
lr oc Uiuek Rauat E-33127, Sec-1, Rohini 122499
iT07 Shgan hrora 5ll, 14I c FLfiTS, Rohini 1116400
lT08 John Ray R-44, Kirti Hagar 158q00
1T 06 Ramesh ltumar 8G-q2, Shalimar Bagh 170400
;T 04 Sandeep Kausnik llc-32, Shali0ar Bagh 182436
;I03 Sharsila Xaur D-31, Ashok Uihar 2\2405
,T 92 Jugal Hittal 34, RarEesh Hagar
rT'l 6 Dinesh GoeI 421-Iriueni Apptt.
it17 Lok€sh Rathor" C-11, ilIG FIat
)19 rours selected.

:s0L>

Fig. 25.43 ORDER By with column alias.


25.12 Formatting Query Output
You can also insert the text and expressions in your SELECT statement.
tr Putting text in the query. If you want to display some comment to be displayed in each row then it is
possible to perform this in the SELECT statement. The syntax is as :

SELECT,lolurffi namel,'Text',column nwne 2


FROM table name;
Example SELECT TNAME,'Salary is', SALARY
FROM TEACTIER;
Then the output will be shown inFig.25.44.
SQL SELECT Statement 563

SILAR}

THRME
,SOLERYIS' SfiLfiEY

_R.kash Sharm* Salary is 5880


Jugal I'littal saIirg is
SharfillaXaur Salary is 282OB
Sandeep Xaushik salaru is 't 52 G0
'sanqeeta Uats Salarg is 9't B8
.&amesh (unar SaIarg is 14260
lShgar frora Salary ls 12246
rJohn BJq salarg is '13200
luiuek Sdr,rat Salary is 18280
iBajPsh ueroa Salary is 5800
rRshok Singhal SaLarg is 7700
lchetan Shukla SalarU is 360S
lnePna tl?hta salarg is 57S0
jBhroana Lamha Salarg is t700
rJagjit singh Silary is 6780
,Dinesh Goel Salarg is
,Lokesh ftathore SaIarg is
rAkash Rathi Salarg is 5730
lSirrlran Chatola SaIary is 4790

itt roors selected.

)s8L)

Fig 25.44 Text in the query.

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:

WHERE department :'Cardiology';


(D) SELECTnameFROMHOSPITAL
WHERE department: 'ENT' AND sex: 'F' :
(c) SELECTnameFROMHOSPITAL
ORDER BYdateofadrn ;
SQLSELECT Statement 565

(d) SELECT name, charges. age FROM HOSPITAL


\ATHERE SEX:'F':
(e) SELECTCOUNT(*)FROM UOSPITAL
WHEREage<30;
$ INSERTINTOHOSPITAL
VALUES( 1 I , 'Aftab', 24, 'Surgery', '25-Feb-98', 3rJ0, 'M') ;
(g) (i) 5 (,,) 16 (iii)7s0 (lv)750
Ql0. Write the SQL for (a) to (/) and write the outputs for (g) on the basis ofthe table HOSPITAL :

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'

(g) Give the output of following SQL statements :


(/) SELECT COLINT (DISTIIiCT Charges) FROM HOSPITAL;
(i,) SELECT MIN (Age) FROM HOSPITAL WHERE Sex: 'M';
(,il) SELECT SUM(Charges) FROM HOSPITAL WHERE Sex:'F',
(lv) SELECT AVG (Charges) FROM HOSPITAL'#HERE Dateofadm <'12-Feb-98';
Ans. (a) SELECT*FROMHOSPITAL
WHERE department :'Cardiology' ;
(6) SELECTnameFROMHOSPITAL
WHERE department: 'Orthopaedic' and SEX :'F';
(c) SELECTnameFROMHOSPITAL
ORDER. BY dateofadm ;
(d) SELECT name; charges, age FROM HOSPITAL
WHERE SEX:'M';
(e) SELECTCOUNT(*)FROM HOSPITAL
WHERE age > 20 ,
g) ]NSERTINTOHOSPITAL
\ALUES (i I "'Mustafa', 37, 'ENT', '25-Feb-98', 250, '1,,1') ;

[q) (l) s (ii\ t2 (ii,) 1600 (,v) 387"50


566 Saraswati lnformatics practices (Xl)
Qll' Write the SQL commands for delete (a) to
f) and write the outputs for (g) on the basis oftable STUDENT:
TABLE:STUDENT
No. Name Age Depaftment Dateofadm Fees Sex
I Pankaj 24 Computer 10-Jan-97 120 M
2 Shalini 21 History 24-Mar-98 2W F
3 Sanjay 2. Hindi l2-Dec-96 300 M
4 Sudha 25 History 0l -Jul-99 400 F
5 Rakesh D Hindi 05-Sep-97 250 M
6 Shakeel 30 History 27-Jsn-L)B 300 M
7 Surya Y Computer 25-Feb-97 210 M
8 Shikha 23 I-Iindi 3lJul-97 2ffi F
(a) To show all information about the students of History department.
(b) To list the name cf femare students who are in Hinci department.
(c) To lisi names of ail students with their date of admission in ascending order.
(d) The display Student,s Narre, charges, age for male students only.
(e) 'l-o count the number of strrdents with agp23.
(f) To insert a new row in the STUDENT table with the following data :
9,' Zaheer',6,'C omputer,,, 12 -Mar-97,, 23 0,,M, .
3
(g) Give rhe output of the following SeL statements :
(,) SELECT COLTNT (DISTINCT department) FROM STUDENT
(ii) SELECTMAX(Age) FROM STUDENT WHERE Sex:,F,;
(i,l) SELECT AVG(Fees) FROM STUDENT WHERE SEX : ,M,:
(lv) SELECT SUM (Fees) FROM STUDENT WUenB Our"ofu'j, .,9 1 -yun_gg,,
Ans. (a) SELECT*FROMSTUDENT
WHERE department :'History, ;
(b) SELECTnameFROMSTUDENI
WHERE departrnent = 'Hindi' and SEX:'F, ;
(c) SELECTnameFROMSTUDENT
ORDERBydateofadm;
(d) SELECT name, charges, age FROM STUDENT
WHERE sex:'M' ;
(e) SELECTCOUNT(*)FROMSTUDENT
WHEREAGE>23;
$ INSERIINTOSTL]DENT
VAL UES (9,'ZAFIEER', 3 6,'Compute r,,' l2_Mar -97,, 23 0,,M,) ;
G) (,) 3 (ii) 2s (iii) 236.00 (,r) 1080
Ql2' Write the SQL for (a) to (/) andwrite the output of the (g) on the basis of the table TEACHER :

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

7 ShivOm 4 Computer 25-Feb-97 21@ M


8 Shalakh a 33 Maths 3l-Jul-97 20000 F
(a) To show all information about the teacher of History department.
(b) To list the name of female teachers who are in Maths department.
(c) To list names of all teachers with their date of admission in ascending order.
(d) The display teacher's Name, Salary age for male teacher only.
(e) To count the number of teachers with agp23.
A To insert a new row in the TEACHERtable with the following data :

9, 'Raja', 26, 'Comouter', '13-lr{ay-95 }, 2300, 'M,.


(q) Cive the output of the following SQL statement :
(,) SELECT COTINT(DISTINCT departrnent) FROM TEACIIER;
(iD SELECT MAX(Age) FROM TEACHER WHERE SEX:'F';
(ri) SELECT AVG(Salaq,) FROM TEACHER WIIERE SEX :'M';
(/v) SELECT SLIM(Salary) FROM TEACHER WHERE DATEOFJOIN < ,12-Jut-96,;
Ans. (a) SELECT*FROMTEACHER
WHERE departrnent :'History' ;
(b) SELECTnameFROMTEACHER
WHERE department :'Maths' and SEX :'F' ;
(c) SELECTnameFROM TEACHER
ORDERBY dateofioin;
(d) SELECT name, salary age FROM TEA-CFIER
WHERE sex:'M';
(e) SELECTCOUNT(*)FROMTEACHER
WHEREage>23;
(fi INSERTINTOTEACHER
VALLIES (9,'Raja',26, 'Computer', '13-Mav-95', 2300, 'NI') ;
G) (ii, 20050.00 (iv) 2300
(,) 3 (ii) 35
Q13. Write SQL commands for (a) to (c/) and write the outputs for (e) and (/) onthe basis oftables CLUB and
COACHES:

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

3 DIVYA 3OO CHEMISTRY 62 2


4 ARUN 350 PI{YSICS 6 I
5 SABINA 5OO MATHEMATICS 70 I
6 JOHN M CHEMISTRY 55 2
7 ROBERT 250 PFTYSICS & I
8 RUBINA 450 MATHEMATICS 68 I
9 VIKAS 5OO COMPUTERSC 62 I
IO MOHAN 3OO MATHEM,ATICS 57 2
(a) List the names of those stucients who have obtained Div I sorted by NAME.
(6) Displaythereport,listingNAME.sTlPEND,SUBJECTandamounfofstipendreceivedinayear
assuming that the STIPEND is paid every month.
(c) To count the number of students rvho are either PHYSICS or COMPUTER SC graduates.
(a) To insert a new row in the GRADUATE table :
I i,'KAJOL" 3OO,'COMPI]TER SC" 75, I
(e) Give the output of follorving SQL statement baseci on table GRADUATE :
(,) SELECT MTI..I(AVERAGE ) FROM GRADUATE WHERE SUBJECT:'PHYSICS';
(,,) SELECT SUM(STIPEND) FROM GRADUATE WHERE DIV : 2;
(rir) SELECT AVG(STTPEND) FROM GRADUATE \&/HERE AVLRAGE >: 65 ;
(,,) SELECT COUNT(DISTINCT SUBJECT) FROM GRADUAIE;
Ans. (a) SELECT NAMEFROMGRADUTE WHERE DiV : I ORDERByNAME;
(b) SELECT NAME, STIPEND, SUBJECT, STIPEND *I2 FROMGRADUAIE;
(c) SELECT COUNT(*) FORIVI GRADUATES WHERE (SUBJECT: ,pFIySrCS'
OR SIJBJECT :'COMPUTER SC');
(d) INSERT INTO GRADUATE VALUES (l l, KAJOL" 300, 'COMPTJTER SC"75,1);
(e) (i) 63 (1,) 1000 (iii)450(i1,)4
Ql5' WriteSQLcomntandsfor(a)to(d)andwritetheoutputs for(e)afi(fionrhebasisoftablesEMPLOyEE
andINCHARGE:
SQLSELECT Statement 569

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

8 RUBINA 9450 MAINTENANCE 22-Feb-98 37 F

9 VIKAS 75OO COMPUTEP. l3-Jan-94 4l M


IO MOHAN 93OO MAINTENANCE l9-Feb-98 3'7 M
(a) List the names of the employees who are more than 34 years old sorted by NAME.
(b) Display a report, listing NAME, BASIC, DEPARTMENT and annual salary. Annual salary equals
BASICX I2.
(c) To count the number of employees who are either working in PERSONNEL or COMPUTER
department.
(d) To inset a new row in the EMPLOYEE table .

I 1,'VIJAY', 93 00,'FINANCE',' I 3 -Jul-98', 3 5,'M'


(e) Give the output of the following SQL statement based on table EMPLOYEE ;
(I) SELECT SUM(BASIC) FROM EMPLOYEE WHERE DEPARTMENT: 'PERSONNEL';
(,r) SELECT AVG(BASIC) FROM EMPLOYEE WHERE SEX :'F';
(,li) SELECT MAX(BASIC) FROM EMPLOYEE WHERE DATOFAPP > '22-Feb-97';
(,v) SELECT COUNT(DISTINCT DEPARJ'MENT) FROI\4 EMPLOYEE;
Ans. (a) SELECT* FROMEMPLOYEE WHEREAGE>34ORDERBYNAME:
(b) SELECTNAME, BASIC. DEPARTMEI"T. BASIC* 12 FROM EMfLOYEE;
(c) SELECTCOLTNT(*)FRON4EMPLOYEE
W H E RE D EPARTI\4 EN T :' ER S ONlr- E L' O R DEPARIMEN T
P
:'COMPUTER ;
(d) INSERTINTOEMPL.OYEEVALUES(I1,VIJAY'.9300,'FINANCE,'13-Jul-98',35,'M');
(e) (,) 2a600 (ir) 8750 (ri,) e500 (n, 5
Ql 6. Write SQL r:ommands for ( i) to (vii) on the basis of the table STUDENT.
TABLE: STUDENT
Student No. Class Name GAME Grade SUPW Grade
10 7 Sanreer Cricket B Photography A
II 8 Sujit Tennis A Gardening C

12 7 Karnal Swimnring B PhotograPhY B


13 7 Veena Tennis C Cooking A
14 9 Archana Basketball A Literature A
15 l0 Arpit Cricket A Gardening C

(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

(a) To select the ltemNarne purchased after 3l -Oct-97.


(6) fo list the ltemNarne. which are within the Warranty period till present date.
(c) To list the ttemName in ascending order of the date of purchase where quantity is more than 3.
(4 To display ltemName, CostPerltern, and Quantity whose Wananty is over.
(e) To count the number of items whose cost is more than I 0000.
(l) To insert a new record in the Lab table with the following data :
8,'VCR', I 0000, 2,'2-F eb-2000', 1,2.
g) Give the output ofthe following SQL comrnand :
0) SELECT MrN@TSTINCT Quantitv) FROM LAB;
(,,) SELECT MlN(Warranty) FROM LAB WTIERE Quantity:2;
(ii,) SELECT SUM(CostPerltern) FROM LAB WHERE Quantity>2;
(lv) SELECT AVC(CostPerltem) FROM LAB WHERE DateofPurchase <'l -Jan-99';
Ans. (a) SELECTitemnameFROM lab
WHERE dateofo urchase > {3 I lA 197 } ;
(b) SELECT itemname, cosrperitem, quanrity FROM lab
WHERE date( ) - dateofpurchase < warranty;
(c) SELECT itemname FROM lab
ORDER BY dateofpurchase WHERE quantity > 3;
(d) SELECT itemname, costperitem, quantity FROM lab
WHERE date( ) - dateofrurchase > warranty;
(e) SELECT COLINT(*) FRoM lab
V/HERE costperitem > i0000;
(/) INSERT INTO lab VALUES(8,'VCR', 10000,2,2-Feb-2000', 1,2);
G) (i) 5000 (,, I (iii) 80000 (ry) 23800.00
Ql9. Given the following Teacher relation : Write SQL command for quesiion (a)to (/) and the output for (g).
TABLE:TEACHER
No Name Depaftment Dateofioining Salary Sex
l. Raja Computer 21-May-98 8m0 M
2. Sangita History 2l-May-97 9000 F

"3, Ritu Sociology 29-Aug;98 8000 F


4. Kunrar Linguistics 13Jun-96 10000 M
5" Ver,katrarran lJ istory 3l -Oct99 8000 M
5. Sidhu Con:puter 21-May-86 14000 M
7. Aishu,ar,va Socioiogy l1-Jan-98 12000 F

(a) To select all the information of teacher in Conrputer department.


(b) To list the name of female teachers in l{istoLy department.
(c) To list all names of teachers with date of admission in ascending order.
(a) To display Teacher's name, Department, and Salary of female tcacher.
(e) To count the number of items whose salary is less than 10,000.
(/) To insert a new record in the Teacher table with the following data ;
8, 'Mersha', 'Conrputer', 'l-Jan-2000'. 12000, 'M',
(g) Cive thc output ofthe following SQL eommaRd :
(,) SELECT MIN(DlSTINeT Salary) FROtul Teaelrer;
(i, SELECT MiN(Satary) FROM'Ieacher WHERE Sex-'M't
(iil) SELEC T SUlvl(Salary) FROIV4 Teaeher WHERE Departmerrt -'Hisiory';
(iv) SELECT AVO(Salary) FROM Teae her WHERE Dateof,oining <'l-Jan-98';
t--

Ans. (a) SELECT * I--ROM Teacher WHERE Teacher:'Cornputer';


(b) SELECT * FROM Teacher WHEI{E Sex -'F'AND Deparrment:'History';
(c) SELECT Name FROM'Ieacher ORDER BY Dateofiorning;
(4 SELECT Name, Departnrent, Salary FROM Teacher WHERE Sex:'F':
(e) SELECTCOUNT(*) FROIvI Teacher WIIERE Salary < i 0000.
(fl INSERT INTO Teacher VALUES (8, 'Mersha', 'Computer', ' i -Jau--2000,, 12000, 'M');
k) All the outputs are same whether the new 8th row is included or not
(, 8000 (1, 8000 (i1,) 17000 (rv) I 1250
Q20. Giventhefollowingfamilyrelation.WritesQLcomrnandforquestion(a)to(flandtheoutputfor(g).
TABLE: FANIILY
No. Name FemaleMembers MaleMembers Income Occupafion
1 Mishra 3 2 7000 service
2 Gupta 4 I 50000 business
3 Khan 6 3 8000 mixed
4 Chaddha 2 2 25000 business
5 Yadav '/ 2 20000 mixed
6 Joshi 3 2 14000 service
7 Maurya 6 3 5000 farming
8 Rao 5 2 10000 service
(e) To select all the information of family whose occupation is service.
(b) To list the name of farniiy where fenral rnembers are more than 3.
(c) To list all names of farnily *'ith income in ascending order.
(d fo display family's name, male members and occupation of business family.
(e) To count the number of family shoes income is less than 10,000.
(fl To inseft a new record in the Family table wirh the following data :
'D'souza', 2, 1. 15000, 'Service'.
(g) Give the output of the following SQL command :
(i) SELECTMIN(DISTINCT lncome) FROM Family;
(ll) SELECT lVl ln- (Femal eM embers) F RoM Fam i ty wHERE occupation:'mixed';
(iil) SEILECT SU M(incorne) F RON1 Farni ly WI{ERE Occupation:'service';
(n) SELECT AVC(lncome) FROM Family;
Ans. (a) SELECT * FROM Farnily WHERE Occupation:'service';
(b) SELECT name FROM F-arnity Wtl ERE Femalemembers > 3 ;
(c) SELECTname, IncomeFROMFarrilyORDERBY Income;
(4 SELECT Name, MaleMembers, Occupation FROM Famity WHERE Occupation:'business';
(r) SELECT COUNT(lncorne) FRONI Family WHERE Income < 10000;
f) INSERT IN fO FamilyVALUES('D'souza',2,1.15000.'service');
G) (i) 5000 (r0 6 (iii) 31000 (r1,) 17375
Q2l. GiventhefollowrngEMPLOYEE relation.WrileSQl-cornmandforquestion(a)to(x)andtheoutputfor
(l)
TABLE: EMPLOYEE
ENO ENAME JOB MGR HIREDATE SAL COMIVI DEPT
7369 Sunita Sharrna CLERK 7m2 17-DEC-80 2800 n
7499 Ashok Singhal SALESMAN 7698 2O-FEB-8I 3600 300 30
1521 Rohit Rana SALESMAN 7698 22-FEB-8I 950 500 30
SQL SELECT Statement 573

i566 JyotrLarrba MANAGER 1839 02-APR-81 4915 20

1654 Marlin S. SALESMAN 1698 28-SEP-81 6250 1400 30


1698 Binod Goei MAN.\GER 7819 0I-MAY-81 -s850 30

1182 Chetan Gupta IvIANACER 7839 09-JLIN-8i 245A 10

7788 Sudhir Rawat ANALYST 7566 19-APR-87 5000 20

1839 Kavita Sharma PRESIDEI'JT 17-NOV-81 5000 10

7&44 Tushar Tirvari SALESMAN 1698 08-SEP-81 4500 0 30

18'76 Anand R.athi CLERK '1788 23-MAY-87 6100 n


7900 Jagdeep Rana CLERK 7698 03-DFIC-81 4950 30
'7902 Sumir Vats ANALYST 1566 03-DEC-81 3500 3600 n
7934 Manoj Kaushik CLERK 71U 23-JAN-82 5300 10

(a) To select all the columns of the above table.


(6) 'fo list the name and employee number from the above table.
(c) To list all names, hiredate and salary'of all employees
(4 To display the employee natne and the incremented value of SAL as SAL + 300.
(e) Tolisttheemployeenarneanditsannual salary(Annual salary:12*sal +100).
$ Display the ename and sal u,here comm is NULL.
k) fo list the distinct departrnent number from the table.
(/r) To list the unique jobs frorn the table.
(,) To list the salary where saiary is less than the commission.
A To iistthe saiarybet.veen 1000 and2000.
(k) To list the mgr which are lN 7902. 1566,7'788.
(i) To list the ename starting ,,vith 'S'.
(nr) To listthe all the columns where salary is greaterthan 1100.
(r) To list all the columns in the ascending order of hireCate.
(o) To list all the columns in the ascerrding order of deptno and descending order of salary.
(p) fodisplaytheemployeenameandjobofemployeeshiredbetweenFeb20, 1981 and May l, 1981.
(q) Display the ename and deptno of allemployees in department 20 and 30 in alphabetical ORDER BY
narne.
(r) To list the name and salary of all the employees who earn more than 1200 and are in department I 0
or 40.
(s) lb list name and hiredate of alI the employees rvho are hired in I 98 I.
0) To list all the employees who do not have manager.
0r) To list name and salary of all employees who earn commissions.
(v) lblistthenamesofall employeeswheretheseconci letteroftheirnameisana.
(rr) Tolistthenamesandjobofalltheemployeeswho'uvorkindepartrnent20andtheirmanagerisTT88.
(x) To tistthe deptno, job arrd sur.n of salary group by deptno and job.
(v) Write the output of the followii..g:
(r) SELECT ENAME, l2*SAL + CON{M FROM EM PLOYEE \ THERE ENAME :'Ashok Singhal';
(li) SELdCT ENAME l.tOB AS "Ernployee" FROM EMPLOYEE;
(ri) SELECT ENAME FROM IIMPLOYEE WHERE ENAME L,IKE' a%';
(iv) SELECT ENAME, MGR FROM EMPLOYEE WHEREMGR ISNIJLL;
(v) SELECT AVG(SA[.), MAX(SAL), M IN(SAL), SUM(SAL) FROM EM PLo\rEE W H ERE JoB
LIKE,'SALE,S%'I
(vi) SELECT AVGNVL(CO'N4M,0) FROM EMPLOYEE;
(vll) SELECT DEPTNO, AVG(SAL) FRON{ EMPI-OYEE GROUP BY DEPTNO;
(uiii) SELECT COUNT(*) FROI\{ EMPLOYEE WHERE DEPTNC:20;
574 Saraswati lnformatics practices (Xl)
(,.x) SELECT COUNT(COM M) FROM EMPLOYEE WHERE DEpTNO : 20;
(x) SELECT DEPTNO, MAX(SAL) FROM EMPLOYEE GROtJp By DEPTNO
HAVTNG MAX(SAL)>2900.
Ans. (a) SELECT * FROM employee,
(b) SELECT erlame, empno FROM employee;
(c) SELECT ename, hiredate, sal FROM employee;
(4 SELECT ename, sal+3gg FROM employee:
(e) SELECTename, l2xsal-i100 FROMemployee;
(n SELECT ename, sal FROM ernployee WH ERE cornm IS NULL:
(g) SELECT DISTINCT(deptno) FROM employee;
(/l) SELECT DISTINCT(ob) FROM employee;
(,) SELECTsa| FROM employee WHEREsa| <comm;
0 SELECT sal FROM employee WHERE sal BETWEEN 3000 and 4000;
(t) SELECT mgr FROM employee WLTERE mg IN (7902,7566,7788);
(D SELECT ename FROM enrployee WHERE ename LIKE'SoZ';
(ru) SELECT x FROM ernployee WHERE
sal> 3100;
(a) SELECT * FROI\,Iemployee ORDER By hiredate;
(o) SELECT * FROM employee ORDER By deptno, salDESC;
(p) SEI,ECT ename, job FR.OM employee
wHERE hiredate BETWEEN,20_F'eb_ I g g 1' AND'0 I _Nov- I gg I'
(q) SELECT ename, deptno FROM ernployee
WHERE deptno IN(20,30)
ORDER BY ename;
(r) SELECTename!salFROMemployeeWHEREsal>l200AND(deptno:l0ORdeprno:40);
G) SELECT enarne, h iredate FROM employee
WHERE hiredate <'0 1 -Jan-82,
(/) SELECT * FROM ernployee
WHEREmgTISNULL
(u) SELECT ename, sal FROM emplo-v-ee
WHEREcommISNOTNULL
(v) SELECT ename FROM employee WHERE ename LIKE' a%o';
(w) SELECT ename, job FROM employee WHERE deprno:20 AND mgr: 778g;
(x) SELECT deptno, job, SUM(sal) FROM employee GROUp By deptno, job;
O (r) Ashok Singhal 43500
(ir) Employee

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)

4900 6250 3600 19600


(vr) AVG(NVL(CONIM.0)

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

mem code Character 3 Member code


mem_name Character 30 Member name
mem_add Character 50 llember address
mem_phonc Character 1 Member contact number
no_of bk Numeric 3 Number of books stock
no_of iss Numenc. 3 Number cf books issued
Answer the following using above table :
(i) Display all distinct records using SeL command.
(ll) create a new table using SeL commands liorn the existing table MEMBER.
(lli) Display the report mem code wise frornthe table MEMBER.
(rv) Display all the records from the MEMBER price wise in
descending orcler.
(v) Display the detail of a[ the members whose narne starls with letter p.
(vr) Display all the records whose mem code is between r 00 to 400.
(vil) Display the record of a member whose phone number is 7i7 1234.
(vrii) Add new field in the table cailed F no_mem of Numeric type and
width is 3.
(rr) Dcle:e all the rows of a table.
(x) Drop the iable.
l0' write sQL commands for the queries (a) to (fl and write the output of the
SeL commands given in (g)
based on a relation EMPLOYEE shown below.

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 :

7,'TARIK SINGH', 45OOO,'SOUTH', 45,,C,,'E,LEC'.


(g) W'rite the output olthe following commands based on the given
relation EMpLO./EE :
(r) SELECT MrN(AGE) FROM EMpLoyEE;
(i,) SELECT SUM(SALARY) FROM EMPLOYEE WHERE GRADE:
A';
(Iii) SELECT AVG(SAI,ARY) FROM EMPLOYEE WHERE DEPT:'CIVIL';
(rr) SELECT COTINT(DISTTNCT DEPT) FROIVT EMPLOyEE;
ll' write SQL commands for the queries (a) to (fl aud write the output of the
sel. commands given in (g)
based on a relation STLTDENT shown below.

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

5 Rakesh 2 Hindi 05-Sep-97 '25A M


5 Shakeel 30 History 27-hn-98 300 M
7 Surya Y Cornputer 25-Feb-97 Zrc fvl
8 Shikha 23 t{indi 31-Jul-97 200 P

(a) To show ali infonnation about the students of Histor v- depi.


(D) To list the names of female students who are in Hindi dept.
(c) To list narnes of all students with their date of admission in ascendins order.
(A To display student's nanle, fee, age for male students only.
(e) To count the nuntbei of students with dge<23.
fi To insert a ne\4/ row in the STUDENT table with the following data :
9,' Zaheer', 3 6,'Computer',' I 2-Mar-95, 23 0,'M'
(g) Give the output of follorving SQL statements .
(, SELECT COUNT(DISTINCT dept) FROM STUDENT;
(,, SELECT MAX(Age) FRON{ STUDENT WHERE Sex: "F";
( i rl) SELECT AVG(tree) FROM STUDET.T- T WHERE Dateofadm <'0 i -J an-98';

(iv) SELECT SUM(Fee) FROM STUDENT WHERE Dateofadm <'01-Jan-98';


12. Write SQL commands for the queries (a) to (l) anci u.rite the output ofthe SQL commands given in part (g)
based on a relation TOY SHOPPE shown belorv :

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

4 Creative Mind Building Blocks 800 18 5 8

5 Ping Pong Two Player 500 53 5 9


6 Race-Trace Mechanical 1800 17 9 12

(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 :

'StuffTov', 60C, 15, 1, 6


7, 'Jerry'',
(g) Write the output of the following (Consider the table TOY_SHOPPE as given above):
(, SELECT MAX(Pice) FROM ToY_SHOPPE;
(i,) SELEC I' SUlvf(Quantity) FROM TOY_SHOPPE WHERE Category: 'StuffToy';
(,,,) SEI-ECT AVG(Price) FROM IOY_SHOPPE WHERE Quartiry < 20;
(/r,) SELECT COUNT(DISTINCT Category) PROM TOY_SHOPPE;
13. Write SQL cornmands for the queries (a) to (/) and write the output of the SQl, commands givenpart(J)
based on a relation STUDENT shown below :

RELATION:STUDENT
No. Name Stipend Stream AvgMark Grade Class
1 Neha 450.00 Medical 89.2 A llc
578 Saraswati Informatics Practices (Xl)

2 Damini 400.00 Conurerce 78.5 B l2B


3 Gaurav 250.00 Humanities &A C I lA
4 Anu 300.00 Commerce 61.5 C l2B
-i Vikas 500 00 Non-rnedical 92.0 A 12A
6 R.ubina 450.00 Non-medical 88.5 A 12A
(a) -lo displal,the names of all students who are in Medical Stream.
(D) To display name and average of all the students having Avg<70.0.
(c) To display list of all the students rvith stipend>350.00 in ascending order of Name.
(rf To display a report with Name, Marks for each student in the table. Marks are calculated as AvgMark*5,
(e) 1o display'the Stream and the number of students of each stream in the table STUDENT.
ffi Ta insert a nevy student in the table STUDENT with the follou,ing data :
7,'Sabina, 500.00, Non-medical', 90.6,'A','l iA'
(g) Write the output of the tbllowing :

(,) SELECT MIN(AvgMark) FROM STUDENT;


(ii) SELECT SUM(Stipend) FROM STUDENT WHERE Grade:'A';
(iii) SELECT AVG(Stipend) FROM STUDENT WHERE Stream:'Commerce',
(iv) SELECT COI-INT(DISTINCT Stream) FROM STUDENT;
14. Write SQL commands for the queries given FROM (a) to A and write the output of the SQL commands
given in part (g) based on a relation LIBRARY shoran below :
RELATION: LIBRARY
No Title Author Subject Publisher Quantity Price
I Data Structure Lipschute DS McGraw 4 217.00
2 DOS Guide NORTRON OS PHI 3 175.00
3 Turboc C++ Roboft Lafore Prog Galgotia 5 270.00
4 Dbase Dummies Palmer DBMS I :stakM 7 130.00
5 Mastering Windows Cowart OS BPB I 225.C0
6 Computer Studies French FND Ga)gotia 2 75.00
7 COBOL Stern Prog JohnW 4 1000.00
8 Guide Network Freed NET Zpress 3 200.00
9 Basic for Beginners Norton Prog BPB 3 40.00
l0 Advanced Pascal Schildt Prog McGraw 4 350.00
(a) To dispiay the title of all books with Price between 100 and 300.
(6) To display Title and Author of allthe books having type Prog and publisher b;r BPB.
(c) To display list of all the books with price more than 130 in ascending order of Qty.
(rfl To display a report with Title, Misplacement Charges for each book in the table.
(e) To display the publishers and the number of books of each publisher in the table LIBRARY.
f) To insert a new bcok in the table LIBRARY with the following data :
I l,'CompSc. Cl-l-','Rita','Khanna', 1225
(g) Write the output of the following :

(i) SELECT IvIIN(Price) FROM LIBRARX


(i, SELECT SUM(Price*Qty) FROM LIBRARY WHERE Qry > 3;
(,ii) SELECTAVG(price) FROM LIBRARY WHERE Qty<4;
(lv) SELECT COUNT(DISTINCT Publisher) FROM LIBRARY;
Chapter - 26

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 :

O Single Row functions.


tr Multiple Rorv functions.
26.2 Single Row functions
Single Row functions operate on the single row and return one result per row. They can accept one or more
arguments and retum one value for each row. They can be used with SELECI WHERE, and ORDER BY clause
and also they can be nested. An argurnent can be of following types :

tr User supplied constant.


O Variable name
tr Varibale value
tr Expression.

Single row fuRctions can fall in the following categories :

tr Character
tr Number
tr Date
tr Conversion
tr General

26.2.1 Character Functions


This group offunctions is uscd with character variables.Single row character function take character data as
input and return either character or number values. Character functions can be furlher divided into two
categories :

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

The syntax is as : iSQL>

LOWER( string/column name) ilotlER t TNRI{E }

Purpose. Returns a specified character expression in rakesh sharma


jugal nittal
lower-case letters. It takes any string or column and sharnila kaur
converts any letter to its lowercase. ,sandeep kaushik
sangeeta uats
Ex a mp I e SELECT LOWER(TNAME) rarDesh kunar
shyan arora
FROMTEACTIER: ;john rag
]uiuek raurat
The above query shows the name of all the lrajesh uerna
teachers in the lowercase as shown in Fig 26,1. ,asholr singhal
ch8tan shukla
repna nehta
Shoana lamha
rjagjit singh
dinesh goel
ilokosb rathorP
lakJsh rathi
.simrao chaula

19 rofrs sel*cted.

'sQL> I

_Jl*
Fig. 26.1 Names in lowercase using LOWER function.
T]PPER
The syntax is as :

UPPER( string/column name)


SQL Functions 581

Purpose. Retums a specified character expression in


upper-case letters. Ttris function does the opposite of -,Srtbrr-; &c,lh
sQr> SELECI UFPEE(THA}E} FROH TEf,CHER;
LOWER function.
E x a mp I e SEI.ECT LIPPER(TNAME)
UPPtB ( rlrAlrE l
.RRKESH SHEflUff
FROMTEAC}IER;
'JUGAL T'II TTRL
The above query shou,s the name of all the TSHRRI,tILS lt{UB
iSRilDEEP ltfiUSHIl{
inFig26.2.
teachers in the lowercase as shown ;S*NGEETE UfiTS
BRI4ESH HU},IflR
SHVAI'I AEORA
JOH}I RAY
UIUEIi R0trfiT
BSJESI{ UERI4O
ASHOI( SINGHRL
CIiETRN SIIUXLR
TREExR flEilT(
iBHVIRIM LBIEE
IJnGJII SINGH
lDINESH GOEL
TLoNESI 8fiTiloBE
,fi1(ASll Rf,THI
lslt{ReN c[nULR
19 ror,r5 selected.

Fig.26.2 Names in uppercase Using UPPER function.


INITCAP
The syntax is as :
96ar!{r
SQL> SELECI IHIICAP(INAIIE) FROi,I TEACHER;
IMTCAP( string/column name)
I NTTCAP ( INR}IE )
Purpose. Returns a specihed character expression by Rakesh sharna
converting the f,rrst letter of each word to uppercase JugeI }fittal
Sharmila Xaur
and remaining letter to lowercase. 'Sandeep l(aushik
Sangeeta Uats
E x am p I e SELECT INTICAP(INAME) Bail€sh ltumar
FROMTEACTIER; Shgam Crora
iJohn Rag
The above query shows the result as shown in Uiuek Rae,at
R*jesh Uerma
Fig26.3. Ashok Singhal
ChetaE ShukIa
Beena tlehta
thuana Lanba
Jagjit singh
Dinesh GoeL
-Lokesh Fathore
okash Rathi
siEran Ehau1a

19 rou,s selPctPd.
sqr> I

Fig. 26.3 Names first character in uppercase and remaining


in lowercase Using INITCAP function.
You can also use the above function in the SQL query WIIERE clause. For example,
582 $araswati lnforrnatics Practices (Xl)
Example SFIFCTTNO,TNAI\.IEFROMTEACI#R
WHEPC TNAME = INITCAp('rakesh sharma')

CONCAT
The syntax is as :

CONCAT(stringl/column namel, string2/column name2)


Purpose. Returns by concatenating the first charcacter value to the second character value.
Example SELECT CONCAT(TNAIVE, TADDRESS) FROM TEACHER.;

The above querv shows the result as shown inFig26.4.

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 :

SUBSTR(character expression,starting yalue, number of character)


Purpose. Retums a speciflled number of characters from the given character expression, This tells SeL to
clip
out a subsection ofthe string or eharacter expression, beginning at position starting value and,continuing
for
number of eharacters.If you do not sp€eify the number af characteri,SuBsTR wiliclip beginning at stan
and
continuing to the cnd of the string,
Example SELECT SUBSTRGNAME, l, 4) FROM TEACIIER;
The above query rdsult in the first four charaetcrs of all the teaehers name.
SQL Functions 583

LENGTH
The syntax is as :

LENGTH( Character expressionl String)


Purpose. Returns the length of the specified expression, i. e. , LENGTH tells you hov,r long a string is - how many
characters it has in it, including letter, spaces and anything else.

Example SELECT TNAME, LENGTH(TNAME) FROM TEACIIER;


LPAD
The syntax is as :

LPAD(column/ expression, n,'string')


Purpose. Returns the character value right justified to a total width of n character positions.
Example SELECT TNO, TNAME, LPAD(SALARY, 12,'x1 FROM TEACIIER;
The above query shows the result as shown inFig26.5.

'Blal,,Etr
St
sQL> SELECI TNo, LPED(SfiLRRY, 12, FRON TEACHER;

rNO TNRHE LPAD(SELRBY,

T01 Bakesh Sharna ***+**+r58 0g


I02 Jugal I'littal
T03 Sharnila ltaur ***r*l*2 02OO
T04 Sandeep Eaushik *******i520€
T05 Sangeetd Uats ****ri*.9'l 0{
T06 Ranesh l{umar **.r*r*142 00
1T07 Shgim Rrora l***:r*12200
rT08 John Ra!! *******'132 BO
,T09 Uiuek Baorat *+*****1 S2 00
& Ba j esh llerma
'T't +**xr***5800
,T11 A5hok Singhal *****r**77 00
T12 Chetan Shukla ***r+Ir*36 B0
,T13 Reena Hehta r******157 B0
iT14 Bhuana Lanba *****r*.47 0S
.T15 Jagjit Singh +**+i***6708
I16 Dinesh Goel
lT17 LokPsh Rathore
,T18 ekash Bathi **+***;+57 60
'T19 Sinr:n ehalrla ********4708
19 rous sel?cted,
SOL> I

Fig. 26.5 Padding salary values using PAD function.


TRI]\,I
The syntax is as :

TRIM( leadlng/tralllng/both eharaeter !'ROM eharactm cxpresslon)


Pur'pose. Returns the trim heading and trailing characters or both from a eharacter stdng,
E xample SELECT CONCAT(TRIM(TNAME),TADDRESS) FROM TEACI{ER;

The above query shows the fesult as showfl in Fig 26,6.


584 Saraswati lnformatics Practices (X!)

.,$k'g# Scxr--fr"€nt[fr*,;r:ljg> ::,,, "t; '. ':.. .'.. .,. ,.;, it.
SQL> SEI-ECT CCNOAT(TRIi((TNAI.II).TROD8ESS) FEOI,I

e0Ncft r { TEI N(THnHt },TnDDRESS}

fr rkesh Sharmaz4s-bialviga Hagar


JilgaI tiittdl?4, Pamesh Naqar
SharmiLa xaurD-31, nshok lrihar
SandeRp ltaushiktlc-32, Shalimar Bagh
Sangeata UatsG 35, Naluig3 itagar
llaaesh ltumafBc-42, Sh.dlinar Eagh
Sh!ifll EroraSt!, SiIB FLAIS, llohini
John Ray8-q4, Kirti Hag*
Uiuek EauatE-3$/z7, Sec-1, Bonini
Rajesh OtrrnaD-11.r130, Se8-5, Di{arika
Ash0k SinghalF-J165, East Patel" tlgr
Chetan Stlukla0-1u5, 10th C{,oss
,Reena l4ehta120, DD* Colonq
ftpptt-,
Ehi4alre LanbaE-140, Sr,rastik DLF
Jagjit Singhfi-2rrD, Printers Rpptt-
Dinesh Gao1l21-Triupni Apptt.
Lokesh RathoreC-11, l4IG Flat
f,kash Eathin-52, Sansad narg
Siflran Cha)rl.V-1/128, Sec-5" Rohini
'19 ro$s selected-
SQL> I

Fig. 26.6 TriminE leading spaces usinE THIM function.


INSTR
The syntax is as :

INSTR(string, set [, start [, occurrence]l)


Purpose. Returns the numeric position of a named character. The INSTR function allows for simple or
sophisticated searching through a string for a set of characters, not unlike LTRIM and RTRIM, except that
INSTR does not clip anything off. It simply telis you where in the string it fourid what you are searching for.
This is similar to the LIKE logical operator of SEI-ECT statement, except that LIKE can only be used in a WHERE
or HAVING cihuse and INSTR can be used anyrvhere except in the FROM clause.
INSTR searches in the string for a certain sel of' characters. It has two options, one within the other. The
first option is the difault; it will look for the set starting at position l. If you specify the location to start, itwlll
skip over all the characters up to that point and begin its search there. The second option o<:currence found
number of limes the search string occurs.
For ex4mple, consider Fig. 26. I , which contains all the narnes of teacher. Now find the tirst occurrence of
letter 'a' in the Fig. 26.1, INSTR is used without its options and with .rel as 'a' (note the single quotation marks,
since this is a literal) as shorl n inFig.26.7 . So, to find the position, write the command

SELECT TNAME, INSTRGNAME, 'a') FROM TEACHER;

whieh will trnd the position as shown inFig.26.7 .


The above example will find firstposition of 'a'. If you want to find the second occunence of the letter 'a',
then the ccmmand will be,
,a,,
SELECT TNAME, INSTR(TNAME, 1, 2) FROM TEACFIER;
Here, INSTR found the second 'a' in Rakesh Sharma's name, at position 10 and in Jugal Mittal's name at
position 12. John Ray has oniy one 'a', so for him, Ashok Singhal, Jagjit Singh, Dinesh Goel, Lokesh Rathore
the result is zero, meaning no success - no second 'a' was found.
S(LFtrrctions 585

lSqL) SILEDI T!ffiilE, lllSTf{THftr4E,

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

'19 rous selected -


J

isor->
I
|

Fi1.26.7 Finding character position using INSTR function.

26.2.1.1SELECT Clauses with String Functions

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

;T-tB RFena F,lehta


.?86 Bemesh Kuilar
ir61 nakesh sharma
,r18 Rljesh uerna
rsQL> I

Fig. 26"8 Using SELECT clauses with string function.


586 Saraswati lnformatics Practices (Xl)
26.2.2 Number Functions
Cracle functions deal with three classes of numbers: single values, groups of vlaues. and lists of values. As
with string firnctions, sotne of these functions changes the values they are applied to, while other mer.eiy reporl
information about the values. The classes are distinguished in this way :
tr A literal number, such as 564.7682
tr AvariableinSQLPI-USoTPLiSQL
tr One number form one coluntn and one row ofthe database
Oracle single-value functions usually change these values through a calculation.
A group of values is all the numbers in one column from a series of rows such as the monthly total salary
of all teachers of all rows. Oracle group-value functions telIyou something about the whole group, such as
average salary, but not the individual teachers of the group.
A list of values is a series of numbers that includes :
tr Literal numbers, such as l, 7, I3, 45
tr Variables in SQL PLUS or PLiSQL
tr Columns, such as SALARY AnnualSalary
This group of functions is used to return various mathematical calculations. They acceptnumeric input
and returns the numeric values. 'fhe listing 26.2 lists SeL numeric functions.

Listing 26.2 Numeric functions.


Function Purpose
valuel + value2 Addition
valuel - value2 Subtraction
valuel * value2 Multiplication
valuel / value2 Division
ABS(value) Absolute value
CEIL(value) The smallest integer larger than or equal to value
EXP(value) e raised to value EXPonent
FLOOR(value) Largest integer smal!er than or equal to value
LN(value) Natural logarithm of value
LOC(value) Base l0 losarithm oFvalue
MOD(value, divisor) Modulus or remainder of a value
POW ER(value, exponent) Value raised to an exponent power
ROUND(value, prec ision) Rounding of value to precision
SQRT(value) Square root ofvalue
'l'RUNC(value, precesion) Value truncated to precision.

Addition, Subtraction, Multiplication and Division (*,-, * and /)

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

i,ntq....q*. ,$eircfi '!6rb,nr


sqt>
[a[ . .:-
sELEtr sfiLf,ttv, setAEY {, i sffLAR? - .1
OO" S6LfiRY seLnRv l $& F*or{ ri*cHrn;
SCLffR? SALTfiY+160 SoLfl*Y-180 SgLnRY+1 2 snLn&v./3 0

58 SO 5? BB 5760 69680 183-33333


2SE 00 2030& 20190 242480 673-33333
15208 193 00 15108 -1821100 S06,66667
91 06 92 0B 9osg 109200 363-33333
1420$ 14306 1419[ 170r186473.33333
12208 12300 1214A 146400 l+06,66667
1a285 1s308 -13180 158408 {40
1 B20S 1 030s 10100 122\Bs 3E6
s8 60 SCBn 5ZE0 696110 193"33333
7706 18 00 7658 92rrBB 256,66667
a6 00 3700 3580 43280 128
5t0g 98 60 5668 68400 19A
47 0E q8 00 {600 56&69 1s6-66667
6700 d806 6600 B8400 22A.33333

57SB 58 00 5600 68{08 190


47 00 4800 q6s0 56400 156.66667
19 rotrs selpcter.
SqL>

Fig. 26"9 Arithmetic calculations.


ABS
The syntax is as :

. ABS(value)
Purpose. Absolute value is the measure of the magnitude of something. This function always returls a positrve
integer.

Example SELECT ABS(1i!4), ABS(+56). ABS(345.678) FROM DUAL;


Here, the DUAL table is owned by the user SYS and can be accessed b1, aIJ the users. It conatins one
column, DLIMMY, and orre row with the value X. The DUAL table is useful when you want to return a value
once only. When you execute the above SELECT statement. the following output will be displayed.

485(164) IJBS(-456) ,\BS(3.+s.678)

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.

E x amp I e SELECT CEIL( 1 64), CEIL(-45 6), CEIL(345.678) FROM DUAL;

When vou execute the above SELECT statement, the following output will be displayed.
588 Saraswati lnformatics Practices (Xl)

cErr_(164) CErr.(-4s6) CErr_(345.678)

tg 456 345

EXP, LN and LOG


The syntax is as :

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).

Exampte SELECTExP(3), EXP(5), LN(3), LN(21.085553), LOG.G)G(l),3), LOG(10, 100)FROMDUAL;


FLOOR
The syntax is as :

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.

FLOOR(I64) FLOOR(+56) FLOOR(345.678)

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.

Example SELECTMOD(I00, I0), MOD(-I00, I0), MOD(I M.100.I2)FROM DUAL;


When you execute the above SELECT statement, the following output will be displayed.

MOD(100,10) MoD( 100,10) MoD(144.100,12)

-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

Example SELECT POWER(10" 2), POWER(5,4), POWER(64,,5) FROM DUAL;


When you execute the above SELECT statement, the following output will be displayed.

POWER(10,2) POWEK5,4) POWER(64,.5)

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.

Example SELECTROUND(67689.655,1),ROUND(-3456.65,r),ROt rD(8976.56,0)FROMDUAL;

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)

67689.1 -3s00 8977

SQRT
The syntax is as :

SQRT(value)

Purpose. This function is the reverse of POWER function, i. e., POWER(value, .5).

Example SELECT SQRT(100), SQRT(144). SQRT(256) FROM DUAL;


When you execute the above SELECT statement, the following output will be displayed.

sQRr(100) sQRr(144) sQRr(2s6)

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

Example SELECTTRUNC(4560.S9),TRUNC(4560.89, 1),TRUNC(-4560.89, 1)FROMDUAL;


When you execute the above SELECT statement, the following output wil! be displayed.

TRLINC(4560.89) TRUN-C(4560.89, 1) TRLINC(-4560.89, 1)

4560 4560 8 -4560.8

26.2.3Working with Dates


Oracle stores dates in numeric format, representing the century year, month, day, hours, minutes, and seconds.
The default date in Oracle is DD-MON-YY. For example, l2-Aug-99. The SYSDAII'E is a function which return
590 Saraswati lnformatics practices (Xl)
the current date and time. You can use the SYSDAIE just as you would use any other column name.
Examp le SELECT SYSDAIE FROM DUAL;
Where DUAL is the dummy table and the output wili be displayed as :

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

MONTHS_BETWEEN(daIc l,date2) Number of months between two dates


ADD_MONTHS(daIe, n) Add calendar months to iate
NEXT_DAY(date,'char') Next day of the date specified
I-AST_DAY(date) Last day of the month
ROLh{D(date[,'fmt']) Last day of the rnonth
TRUNC(date[,'fmt']) Truncate date
MONTHS BETWEEN
The svntax is as :

MONTHS BETWEEN(da tet, date2)


Purpose. Returns the number of months between datel and date2. The result can be positive or negative, If
datel is later than date2 the result is positive otherwise the result is negative.
Example If the svstem date is 07-JUN-2003, then the months between the joining date of all teachers and the
system date can be calculated wiih the following query ls as :
" SELECTTNAME,,DOJ,SYSDATE,
ROLIND(MONTHS BETWEEN(SYSDATE, DOJ),0) AS,'No ofMonrhs"
FROM TEACHER;

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

2. E0UND ( l,l0NIHS 8T T IIEEN( SVSDN TE , 00J),0) AS "Ho of Hant


FBOt,t TESTHEB;

;ty5___ DoJ SYSDATE tlo of t4onths


_,_
,Rakesh Sharrri& 1 2- DEC- 81 87-JUN- O?
,IB
Jug€l llittat 03-JUL:S9 67-Jflt- 63 47
jSharsrila l{.uur 06-J UH- 06 s7-JUH- 03 ,&
-SafideFp ltaushik
08-fluG- 01 07-JUN- 03
Sang€eta Lrats 2 0-FE8- ts 0 B7 -JU}T_ B3 Ir0
Iianesh l{umar 63-Jtll-97 67-JUH- 03 71
.'hgam Ar6ra 1 5-R UG- 98 B7-JUN_ 63 5S
;-lohn Rag 22-SEP- 51 67-JUN- 03 Z1
Uiusk flar,!Bt 1 2-0CT- 01 B7-JtiN- C3 2g
Bajesh uFfna B7"i{0u- BB 87 -JUlt- 03 31
.Rshok Singhil 1 1 -RUG-99 B7-JIJH- Og 46
lchetan Sh&k1t -t
3-JUil- 01 B7 -JUtt- 03 24
Beena Uehta 1 8-JUL- 06 07-JUH-$f, 35
.Shtrdna Lamba 16-JUL-01 07-JUH* 03
,Jaqjit singh 11-JUL-S8 B7_JUN_ 83 5S
Dinesn coel 12-0CT-80 B7-J UN_ 63 32
:Lokesh RJthore 17-JUL-99 07-J UN- Or 47
nkash Rathi 1 8-JUL- 00 97-JUN- 03 35
Sinran Char,rla .I6-JUL_ 07-JUH-03
B1 2g

:19 rorrs select"d-


,sQl>
I

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 :

SELECT'TNAME, DOJ, ADD_MONTHS(DOJ, 6) AS "New Date"


FROMTEAC}IER;

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 :

SELECT DOJ, NEXT_DAYDOJ,'MONDAY') AS "First Monday"


FROMTEACT{ER;

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
.

sqL> SELECT DoJ" ilEXT $flV(rroJ, fis "First TEFIHER; ,4

D6J First l,lon

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

ROUND and TRUNC


The ROUND and TRUNC functions can be used for number and date values. When used with dates these
functions round or truncare to the specified format model. Therefclre, you can round dates to the nearest year
or month.
The syntax for ROUND is as :

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 '

sql> sELsGr iNo, 00.r,


2 RoUllB(00J,'ttoNTH'), ISUt{C(DBJ'

E0ti$!S{t}0J TSUNC(D8J

;T0? 15-AUG-98 01-f;-'JG-g8 61-*UG-98


,ftS f-t-JUL-g8 Bt-JU[-98 01-JUt-98
;seL> I

Fig. 26.13 Finding the last date of ioining date month'


26.2.4 Conversion Functions
of variatrle to another'
This group of functions allows you to convefi memory variables or data from one type
conversion or Explicit datatype conversion'
The Jatatype conversion can be Implicit datatype

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 :

TO_CHAR(n um ber/ d ate[fmt l)

number or date value to a VARCHAR2 character string


with iously,
es were displayed in the DD_lr,ION_yy fornrat The TO
C
this defauri forrnat to one specified by you. rrre
rmat :
rorroriin; il:i"::
A The format model must be enciosed in single quotation
marks and is case sensitive.
tr The format tlrodel can include an1'valid date format
elen-rent. Be sure to separate the date value from
the format model by a comma.
SQL Functions 595
-
tr The names of days and months in the output are automat.ically paddetl with blanks.
tr To remove padded blanks or to supress leading zeros, use the filI mode fm elernent.
tl You can resize the display width of the resulting character field with the SQL *PLUS COLUMN
conrmand.
tr The resultant column width is 80 characters by default.

Example To display the joining date of


all teacher in the format 'l\4Mru-Y', tho €iie, Ee
query willbe: rHO, TB _cn0B(00J,
TEECXER;
SELECT TNO, TO_CHAR(DOJ.
TNO }lftNTil
'MI\.4/YY') lvlonth- -Joiued
FROMTEACFIER ,T81 12181
.T02 67199
When the above query will be ,TS3 06/ 00
I 84 8s161
executed, the following screen will be ,T 65 BZI SS
displayed as shown in Fig. 26.1.i. T5d Atl97
T07 08/98
T08 B9l81
T09 1Bl01
T'r6 11/08
tr'll 88,/99
;T1z s6l 51
T-t3 07/00
'T14 S7lS1
T15 07/98
.T't6 10/BB
r'17 87 /99
'T't I 07.r00
'J1q 07161
i'lg .orn selerted-
sql> |

Fig. 26.14 Joning date in MMIYY format.


The following listing 26.5 shows valid date, time and other formats.

Listlng 26.5 Valid date, time and otherformats.


DateFormats
Element Description
SCCoTCC Century; S prefixes BC date with -
YYYY
Years in dates or SYYYY Year; S prefixes BC date with -
YYYoTYYoTY Last three, two or one digits of year
YYYY Year with comma in rhis position
IrYY,r\TryI Four, three, two or one digit year based on the ISO staLndard
SIEARoTYEAR Year spelied out; S orefixes BC date with -
BCoTAD BC/AD indicator
B.C"orA.D. BC/AD indicator with periods
a Quarter of year
MM Month, two-digit value
MONTH Name of month padded with blanks to lenght of nine characters
MON Name of month, three-letter abbreviation
596 Saraswati informatics Practices (X!)
RM Roman numeral month
WWorW Week of year or month
DDDoTDDoTD Day of yeaq month or week
DAY Name of day padded with blanks to lenght of 9 characters
LY Name of day; tfuee-letter abbreviation
J Julian day; the number of days since 3 I December 47 1 3 BC
TimeFormats
Elernent Description
AM or PM Meridian indicator
A.M" or P.Iv{. Meridian indicator with periods
IIH orlIHl2 orIil124 Hour of day or hcur (l - 1 2) or hour (0-23)
MI Minute (0-59)
SS Second (0-59)
SSSSS Seconds past midnight (0-86399)
OtherFormats
Element Description
Punctuation is reproduced in the result
"of the" Quoteri string is reproduced in the result
TT{ Original number (for example, DDTH for 4TH)
SP Speiled-out nurnber (for example, DDSP for FOLrR)
SPTH or T'I{SP Speiled-out ordinal numbers (tbr example, DDSPTH f'or FOURII{)

TO_CHAR with Dates


gd.i6rt
Let us see the example given below :
SELECI I}MHE,
T0_CHe8(00J, 'f'.rD Honth VYYY') "Date or Join"
SELECTTNAME, FROft TEECHEB;
T0_C[LAR(DOJ,'frnDD Month YYyt)
"Date of Join"
Date of Join
FROMTEACHER: :Rakesn Sharna 12 December 2001
iJugal tlittal $ Ju19 lCsg
iSharnila l(aur 6 June 2o0g
When the above query will be executed, Sandeep [aushik 8 August 2081
Sangeeta Uats 20 FeDruarg 2080
the following screen will be displayed as shcwn ,Bamesh l(unar 3 Jul.U 1997
jshyair
in Fig. 26.15. Rrora 15 *ugust 1098
i;onn nay 22 Septembcr 2861
tuiuek Raudt '12 EctoEer 2901
fiajosh Uerna I Houeftber 290&
nshok Sir$haI -t1 Bugust -t?99
,Dietan Shu!.la -13 June 20[1
.RPena lleilta
-Bhuana 18 Ju}! 20t!0
Lanba 16 JuIg 2001
iJagjit singh 11 JuIy 1998
'Dinesh Goel 12 october 2000
Lokesh Rathore 17 Ju19 1999
,okasft Rathi 18 Jullti 28t,0
,Simran Chaula 16 JuLg 20Sr
,19 roi{s selecte(-
sqr-> |

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

Twelfth of December 2001 12:00::00 AM. The query willbe :

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;

TNA14E Date of Join


tRakesh Sharma Tuetfth of DecerltDPr 20St 12:04::90 fim
,Jugal t{ittaI Ihird of July 1999 '12:90::08 n1,|
:Share:ila l(iur Sixth of June 2008 12:00::00 At'l
lsandeep Naushik Elqhth of nrgust 2901 12:80::00 AN
jsarge*ta Uats Ir,rentietn of Februar! 2090 '!2:80::00 RN
,Blmesh Kumaf Ihird of Julg 1997 12:09::00 fitl
Shyam Rrora Fifteenth of Rugust 1998 12:00::00 At4
John Bay Tuenty-secood of SeptembPr 2061 12:08::00 fill
jUiuek Earoat Truelfth of 0ctober 2091 12:00::00 FN
,fiajesh Uerna Seuenth 0f Nouerher 2008 12:08::00 RH
iAshok Singhal E).eupnth oF Cugust 1999 12:90::08 Al'l
jchet.n Slrukla Tnirteentn of June 2001 12:90;:80 gtl
rFeena Hehta Eiqhteeath of Ju19 2006 12:90::S0 Al',l
iBh*oana Lamba siltEentn of July ?gE1 12:69::09 RN
Jsgjit singt Eleuenth of Julg 1998 12:08::06 fi14
;Dinesh GoeI TulrlFth of gctober 2086 12:80::90 AN
:Lokesh tratnorP Seuenteenth of JdlJt '1999 12i00::00 Rll
.fikash Bathi Eiqhteenth oF JuLq 2{tB8'12:00::o0 An
lsimran Chalrla siiteenth sf Ju19 2081 12:98::00 fifl
:19 rotrs selected"
SQL>

' 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.

TO CHAR with Dates


those numbers to the
Wheii rvorking with number values such as character strings, you should convert
vlaue of NUMBER datatype to V'{RCI IAR2
character datatype using the TO-CHAR function, which translates a

datatype. This technique is especially usefui with concatenation'


-Iiyou converts a number to character
convening a number to character datatype, the ibllowing listing 26'6
datatype.

Listing 26.6 Number format elements.


Element DescriPtion Examph Result
9 Numeric position (number of 9s determine 9wry9 12:4
4isplaY width)
0 DisPlaY leading zeros w99g $1234
$ Floating dollar sign $ww st234
L Floating location culrency symbol L999999. FFlz3/.
Saraswati lnformatics practices
Decimai point in position specified
D34.n
Comma in position specified
1,234
MI Minus signs to right (negative values)
123+
PR Parenthesize negative numbeis
<1234>
Scientific notation (format rnust specify four Es)
1234E+O3
V Multiply by l0 n times (n = number of 9s after V;
IN4IN
B Display zero viaues as blank, not 0
1234.UJ
Foi'example, to display the annual salary for all teachers using
a number format, the query will be :

SELECT TNAME, TO_CIIAR.(S ALARyx I 2,,g9g,ggg'),,Annual


Salary,,
FROMTEACFIER;
When the above query will be executed, the following screen
will be rlisplar,ed as shown inFig.26.17.

-
'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

Fig. 26.17 Converting the number into character format.


TO_NUMBER and TO DATE
You may want to convert a character string to either
a number of a date. To accomplish this task, you use
TO-NUMBER or TO-DATE functions. the
hh" fo.-ut model you choose will be based on the previously
demonstrated format elements. For example, to display
the names an<I joining dates of all the teachers who
joinged onJuly 18, 2000. The query
will be :
SFT FCTTNAME,DOJ
FROMTEACFMR
WHERE DOJ = TO_DATE( July 18, 2000,. ,Monrh DD, yyyy,);

when the above query will be executed, the followrng screen


will be displayed as shown in Fig. 26. 1g.
SQ!- Functions 599

'!;rl 'r.."'. '::tr. ' ";


Uah
SQL> SELECI TNNHE, DOJ
2 FROH TETCIIER
llllEBE D0J = I0_08IE('JuIg 18. 2E0O' 'l,lo0th 00. tYYV' ) ;
IHAI4E DOJ

Re?na l,lehta 18-JUL-G0


,Akash Bathi 1S'JUL- &0

'sQr> I

ltrJ
Fig. 26.18 Gonverting a character string into date format.

26.2.5 DECODE Function and its Usuage


The DECODE function decodes an expression in a way similar to the IF-THEN-ELSE logic used in various
Ianguages. The syntax is as :

DECODE (coVexpression, searchl, resultl [, search2, result2, ....,] [, default])


The DECODE function decodes expression afier comparing it to each search value. If the expression is
the same as search. resttlt is retumed. lf the default value is omined. a null value is returned where a search
value does not match any of the result values.
For example, calculate the salary of all teachers whose departnrent number is 'D01' given an increment of
l0% other wise give 20Vo to other teachers. The query will be :
SFTFCTTNAME,
DEPT-NO,SALARX
sqL> SALNBV,
DECODE@EPT_NO, 2 SALABY*1.10, StLARV11.20) Beuised
'DOl', SALARY*1.10, 3

SALARY* 1.20) Revised THRI4E DEPT SELNBY REUISED


FROMTEAC}IER;
Bdkesh SharFi D05 5800 6968
When the above query Jugal ltittal Dliz
Sharnila Haur DB1 282fr5 242&0
will be executed. the follou ing Sandeep faushik D03 152.$g 18240
91 S0 't
screen will be displayed as Sange€ta Uats
Ramesh Nuner
DO5
DM 14206
092 0
170tt0
shown in Fig. 26. 19. ,Shyao nrora DO? 12200 14640
,Joho Rag D03 13269 15849
iUiuelr 8i$at 001 10296 12248
,R*jpsh Uerna 004 5880 6966
,65hok Singhal 002 77SB 9248
Chetan shukla D02 3608 4320
Beena l4ehta DD3 5708 6840
Bhrrana Lanba D0lr 4760 564S
Jagjit Singh ng[ 6706 804S
tlinesh Goel D04
LokPsh Hatlore D03
.ftkish Rathi DO3 5700 68411
,Sioran Charrla 004 lr7 0B 5 64&

'19 r'orrs selPctsd-

SQL>

JtJ ,.

Fig.26.19 Giving salary increment using DECODE function.


600 Saraswati Inforrnatics Practices (Xl)

26.3 Nestis'lg F!.!nctaons


Single-row functions can be nested to any depth. Nested functions are evaluated from the innermost level to
the outermost level" Some examples fcllow to show you the flexibility of these functions. Nested functions are
evaluated from deepest level to the least-deep level as shown in Fig.26.2A.

FUN3(FUN2(FUN1(col, argL), ar g2), arg3)


Step 1 1

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.

.d !aa,I: qjrtire Hdp


SQL) SELECT TNHI,,IE, TO CHAR(NEXT DNY(EOD NOHTHS
2 (DoJ,6),'!40r0RY'),
'f dag , honth ddth , YYYV' )
4 "Next 6 l,lonth Reuieu"
5 FRUI.I IERDIIEB
6 ORDIR BV }OJ;
TNft14E llaxt 6 lronth Eeqieur

flaoPsh iturnar llonda!!, J.nuarg 5th, '1998


Jagjit sinqh Honday, Januar! 18th, 1999
ShyaB erora Honday, Februarg 22nd, 1999
Jugal Flittal ilondag, Januarg 1oth, 2060
Lokesh Batiore Hondag, Januarg 24tn, 2000
r0shok Singnal Hunday, Februarg 14th, 2008
rsanqe€ta Uats I'londay, August 21st, 2806
,sharnila Kaur Hondau, DecsmbEr 11th,206[
,Rerna hlPlrta ilonday, January 22nd, 2081
'Akash fiathi Hondalt, .ranuar! 22[d, 2001
Din€sh GoPL |londag, Fprit 16th,2001
flajesh Uerma ilonday, ttalt 14th,2861
lchet.n ShuLla l,looday, DecemDer -17th, 2001
,Ehsrara Lamba hloodag, January 21st, 2gg2
,Siroran Charula Dlondag, Jdnuary 21st, 20gz
sand€ep Xaustrik l,londa!, fEbruar! 11th, 2002
'J6hn ReU Hondag, fiarDh 25th, 20G2
rUi{e,{ Rer.!at I'londag,Ap!"iI 15th, 2002
.f,akesh Shlrma ilonday, Juoe 17th. 2t162
19 rot(s sPlected,
,sQt->

Fig.26.21Nesting functions in a query.


.('

SQL Functions 601

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

: Q15. How will you count number of characters in a character expression ?

, 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

602 Saraswati lnformatics Practices (XI)


(i) Up to I decimal places (1il to a whole number.
Ans. (l) SELECT ROLTND(AMOUNT,1) FROMORDER;
(ir) SELECT ROUND(AMOLINT,0) FROM ORDER;
Q24. AnumericdatafieldCNTcontains356T5.ST65storedintableITEM.WriteacommandtoroundoffCNT
to (l) Whole number (ll) Upto 3 decimalplaces
Ans. SELECT ROUND(CN! 0) FROM ITEM;
SELECT ROUND(CNT.3) FROM rTEM;
Q25' Write a SQL function to remove leading and trailing spaces from a character expression p, where
P: "ANAY#JAIN##### " (where # denotes a blank space).
Ans. TRIM(P)
Q26. Ansrver the lollowing :

(a) What will be the output of


SELECT ROUND( 1 24.44)+MOD( 1200. 87,3) FROM DUAL;
(6) What will be the output of
SELECT MOD(30.500,5)+ROUND(l 00.50,1) FROM DUAL;
(c) Write the commands to display the name of passenger and address of all the passengers after
removing the leading and trailing blank from the table pASSMAST.
(@ Write the cornmand to conveft the message "ABC INTERNATIONAL PUBLIC SCHOOL,, into lower-
case letter.
(e) Find the output of the command given.below :
ISELECT NEXT DAY(,08_JLN_2003" iFRIDAY') FROM DUAL
f) Write a command display the systetn date.
Ans. (a) 12187
(b) t0t
(c) SELECT TRIM(NAME). TRIM(ADDRESS) FROM PASSMAST;
(d) SELECT LOWER(ABC INTERNATIONAL PUBLIC SCHOOL) FROM DUAI;
(e) 13-JUN-03
(, SELECT SYSDATEFROM DUAL;
Q25. Write SQL commands for (a) to (fl and writes the outputs for (g) on the basis of table HOSpITAL.

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,

Arprit SurqPry 300 360


Zarips ENT 250 300
l(areen firthopaedic 206 2q0
Rrun Surgerg 300 360
Zubin ENT 259 300
Ketaki ENT zsc 300
ankita cardiologg 80$ 960
Zareen GynaecologY 308 368
Kush Carrliologg 808 960
Shilp a l,le ctici ne 4 00 48 0

Review Questions

l. What do you understand by a function ?


2. Describe the tenr expression and function.
3. Write the function to display your system date.
4. What is the difference bw'teen CEL and FLOOR ??
5. WhatisthedifferenceTO CHARand fO NUMBER?
6. What is the difference between NEXT DAY and LAST DAY ?
604 Saraswati lnforrnatics Practices (Xl)
7. Which type of output does the following produce :

(, LENGTH0 (,, ro_DATE0


(i,,) To CHAR0 (tv) LPADQ
(v) TRIIvIQ (vt) ROUNDQ
(vii) CUBSTRQ (vill) INSTRQ
(rr) MONTHS BETWEEN
8. Write the resulting output of the following :
(a) SELECT ROUND(1023 .432,1) FROMDUAL;
(b) SELECT LENGTH(RAMESH SFIARMA') FROMDUAL;
(c) SELECT UPPER('master')FROIviDUAL;
@ sEr-ECT MOD(ROUND(120.60, 1), 5) FROMDUAL;
(e) SELECT POWER( 5.5) FRoI,{DUAL;
(fl SELECT CEIL(120.0)PROMDUAL;
G) SELECT CErL(-120.34) FROMDUAL;
(h) SELECT FLOOR(6s467.8890) FROMDUAL;
(i) SELECT FLOOR(-I2340.0) FROMDUAL;
(j) SELECT LOG(10,2),ABS(-3)FROMDUAL
(k) SELECTLOG(IoO,10) FROM DUAL
(D SELECT MOD(36,3) FROM DUAL;
(rr) SELECT IvIOD(14*9,90/9) FROMDUAL;
(n) SELECT ROUND(3244.1962,1) FROM DUAL;
(o) SELECT SQRT(144) FROMDUAL;
(p) SELECT SQRT(I5.6*24.3) FROMDUAL;
(q) SELECT 1000+SQRT(100) FROMDUAL;
(") SELECT SQRT(1,14)+ 1000+TO NUMBER(I2) FROMDUAL
G) SELECT FLOOR(144.34)+ 1000+ CE\L(32.23) FROMDUAL
(/) SELECT MOD(9*5,9)+CEIL(100.56) FROMDUAL
(w) SELECT SQRT(1s.6*24.3) + LOG(100, l0) FROM DUAL;
(u) SELECT SQRT(15) FROM DUAL;
(r) SELECT SQRT(345)+SQRT(Is) FROMDUAL;
(t') SEL.FCT SQt[(345)-SQRT(15) FROMDUAL;
(-r) SELECT FLOOR(100.3,1)- ABS( 100.22)+ABS(200.43)FROMDUAL;
(t, SELECT FLOOR(3456 98)+6p1a,rt16.89) FRON1 DUAL;
(J SELECT TRIM (' ABS Public School ') FROM DUAL
(aa) SELECT LENGTHCABS Public School') FROM DUAL
(ab) SELECT LOWER ('ABS Public School') FROM DUAL;
(ac) SELECT SUBSTR(TRIM('ABS Public School),1,3) FR.OMDUAL
(a@ SELECT UPPER('ABS PLrblic Schooi) FROM DUAL;
(ne) SELECT MONTHS BE'l-WEEN('12-OCT-01','25-JUN-02) FRCM DUAL
(c/) SELECT SUBSTR(TRIM(' INDIAISGREAT'),3,9) FROMDUAL

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

(a) Whoie nurn[-:er


(b) Upto 1 decimalplace.
SQL Functions 605
14. A numeric data field NUM contains 14s67 .62i 1. write a command to round off NUM to :
(i) Whole number (it) Upto 2 decimal places.
15. Write the SQL command to remove trailing spaces ftom the character expression p, where
P: "Deepali#Arora####" ("#" denotes a blank space).
16. A Character expression Name contains "hgfgggdddd". Write a command to pick the following set of
characters from it : (i) First 6 characters (ll) From 3 rd to 7th character.
11. Given the following EMPLOYEE relation. Write SQL cr:mmand for question (a) to (x) and the output for
o)
TABLE: EMFLOYEE
EMP_NOM{AME DESCINATION E4CR EIIREDATE SAI, COMM DEPT
7369 Sunita Sharma CLERK ],aW 17-DEC-80 2Bm n
7199 Ashok Singhal SALESMAN 7695 20-FEB-BI 3600 300 30
7521 Rohit Rana SALESMANI 1698 22-FEB-B] 5250 5m 30
7565 JyotiLamba MANTAGER 7839 02-ApR-81 4975 2C
1654 Martin S. SALESMAN 7698 28-SEp-81 6250 1400 3i)
7698 BinodGoel MANAGER 7839 01-MAy-81 5850 30
774 Chetan Gupta MANAGER 7839 09-J[IN-81 2450 10
7188 Sudhir Rawat ANALYST 75(6 19-ApR-87 5000 n
7839 Kavita Sharma pRESIDENT l7-NOV-gl 50m l0
lW TusharTiwari SALESMAN 1698 08-SEp-gt 4500 030
1876 Anand Rathi CLERK 77BB 23-MAy-87 6100 n
79ffi Jagdeep Rana CLERK 1,698 03-DEC-81 4g5O 30
7m2 Sumitvats ANALYST 756f 03_DEC_81 3500 3600 n
7%4 Manoj Kaushik CLERK i782 23-JAN-82 5300 t0
(a) To convert the designation into lou,er case.
(b) To list the name and emplovee number from by converting the name lnto uppercase.
(c) To list all names. hiredate and and confirmation date as the hiredate + 6 months.
(d) To display the employee name and the incremented value of SAL as SAL + 300 if the department is
l0 otherwise SAL + I 00.
(e) To list occurence of character 'a' in the name of the employees.
$ Display first three characters of the fleld designation.
(g) What will be the ourput of the following :
(, SELECT ENAME, HIREDAIE. SYSDATE.
ROUND(MONTHS_BETWEEN(SYSDArE, HIREDATE),0) AS "No ofMonths" FRoM EMpLoyEE;
(il) SELECT ENAME, INSTR(ENAME, 'a', l, 2) FROM EMPLOYEE;
(ili) SELECT SUBSTR(ENAME, l,s ) FROM EMpLOyEE;
(lv) SELECT CONCAT(ENAME, JOB) FROM EMPLOYEE
Chapter - 27

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.

27.3 Relating Multiple tables


Each table contains data that describes exactly one entity. For example, the TEACHER table contains information
about teachers, Categories ofdata are listed across the top ofeach table and individual cases are listed below.
Using a table fqrmat, )/ou can readily visualize, understand and use information.
Because data about different entities is stored in different tables, you may need to combine two or more
tables to answer a particular question. For example.
)'ou may want to know the name ofthe depaftment in which
a teacher works. In this scenario, you need information fiom the TEACHER table (which contains data about
teachers) and the DEPARTMENTtabIe (which contains information about departments). An RDBMS enables
you to relate the data in one table to the data in another by using the foreign keys (dept_no). A foreign key is
a column or a set ofcolurnns that refer to a primary key in the same table or another table. The following Fig.27 .l
shows a relation with TEACHER and DEPTM table.
TNO TNAME DEPT NO DEPT NO DEPTN,AME
T02 Jugal Mittal D0l Physics
T03 Sharmila Kaur
TM Sandeep Kaushik )7- N2
D03
Chemistry
Maths
T05 Sangeeta Vats D04 Computer
T06 Ranresh Kumar D05 Biology
Primary ke gn Key
k rykey
Fig. 27.'l Primary amd Foreign keys in a relation table.
Multiple Tables and Sub-Queries 607

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 :

SELECT tablel.column, table2.column


FROIVI tablel, table2
WHERE table I .column : table2.columnl
So, it is ciear from the above s),ntax that the column name should have a table name as a Prefix, when the
same column name appears in more than one tabie. To join n tables together, you need a minimum of (n- I )
join
conditions. Therefore, to join five tables, a mittitnum ofthree joins are required.

27.5 Carlesian Product


The Cartesian product of two relations is the concatenation of tuples belonging to the two relations. The
Cartesian product is a binary operation and is denoted by (x). The degree of new relation is the surn of the
degrees of two relations on which Carlesian product is operated. The number of tuples of the neu'relation is
equal to the product of the number of tuples of the tr,vo relations on which Caftesian product is performed
Consider the two relations given below :

TEACHER DEPARTMENT

TNO TNAME DEPT NO


m2 Jugal Mittal n2
T03 Sharmila Kaur D0l
TM Sandeep Kaushik D03
m5 Sangeeta Vats D05
T06 RarneshKumar D03

Fig.27 "2 Two tables for cartesian operation.


To find the cartesian product of the above two tables, the query will be :
SELECT TNAME, DEPTNT\ME
FROM TEACHER. DEPARTM ENT;
From the above query, the cartesian product will display the following result :

TNAME DEPARTMENT

Jugal Nlittal Physics


SharmilaKaur Physics
Sandeep Kaushik Physics
Sangeeta Vats Physics
Ramesh Kumar Physics
Jugal Mittal Chemistry
Sharmila Kaur Chemistry

JugalMittal Maths
SharmilaKaur Maths

Jugal Mirtal Computer


SharmilaKaur Compnter

Jugal Mitral Biology


SharmilaKaur Biology

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:

lsQL> SELECT * FBotl


i:

;rxo TNAI'lE IA[ofiESS SfiLRfiY DEPT DOJ

;I0'l Rakesh sharfia 245-l,la1ui!ra ltagar 9806 005 1 2-DEC- 81


iT02 Jugal Hittat 34, Bamesh Nagar DS2 &3-JUL*99
T03 Sharnila Naur D-31, flshok tlihar 20280 00'l 06-JUll- 00
,T0[ Sandeep t(aushik 14G-SZ, Shalimar Sagi 15298 Doit 6B-RUG-{'1
.T05 Sangeeta Uats G-Ss, flaluiya Nagar 9108 D&9 28-Ff8-8&
iI06 Ramesh Huhar BG-q2t Shalinar Sagh tq200 003 03-JUL-97
,T07 Sh!,an Arora 50, lllG Fl_RTS, Bohini 12280 002 1s-RUG-90
iIOS John Ray 8-4Ir, l(irti Nigar ,I32BB D83
22-SEP-O1
:T69 Uiuek Rauat E-sil27, sec-1, Folrini lE2B0 001 12-0CT- 0''
.TJ g Ba jesh Uerna D-11./130, Sec-s, Duar.ka 58BB DO4 o7-N0u-o0
T11 Rsholr Singhal F-'1165, €ast PatEt Ngr 7ZB0 002 1 1 -RUG-99
I12 chetan ShukL. C-165, 1oth Crosg 3660 DB2 1 s-JUN-01
T13 neena itehta 120, DDA Colong 5700 003 18-JUL-OB
T'14 th$rana Lamta E-140, Slr-stilr Apptt", SLF 4780 06il 16-JltL-81
T15 Jagjit Singh R-240, Printers Apptt. 6780 0BIr 1 1-JUL-98
T16 Dinesh Goet e21-Triueni npptt. 0lr
D 1 2-08T- B0
T17 Lokesh Bathore C-1'l , l4lc FIat Ds3 1 7-JUL-?9
T18 Akash Bathl 6-52, Sansad l4arg 5780 D63 18-JUL- 0&
T19 Simran Cha{rla O-1/129, Sec-S, Rohini 4706 ES4 16-JIL- 01
Multiple Tables and Sub-Queries UU,

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

Fig. 27.3 TEACHER and DEPARTMENT table.


If we want to know the narne of ihe department for every teacher then we have to apply the equi--join on
the above two tables based on the common key which is DEPT_NO. So, we have to compare the vaiue of
DEPT_-NO column in the teacher table with the DEPT_NO values in the DtrPARIMENT tab1e. The relationsirip
between the TEACHER table and Lhe DEPARTMENT table according to the DEPT_NO is called the eqr:i-j6i6.
E,ieapl,e SELtrCT lEAClER.Tl{}},{8, DEPAPJMENT.DEPilNAh{E
FI\.ON{ TE,A.Cifi R, DEPA"qT},,G}1'I
.y\TtrP.E r'
TEACI-i3i'].. i-r P i' NC = DEiiiUl, E'li i-. DFP I .-'rO :

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.

i \,-' :t" /r'*i


lt ' -/- rr ' ^ '
>-r'SEtEgT
"-Y
IERCHEB"IHANE, OEPRRTiIEiIT.D'iTHATIE
rSOH TERC1IER, DEPRflTI(EHI
I4HESE TIRCHER.DEPT HO = DEPARTflTNT.DEPT

THRI.IE DEfTNRHE

;Raktstt SharmJ BioIog!


,Jqgal ilittal ch*mistrU
'SharFlila ita$r Physics
Ssnd?ep l{ausilik tleths
,SangePta Uats Sioiogg
:HanPslx $unar t'lathg
Shyam Arora ChEoi5trg
John 8a9 Haths
Uiuek Raroat Physics
Rajesh Uerna ComputEr
tAshsk Sinqhal Chemistry
Chetan Shukle Ihelnistrg
:Reena I{ehta flaths
Bhlrani l-amba coBputer
Jagjit sinqh Conputer
DinBsh GoPl Conputer
Lokesh Rathore l,laths
Rkash Bathi llaths
Simran i:haurla Conputer

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)

27.6.1.1Additional Search Conditions Using the AND Operator


As we had discussed above,that we can use a relational operator in the join. In addition to that you can specify
the criteria fbr WHERE clause. For example, if you want to dispiay the department namg of a particular teacher
then your query must be like this :
ExawpleSELLCTTEACI{IIR.TI\-AME,DEPARIMENT.DEP| NAME
FROIV{ TEACMR. DEPARTI'IENT
WHERE TEACHER,DEPT NO = DEPARTMENT.DEPI-NO
AND TNA"ME ='Sangeeta Vats';
The above querl will produce the result as shown in F-ig. 27.5.

Stai' ,fuq1,C:ilH ; .i'ff i:2.1.,i.,.l,'' ;.,.'.'rl .:'i..:,, . ,;t


.Ei*;.6tIt
SQL> SELEEI TERSHER,THf,hIE, DTPflRTI,IEHT,DEPTNRt4E
2 FRoil TEACT{EF, BEFf,RTtiEttr
3 l,HEnE TERCHER-DEPT H0 = DEPnRTflEHT-DIPT Nll
q 6H0 TNRflE = 'sangPeta Uats';
DEPTNAl4E

Fig.27.5 Conditional query in equi-join.


27.6.1.2 Using Table Aliases
A11 the time writing the name of the table Iie
with the column name is very time S QL> T . TNNHE , D.DEPINAHE
2 TEACHER T, ., rfiRrnEilT D
consuming if the table is lengthy. SO, you I . OEPT H0 = O-DEPT N0;
can use the table aliases instead of table
INA1IE DEPI}IAHE
name as we have done in the column name
aliases. Like the column alias give another .fiakesh Sharna Biologg
Jugal Hittal ChPnistrg
name to colurnn. Similarly, table aliases give sharnila Raur Physics
Saodeep (aushik hethE
another name to the table. The table aliases Sanqeeta Uats Eiorogg
can upto 30 characters in length and rhe Ramesh Kuaar ttaths
Shya6 f,rora Ch emistrlt
table aiias is valid only for the current John Rag 14athE
SELECT statement. Itiuek Ral,,at PhysicE
SajEsh Uerna Computef
Example ffshoN{ singhal ehenistry
ghetaa Shukla Dh etlls Er]l
nEerla llEhta l'li ths
Bhsrana LaBba Conpqter
SELECT T.TNAME, D.DEPINAME Jaqjit Singh Coftputer
FROM TEACHER T,DEPARTMENT D Dinegn GqeI conputer
Lokeih Sathore Hlths
WHERE T.DEPT-NO = D.DEPT-NO; nkash &athi 14aths
Sinran Char,rla conpster
The above query will produce the
l9 rou5 selectgd.
result as shown in Fig.27 .6.
sQr>

Fig.27.6 Query using table alias in equi-ioin.


Note. If a table alias is used for a particular table name in the FROM clause, then the table alias must be
substituted for the table name throughout the SELECT statement.
Multiple Tables and Sub-Queries 611

27.6.1.3 Joining More than TwoThbles


In SQL, it is possible tll cors[ruct queries joining more than two tables. Consider ihe tlree table given below :

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 :

CREATE TABLE SlUDEiir (SNO CHAR T4) FRMARY KEYNOT I{ULL,


SNAMEV-ARCLLAR(20),
S.ADDRES S VARCHAR.2,(25 ),
FEESNLMBEIi.(8,2),
GRADECHAR(1)):
STUDENT data:
s01 Rormy Duggal A-12, Sakti Nagar 1200.m A
S(2 VivekKhanna C-12,120,AshokVihar 115iJ.00 A
S03 Sudhakar Rana D-2ll11,Vikash Pur 2m0.00 B

S04 PuneetGoel 45-8. Ty- Il, Pushpa-v'ihar 21m.00 C

S05 KuniarDirvakar B-5. DSIDC Colony 1300.00 A


506 Pankaj Gupta Il-31220,MandirMarg 12C0.m C

S07 Bipul Kaushik 7A..45. SainikVir\ar 1150,00 D

S08 M. Mathew PU-30, PitarnPura 12m.m A


SiB Raina Vats SLi-12Q, PitamPura 1300.c0 B

s10 Pyush Chand lC0, Indian Exp. Building i2m"00 A


Appty the INSERT command to insen the above records into STUDENT table. For exarnple,
INSERTINTOSTI.]DENT
VALUES(SO 1','Ronny Duggal','A- 1 2, Sakti Nagar', i 200.00' A') ;

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;

SHO SNf,IIE SSDDBESS FEES 8

s81 fonnu Duggal A*12, Sskti Nagar 1290 R

s02 Ui.uek l{han,id t-12, 728, fishs* Uihar 150


^! A

s03 sudhakar Rana D-21111, Ui*ash Pur 2004 B

sB4 Puneet GoPI 4g-8, rp-II, Poshpa uihir 21 G0 I


sB9 Itunar Di!r'l,(ar B-5, DSIDG Colooy 13 t!8 R

s06 Paakaj Gupt.a H-x1228, tlaEllir l'larg J208 C

s67 EipuI ltaurhik 7n, q5, sainik uihar '!15 B D

SBf, t{ - HathB(o Plt-38, Pitam Pura 12 6[ A


s09 Raina Uats sU-120, Pitam Pura 1S OB B
S,t8 Puuslr chend 108, !ndian Exp. Building 12 00 A

16 raus selected,
saL> I

FiE.27.7 STUDENT data ln SELECT query command.


612

Create another table TEACHES rvith the following data types and enter the following records :

CRE"\TE TABLE TEACmSGNO CHAR(4),


SNoCHAR(4));
TEACHES data:

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.

.r:jffi ) rw/4s.?i1;.1i* \\ns


sIlL> SELEIT x Fm0N TEnCHES;

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
!

Fig.27.8 TEACHES data in SELECT query command.


Now, if you want to know which teacher is teaching which student along with the teacher name and the
student name, then you have to join the above three tables. The query will be :
SELECT T.TNAME, TE.TNO, S.SNO, S.SNAME
FROM TEACHER T,TEACHES TE,STUDENT S
WHERET.TNO=TE.TNO
AND TE.SNO=S.SNO;
The above query will produce the result as shown inFig.27.9

Sle * .:,,,, :rll:::,:1j, ill;.'l_,, r+l r,;;;";


s{L> SfLECT T.INAHE, TE.TNO, S,SIID, S.SNNI{E
2 FROT4 TE6CIIEB T, IEACI|ES IE, STUDEHI S
s tllERE I-TH0 = TE,TH0
11 Ot{D TE-SN0 = S.Sl{0;
TilO sHo sHftffE

'na*esh Silarna T01 sBl Ro*ng Duggal


Jugal i'littal T82 s03 Sudhakar Bana
Sharilila Kaur T83 s02 UiueL l{hanoa
Jugal Hittal IB2 s04 Puneet GoBI
'Jugel ilittEl T62 sg5 Hunar Diural{er
Sanr8ep faushik T Sl+ s01 Ronng Suggal
Sangeeta Uats T&5 s06 Pankaj Gupta
,Jugal Hittal '102 sa4 PtlnPet Gosl
rsharnila t(aur T03 s83 Sudhakar Sana
Bat(esh Shirma T$1 s07 Bipul l{aushik
'18 ror'rs selected.
SQL>

Fig. 27.9 Joining more than two tables in equi-join.


27.6.2 Non-equi-join
When there is no common column in two tables and then we perfonn a join. This type ofjoin is called non-equi-
join. Noq consider the two table given below :

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 :

CREAIE TABLE GRADE (GRADE CHAR( I ),


MTNSALNUMBER(8,2),
MAXSALNUMBER(8.2))
GRADEdata:
A 15m0.00 21000.m
B 10000.m 14999.ffi
c 6000.00 9999.m
D 20C[.m 5999.00

Apply the INSERT command to inserl the above records into .XsF',tt
GRADE table. For example, sql> SEt-tDT * F*tlM ER4DE;

INSERTINTOGRADE G llIl{SAL tlRXsAt


VALUES(A', 1 5000.00, 2l ffi0.00); R 1500& 21098
Similarly, insert all the records into GRADE table. After B 1 8BSB 14999
c 6B0B q9c9
inserting. when you will apply the command, D 2600 5999
SELECTXFROMGRADE: sqr) |
the following output screen will appear as shown in Fig, 27. 10.

Fig.27.10 GRADE data in SELECT query command.


e14 Saraswati informiat!cs Practices (Xl)

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

sharmila l(iur 20200 R


Sandeep flaushik 15200 A
Ramesh l(ilrnar 1t208 B
,Shgam Arora 12200 S
'Johr Ray 1320S B
iuiuek Rasrat 10208 S
is;ngeeta Uats 91U8 e
ifishok Singhal 7706 B
iJagjit Singn 6700 G
Ra*esh ShdrrDi 5800 D
Rajesh Uerna 58 B0 it
Ch€tan Shukla 3600 D
Resna l'lehta 5768 D
Bhsraaa Lailb. 47BO D
Hkash Rathi 97OG D
iSinran Char'rle STOB D

16 robrs s?lected-
SQL> I
{

Fig. 27.11 Query using non-equi-ioin.


Note. All teachers appear exactly'once in the quer.r. None of the rows in the CRADE table contain grades that
overlap. All the teachers salaries lie within the Iimits provided by the CRADE table. T'hat is, teacher earns less
than the lowest value contained in the MINSAL column or more than the highest value contained in the
M-AXSAL column.

27.G.3 Outer join


When any row does not satisfy the join condition, the row will not appear in the query result. You can use the
outer join to see the rows that do not usualll' meet the join condition. The operator which is used to perform the
outerjoin is '+'. The '+' operator is placed on either side ofthejoin condition enclosed in the parentheses. The
syntax 1s :
SELEST TABI-EI.COLUMN, TABM2.COLI,MN
FROM TABLEI,TABLE2
WHERE TABLEI.COLLIN,rN(+) = 1431g2.COLUMN;
G
SELECT TABLEI.COLUMN, TABLE2.COLUMN
FROM TABLEI,TABLE2
WHERE TABLEI.COLUMN = TABLE2^COLUMN(+);
Multiple Tables and Sub-Queries 615

.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> |

Fi1.27.12 Equi-join after inseding a new department D06.


So, to display the department
'Economics', you have to perform an outer- EK Hel[,
SQL> SE L ECT T.TNNI,IE, D.DEPTHATIE
join, where the query will be : 2 FR O}I TEACHEB T, DEPABTiIENT
(,,TI E BE r.0EPT_N0(.) = D.DEPT
Examplg
TNNHE DEPTNAHE
SELECT T.TNAME, D.DEP|NAME
FROM TEACF{ER T. Sharsrila Kaur Phgsics
Uiuek Ralsat Physi c s
DEPARTMENT D Jugal llittal chenistrg
WHERE T.DEPT-NO(+)= Chetan Shukla chenist ry
Ashok Singhal Chenistry
D.DEPT-NO; Shyan erora Chernistrg
sandeep Kaushik l4a ths
Reena Hehta l,lath s
The above query will produce the result John Ba9 tla th 5
as shown inFig. 27 .13. Akash Rathi Naths
Lokesh Rathore Haths
RaneEh Kumar t,lat hs
Bajesh Uerna Conputer
thlrana Lamba Conputer
sinran Charula conputer
Dinesh GoeI Co np uter
Jagjit Singn Computer
Rakesh Sharna Biologg
sangeeta Uats I iolo gy
Econonics

2l rous selected.
s0r >

Fig.27.13 Query using outer-join.


Note. T'he outer-join operator can appear on only one side of the expression. A condition involving an outer
join cannot use the IN operator or be linked to another condition by the OR operator.
616 Seraswati lnformatics Practices (Xl)

27.6.4 Self joln


Sometime it is required to join the table itself. When you-ioin a table to itself this type of join is called self join.
To join a table itseif means that you can take each rorv of the table, one at a time, and combine it with itself and
with every other row of the table. You can perform a join of a table to itself as a join of two copies of the same
table. So, to perform a selfjoin you must have two different names for the same table. You can do this by simply
using the aliases.
Ex ampl e SELECT T.TT{O, T.T'NAME, Tl.TNANIE
FROM TEACTIER. T, TEACHER T 1
WlflR.E TSALARY = T'1.SAT AF1';
The above query will produce the result as shown inFig.21 .14.

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

I1? Chetar: Shukla Chet.o Shukla


.T14 Bhurena Lambe ShNafta Limha
.r 19 Siftr"aB chaEla fihr'raoa Lamba
lrl q BhlrEana Lamba Sinran Cnatt,la
'T19 si.Erar ebaula Simran Cnar,rla
'T
1s Rae*a NehtJ F€ena llFhta
T18 ekesh Rathi Reena l4ehta
T13 Reena ilehta Akash Rathi
T18 fikash flathi ekash Rethi
TB1 Bakesh Sharna Sakesh SharRa
sTI0 Rajesh Uerna Eakesh SharBa
;rol Rakesh Sharna Bajesh Uerna
.T1B Rajesh uerfiil RajeEh germa
T15 Jagjit Singh Jagjit Singh
r11 fishok Singhal Rshok Singhal
r05 SanEeeta Uets Sangoeta Uats
T09 Uivek fiaruat Ui$ek Balrat
r07 Shgan Arora Shyam Sr6ra
T08 John RaU John R.q
I06 Sanesh Kunar Ranesh l{rlnar
T04 Sandeep Haushik SandPep Naushik

THO lHAr,tE THfihIE

T53 Sharmila Haay Sftar,lila l(3ur


22 rous selecteal-

Fig. 27.14 Query using self ioEn.


27"7 Sub-Queries
In SQL you can place one query inside another query. This types of query is called sub-queries. In the sub-
query, the inner query generates values that are tested in the condition of the outer query. In order to evaiuate
the outer query, SQL first evaluate the inner query within the WHERE clause. In simple words a sub-query is a
SELECT statement that is included in a clause of another SELECT statement. The sub-query is useful when you
need to select rows fr<rm a table with a condition that depends on the data in the table itself. You can place the
sub-query in a number of clauses :

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.

.SQL *sii,iv.rB ,rnn ,lY/rl


SELECT TNANE
2 FRON TERCHER
I'HERE SELARY >
r{ (SELICT SRLRRY FROH TERCHES
i5 til{ERE Tm = ,T0s');
;TNNHE

.Sharnila t(aur
jsandeep ilaushilr
'Reftesh Xrmar
Shyam Arara
lJohn Ray
'Uiuek Baruat

i6 rous selected-
SQL> I

Fig.27.15 Finding salary using Sub-query.


27.8 Guidelines for Using Sub-eueries
You must follow these guideline to write a query :

tr Query must be enclosed in parentheses.


tr A sub-query must appear on the right side of the comparison operator.
tr ORDER BY clause are not allowed in the sub-query.
tr You cal have only one ORDER BY clause for a SELECT statement, and if specified rt must be the iast
clause inthe main SELECT.
tr You can use the single row operators with single row sub-queries( i.e.,),
=, )=, <, <>, <=)
tr You can use the multiple row operators rvith multiple row sub-queri es( i.e.,IN , ALL )

27.9 Types of Sub-Queries


There are generaliy four types ofqueries. They are:

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

+ Less than or equal to


o Not equal to
Example SELECT TNAME, SALARY
FROMTEACHER
WHERE DEPT NO =
(SH-ECI DEPT_NO
FROM TEACHER
WHERE TNO='TO4');
The above query display the teacher name and salary of the teacher whose department is same as that of
teacher no 'T04' as shown in Fig.27 .16.

sELESr rl#c, sd_effi


2 FEET TENGflEB
I UFIERE DEPT I.II
4 ( SELECT DEPI TM
5 FNOM TENCHEN
6 I{HEBE IM} -'rBl{']
:TIsilE

SandEep (aushik 152 06


ilamsh l(urar 1t2 00
John Rag 132 0B
;8eena llehta 57 E0
;Lokesh Bathore
inkash Bathi 570t
iu .o*. selectad -
i

:SQL}

Fig.27.16 Finding salary using Sub-query.


Example SFr FCI TNAME, SALARY
FROM TEACHER
WHERE DEPT NO=
( SELECT DEPT_NO
FROM TEACI{ER
WHERE TNO='T04')
AND SALARY > l?
(SELECT SALARY Ih
ll
FROM TEACHER
WHERE TNO='Tl0');
{
t
Multiple Tables and Sub-Queries 619

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

Siindeep Baushik 15280


Ramesh (unar 14200
John Rag 13200

Fig.27.17 Resulted output of three queraes.


You can also use the group functions in the sub-query.
Example SELECT TNAME, SALARY
FROM TEACMR Ek 5aach lptins E+
WHERE SAr AI(Y=( sqL) SELECI tNeH€, SALtRY
2 FROH TEsCHER
SEI,ESIMIN(SAI-AR})
3 tflIERE SRLARY = (
FROM TEAC}IER): tt SELECT HIH(Sf,LRRY}
5 FROH TEfiCHER);
The above query finds the minimum salary
from the TEACffiR lable i.e.,3600 and the outer TNRHE SRL flRY

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.

Fig.27.18 Group function in sub-queries.


27.9.2 Multiple Row Sub-Query and its Execution
A multiple row sub query returns more than one row and uses the multiple row compaiison operators. The
multiple row operator returns more than one value.
Example SELECT TNAME, SALARX DEPI_NO
FROM TEACMR
WHERE SALARY IN ( SELECT MIN(SALARY)
FROM TEACHER
GROUPBYDEPT_NO);
In the above example the inner query result in 5 rows :10200, 3600, 5700, 4700 AND 5800. The main query
uses these values to returned the result given in Fig 27 .19.
620 Saraswati lnformatics Practices (Xl)

> SELECT TH$HT, SAI-hRV, DEFI-iIO


2 FNO}I TEfrCHEB
c llllrEsE seLfi*y rN ( SELECT Hrr{(sftLAFv}
4 FNOI4 TEECHEB
5 SRIIUP BIDEPT

lTHAfiE SELNf,g DEPT


i-----------
ichctan shukla 3600 D02
iBheane LarDr l!700 004
isimran ChaBli d7G0 Dorr
lReena mehta 5700 ft03
Jftkasn Bathi 5700 D03
if,akesh Sharma 5800 005
iRajesh Uerrua 5800 0Gq
iUiuek Rairat 10200 001

j8 rous selected.
JSqL>

Fi1.27.19 GROUP BY clause in sub-queries.


Example SELECT TNO, TNAME
FROM TEACHER
V\TFIER.ESAIARY<ANY(
SELECT SALARY
FRO]V{TEA
WTIEREDEPT NO=D(2');
The ANY operator compares a value to each value returned by a sub-query. The sub-query retums the
following result : 122{fi,7700, 3600 . The outer query returns the result as shown inFig27.20.

sQL> SELECT Tilo, TitAflE


2 FRO}I TEECHER
3 hf,{ERE SALr{RY < nHY (
4 SELECT SALRRY
5 FROi4 TEECHEB
6 HHERE DEPT flO =

: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>

Fig.27.2A ANY operator in sub-queries.


Note. <ANY means less than the maximum, >ANY means inore than the minimum, - Al{Y means equivalent to
IN.
Multiple Tables and Sub-Querles 621

27.9.3 Multiple Column Sub-Query and its Execution


The multiple column sub-query returns the multiple columns. Multiple column sub-queries enables you to
combine duplicate WHERE conditions into a single WHERE clause. The syntax is :

SFI FCT COLUMNI, COLUMN2,....


FROM TABLENAME
, WHERE ( COLUMNI, COLUMN2,....) rN
( SELECT COLUMNI, COLUMN2, ....
FROM TABLEN.AME
WHERE CONDTTTON);
E x amp le SELECT TNO, SALARY
FROMTEACTIER
WHERE(TNO,SALARY)
IN ( SELECT TNO, SALARY FROM TEACHER
WHERE DOJ =' 16-JUL-0 l');
From the above query, the inner SELECT statement finds the teacher no. and salary of teachers whose
dateofjoining(DOJ)'16-JUL-01'.Theresultedrowsofinnerquerywillbecheckedwiththeouterquery. The
outer query retums the result as shown inFig27.21.

> SELECT IlE, SeLRfiy


C FROI'I TERCIIER
3 I|ERE (THo, SRLnRY)
4 rlt ( SELE0T Tll0" SfiLRRT FSoM IEACIER
5 l,,l{EBE DOJ *'16-JUL-01 '}:
:IHO
i----
:r14 4700
irle
I
47 0S

!sQL>

Flg. 27.21 lN operator ln sub-querles.


27.10 Creating aTable Using a Sub-Query
A second method to create a table is using CREATE TABLE statement with the sub-query. Both create table
and insert rows retumed from the sub-query. The syntax is :

CREATE TABLE new table name


AS

SELECT column namel, column name2,.........


FROM oldtable name
IWHERE condition];
E xample CREATE TABLE TEACHER1
AS
SELECTTNO,TNAME
FROMTEACHER
WHERETNC>'TO2';
622 Saraswati lnformatics Practices (X!)

The above statement creates a table called


TEACHER1 which stores the TNO, TNAME of those
teachers who's TNO is greater than T02 as shown in
> CRERTE TfiBLE TENBilERl
RS
Fig.27.22. SELECT rfto, rNnilE
FROiI TEACT{ER
r{IEBE TNo ) 'I02' ;

Fi1.27.22 Creating a table using sub-query.


27.11 Copying Rows from AnotherTable
You know how to insert the values into the table using the
INSERTINTO command. And in the previous section you learn SQL> II'ISERT INTO TEACHEB,I
2 SELEGT INO, TNAI'IE
how to create table using another table. Similarly, you can insert 3 FBOII TERCI{EB
the rows in any table from another table. As in the above section 4 IIHERE TNo = 'I01';
you have created a table called TEACI{ER 1 . Now, we will insert il ros, created.
the values into that table using the table TEACHER. * FR0H TEechcBl;
isQL> sELEcr
E x amp I e INSERT INTO TEACIIER I rlNll THRNE
SELECT TNO,TNAME T03 sharnile l(aur
FROMTEACT{ER T04 Sandepp Naushik
WHERE TNO='T0l': T05 Sangeeta Uits
T06 BaFesh KurBar
,TE7 Shyaa firora
So, after the above command executed the TNO and ,T08 John Rd!
TNAME of the teacher number T01 get copied into the table .T09 uiuek Baoat
:T10 RaJesh ueroa
TEACHERI. When you will apply the SELECT command with :T11 nshok singhal
iT12 Chetan Shukle
TEACHER1 table, the following Fig. 27 .23 willbe appear. iT13 Beenb l4ehta
iT1{ Bnuana LanDa
,l'19 Jaqjit Sirqh
iT16 Dinesh coel
tl17 LokPsh Sathore
iT18 fikash B.thi
.T19 Sinran Chdi,Ia
T01 Rakesh Sharna

i'|8 rous selecte.l.


isQL>

Fig.27.23lnserted records in TEACHERl table from TEACHER table.


You can also use the sub-query to insert the rows as shown below :

E x amp le INSERT INTO TEACT{ERI


SELECT TNO,TNAME
FROMTEACHER
WHERE SALARY = ( SELECT MAX(SALARY ) FROM TEACHER);
So, in the above example, the sub-query will get executed first and the highest salary is calculated. This
value is used by the outer query to insert the value into the TEACHERI table. After inserting the record, use the
SELECT command to display the records as shown inFig.27.24.
Multiple Tables and Sub-Queries 623

:, I rs,t-4l?i\r, $flr$qq*#f ,J}'ili

SQL) SELECI i FR0t4 TE0CHERI;

IITO TNAhE

T03 Sharnila l{aur


T94 Sandeep Kaushik
.T05 Sanq€eta uats
rT06 Ramesh Hunar
iI07 Shgam nrora
,I0S John Rag
T0S Ulvek Bawat
TIB BajPsh Uerma
I11 eshok Singhal
:112 Chetan Shukla
T13 Beena ]lehta
jT14 Bhtrana LamDa
irls Jegjit singh
lT16 Dinesh coel
,117 Lol(esh Rathore
;I18 ekash Bathl
'I19 Sinran Chawla
Ittl EakPsh Sh.rma
'T 03 Sharnila l{aur

19 ro?rs sPlected-
SQL> I

Flg. 27 .24 lnserted records using sub-query.


27.12 Deleting Rows Based on Condition from AnotherTable
You can also use the sub-queries to DELETE the rows from a table. Consider the two tables :

TEACIIER and TEACIIER1 (TI\{O, TNAME)


Now if you want to delete the rows with the qs*ox Eab
department name 'Physics' then the command SQt) DELETE FBO}I TEREHER1
would be : 2 I{HERE THO I}I (SELECT TNO FRO}I IEACHEB
3 iTHERE DEPT_N0 = 'D03' ) ;
DELETEFROMTEACHER1 6 ross d?leted-
WHERE TNOIN(SELECTTNO
isqL> SELECT { FRol,l TEnGHERI;
FROMTEACTIER
WHERE DEPT_NO='D03') itHo rilfiirE
When tire above statement executed, it will iI03 Sharnila Kaur
be delete 6 records. Apply SELECT command to :f05 Sangeeta Uats
.f07 Shran Rrora
display the remaining records as shown in Fig. iI09 Uiuek Rauat
27,25. ]rro Bajesh uerna
iI11 nshok Singhal
112 Chet.n Shukla
:T1q Bhurana Lamba
irrs JagJit stngh
!116 Dinesh Goel
lI19 SLmran Charxla
f01 Bakesh Sharma
I03 Sharmila Kaur
-13 rolrs sElected.
SQL> I

Fig.27.25 Remaining records in TEACHER1 table.


27.13 Updating Rows Based on Another Table
You can update the table using sub-queries in the similar way as DELETE. Let us write a query as :

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

:T63 Sharnila l(aur


'f05 sihul uerna
,TB7 shuam Aror.
lI09 Uiuek Rawat
rT10 n:jesh UErna
:T1'l Rshok Singhal
,112 Chetan shukla
Tl lr Bhr,,ana Lanba
1I15 Jagjit Singh
'T16 Dinesh coel
T't 9 Sinran thaurla
TO'l RaLesh Sharna
T63 Sharnila Haur
j18 rous selected-
I
isor-> |

Fig.27.26 Update a record using another table using sub-query.


27.14The UNION clause
We can combine multiple queries by using UNION clause. But thecondition to apply union
clause is that both
the tables should have same structure and specify the column name of both the tables in the same
sequence.
The form is as :

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

?sQL> SEI.ECI IIIO, TN4I{E FROTI IEiCHEN


UNIOH
SELEET TNO, INEHE FROH IENCHER1;

iTHo IHRnE

lTEl f,okesn Sharma


ltsz Jugal Mittar
1I0S sharnila l(aur
lf0{ sandeep Xaushik

:I12 f,hetan shukla


f13 Seena Hehta
fl4 Bhrlrana LaEba
I15 Jagjit Stngh
lI16 Dlnesh GoeI
iT17 Lokesh Bathore
iT18 Qkash Rathi
Simran Cnarola
iTl9
p8 rous selecte.l.
!

itot'
l

Fi1.27.27 Using UNION clause between two tables.


If we want to display the duplicate rows also then we use the ALL option. The form is as :

SELECT statement
LiNION[ALL]
SELECT statement;
Example SELECT TNO, TNAMEFROMTEACIDR
I.]NIONALL
SELECT TNO, TNAME FROM TEAC}IERI;

27.15 lnserting Date Values into Table


You can use the special values to insert into the table. For example, if you want to insert a new teacher into the
TEACHER table with the DOJ as the cunent date, the query is :
INSERTINTOTEACI{ER
VALUES(T20','Sonam Kalra','D-71 6, Ashok Vihar', 1 2000,'D02', SYSDATE)

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;

IiIO TIIA}IE I6DDBESS SALREY DEPT DOJ


jT01 Rakesn Sharna 24s-Naluiya H.gar 5880 065 1 2-DEC- 01
'r 02 Jugal H!.ttaI 3lr, Bamesh Hagar 002 03-JUL-99
:T03 Sharmila l(aur D-31, nshok Uihar 20260 D0'l 06-JUfl- 00
]r04 SandPep Raushik l,lc-32, Shalinar Bagh 15200 003 08 -tuc-
iT05 0J
sangeeta uats G-35, Helulua llager 9100 D0s 2 0-FEB-00
T06 R.nesh Hunar 0G-42, Shalinar Bagh 14200 D03 03-JUL-97
jT07 Shlam Rrora 50, HIC FL0TS, Rohini 12200 D02 1 5-AUE- 98
;T08 John Ba} B-tr4, !(irti Nagar 13200 D03 22-SEP- 01
T09 Uluek Raorat E-ggl?7 , SPc-1, Rohini 1 0200 D01 -t2-0cT- 01
irl sEajesh Uerma D-1'1./1*0, sec-5, Duaraka 5800 D0Ir 07-ilou- 06
lrrr eshok Singhal F-1165, East Patel Ngr 7700 002 11-RU0-99
T12 Chetan Shukla C-165,10th Cross 3600 D62 1 3- JUN- 01
ir13 Beena t{ehta '128, DDn Colong 5700 D03 18-JUL-00
rTlIr thsrana Lanba E-l4a!. Surastik npptt., DLF {700 D0Ir 1 6-JUL- gl
;T15 JagJit singh A-240, Printers Rpptt. 6700 004 1'r-JUt-98
Itt 6 Dinesh GoeI n21-IriuEni npptt.
jrl Lokesh Bathore
D 0Ir 1 2-oCT- 00
z C-11, HIG FIat D09 1 7-JUL- 09
iT18 fikash Bathi R-52, Sansad l,larg 57S0 D03 18-JUL-80
lr19 Sirsran Chasla D-"11129, Sec-5, fiohini q700 DD4 16-JUL- 01
ir2 0 Sonan l{alrr D-2/16, Ashok Uihir 12000 D02 08-JUN- 03
r21 Rohit Deroan H-26/56. iloti Hagar Bg00 Dotr 05- APR- 98
'21 rovs selected.

(l I

Fi1.27.28 TEACHER tabte records.


27.16 Use of Substitution Variable to lnsert Values
SQL*PLUS allows you to use substitution variables in the NSERT statement that allows the user to
add values
into the table.
INSERTINTOTEACHER1
VALI]ES('&T_NO','&T-NAME')
When you execute the above statement, the following Fig. 27.29 will be appear with the prompt that
allows the user to enter the values for the teacher number and teacher name.

isQr) INSEBT INr0 TEfiCHTRf


12 URTUES( .&I _N0" '&T_
for t no: T20
lEnter u.1ue
for t' nane; Sonan l(alra
lEnter ualue
01d 2: UfiLUES( '&r*N0', '&T_HRnE.)
'neu 2. UfiLUES( 'T20', 'Sonam halra')
;1 row created.
i
jsQt>

Fi$.27.29 Substituilon values to insert rows in TEACHERI table.


Note. Only for date and character values, the ampersand (&) and the variable names are enclosed
in single
quotation marks.
Multiple Tables and Sub-Queries 627

27 .17 Database Transactions


Transaction control, or transaction management, refers to the capability of a relational database management
system to perform database transactions. Transactions are units of work that must be done in a logical order
and successfully as a group or not at all. The term unit of work means that a ffansaction has a beginning and an
end. If anything goes wrong during the transaction, the entire unit of work can be cancelled if desired. If
everything looks good, the entire unit of work can be saved to the database.
A transaction begin when first executable SQL statement is executed and end with one of the following
events :

D COMMIT or ROLLBACK issues.


tr DDL or DCL statement execute committed automatically.
tr User exits.
tr System crashes.
You can control the transaction using the COMMIT and ROLLBACK statement. The advantages of the
COMMIT and ROLLBACK statements are :
D To ensure data consistency.
tr Preview data changes befbre making changes permanent.
27.17.1 COMMTT
The commit statement ends the current transaction by making all pending changes perrnanent. The previous
state of the data can be recovered before applying the COMMIT statement. After applying the COMMIT
statement the data changes are made permanent in the database. The previous state of the data is permanently
lost.
E x am p le UPDATE TEACHER I
SET TNAME = 'Anand Sharma'
WHERETNO=T03'
To finish the current transaction for the above LTPDATE command, issue a COMMIT contmand as shown
inFig27.30.

SQL}

Donnit conplete.
rsql> |

Fig.27.30lssuing the COMMIT command to finish a transaction.


27.17.2 ROLLBACK
The ROLLBACK discards all pending changes. The data changes are undone and the previous state of data is
restored.
E x amp le UPDATE TEACHER1
SETTNAME='AlokJoshi'
WHERETNO='T03';
628 Saraswati tnformatics practices (Xl)
After using the UPDAIE comrrand, apply the SELECT command to display the record for
T03. you will
notice that the teacher no T03's name has been changed to Alok Joshi. Now, apply
ROLLBACK command, you
will notice that the changed name Anand Sharma is again with the teacher number T03 as shown inFig.21.3I.

SQL> UPDflTE TERCIIER.I


2 SET II{R}IE =
3 IIHEBE T](I =

Rlok Joshi

FRO}I TEAIHE*I
- 'T0t';

Fig.27.31 lssuing the ROLLBACK command revert the change.

Solved Exercises

Q1. What is join ?


Ans. The most important feature of the SQL is its capability to retrieve data from the multiple table in term of
relationship according to the common field, in the single command. This kind
of operation is called join.
Q2. What is caitesian product ?
Ans' The Cartesian product of two relations is the concatenation of tuples belonging to the two relations.
The
Cartusian product is a binary operation and is denoted by (x). Tire degree ofnew
relation is the sum of
the degrees of two relations on which Cartesian product is operated.
Q3. What is equi-join ?
Ans' The join, in which joining condition is based on equality between values in the common
column, is
known as equi-join.
Q4. What is non-equi-join ?
Ans' When there is no common column in two tables and then we perform a join. This type ofjoin is called
non-equi-join.
Q5. What is outer join ?
Ans' When any row does not satisfy the join condition, the row will not appear in the query
result. you can
use the outer join to see the rows that do not usually meet the join condition.
The operator which is used
to perform the outer join is '+'. The '+' operator is placed on either side of
the join condition enclosed
in the parentheses.
Q6. What is self join ?
Ans' Sometime it is required to join the table itself, when you join rable to itself this type
a ofjoin is called self
join.
Multiple Tables and Sub-Queries 629

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

ENO EI\AME JOB !}ffi HIREDATE SAt, COI}IM DmT


7369 SunitaShanna CLERK '79A I7-DEC-80 2800 n
7499 Ashok Singhal SALESMAN 7698 20-FEB-81 3600 300 30
752,1 Rohit Rana SALESMAN '7698 22-FEB-81 52s0 500 30

7565 JyotiLamba MANAGER 7839 02-APR-81 4n5 n


7654 Martin S. SALESMAN 7698 2&SEP{1 Aso 1400 30
7698 Binod Goel MANAGER 7839 0I-MAY-81 s8s0 30

77U Chetan Gupta MANAGER 7839 09-JUN-81 2.4s0 10

7788 Sudhir Rawat ANALYST 7566 I9-APR-87 5000 n


7839 Kavita Sharma PRESIDENT I7-NOV-81 5000 l0
7U4 TusharTiwari SALESMAN 7698 08-SEP-81 4500 030
7876 Anand Rathi CLERK 1788 23-MAY-87 6100 n
79C0 Jagdeep Rana CLERK 7698 03-DLC-81 4950 30

7W2 SumitVats ANALYST 7566 03-DEC-81 3500 3600 n


7934 Manoj Kaushik CLERK 7792 23-J.AN-82 5300 l0

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 ?

Il. What is the difference between implicit and explicit transaction?


12. What is the difference between COMMIT and ROLLBACK ?
13. Consider the two tables given below :

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'

9 KUSH 4t SWTMMINC 13i0111998 900 M


IO SHAILYA 31 BASKETBALL 19/0211998 17OO M
TABLE:COACHES
SPORTSPERSON SEX COACH-NO
AJAY MI
SEEMA ?2
VINOD M1
TANEJA F3
(r) What will be the output of the following query :

SELECT SPORTSPERSON COACHNAME FROM CLUB, COACHES


WHERE COACH ID:COACH NO;
(ii)Display the natne of the coach who is giving training to 'AJAY'.
(ili)Display the narne of the person and coach where coach id: coach no and natne of the coach is
RAVINA.
(lv) To display the coach natne and sports who are teaching the same sports.
14. Consider the two tables given below :

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)

3 DMYA 3OO CHEMISTRY A 2


4 ARUN 3.50 PTrySICS 63 I
5 SABINA 5OO MATHEMATICS 70 1

5 JOFIN 4OO CHEMISTRY 55 2


7 ROBERT 250 PHYSICS @ I
8 RUBINA 450 MAI'HEMATICS 68 1

9 VIKAS 5OO COMPUTERSC 62 I


IO MOHAN 3OO MATHEI\4ATICS 57 2

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

2 Puneet State Bank 25m0 oll02l97 0l


3 Anirban OrientalBank 17000 t:t07199 05

4 Yatin Standard Charted 38000 rc102199 l1


5 Sunny StateBank 47000 06102198 15

6 Jayant Uco Bank 34000 10/08/98 Al


7 Nikhil Bank of Baroda 56m0 02lol9 12

8 Tarun Orientalbank 2W MIMM 08

9 Jisha Uco Bank 345m 05/01/98 ll


TABLE:CUSTOMER
CH Tname TBank
I Yatin Standard Charted
2 Sunny State Bank
5 Puneet Uco Bank
4 Nikhil Bar.k of Baroda
5 Varun Oriental bank
(a) To the name of the customer where tbank value is same as the bbank value.
(D) To digplay the Acc_no of the customer and Tbank where dateofopen is > 01102197.
(c) What will be the ourput of the following query :
Select Cname, TBank
From banh Customer
Where Cname: Tname;

t
Chapter - 28

Creqting Views qnd privileges

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;

Tll0 Tlrfi!tE SALARI


Example CREATEVIEW TEACH
AS ,T 65 sangefta Uats 91 00
r6d Baoesh l(unar 14200
SELECT TNO,TNAME,SALARY r07 Shgam erora 1228A
FROM TEAC}IER r08 Joftn Ray 132 0B
TBg Uiuek Saqrat -t0200
ORDERBYTNO; T1B Rajesh Uerna 58 90
T11 Rshok Singhal l7 00
28.6 Retrieving Data from a View 112 Chetan Shukla 36 B0
T13 Beena iiehta 57Bg
Views can represent data within tables in a more T'14 Bh?.,ana L.nba 4708
convenient fashion than what actually exists in the T15 Jaqjit singh 67BA
116 Dinesh coel
database's table structure. Views can also be extremely 117 Lo*esh Bathorp
convenient when performing several complex queries T1B Akash Rathi 5780
,T19 Simran Chaula 47 [C
in a series. You can retrieve the data from a view T20 Sonan l(alra 1 2060

using the SELECT statement. r21 Bohit Detan $9 0B

Example SELECT x FROM TEACH; ,17 rol,,ts splpcted"

The above command will produce the view .sqL>

result in table TEACH as shown in Fig. 2E.1.


sld
Fig.28.1 View result using SELECT cornmand.
636 Saraswati lnformatics Practices (Xl)

28.7 Querying a View


Once your view has been created, you can query the data dictionary table called USER-VIEWS to see the name
of the view and the view definition. The text of the SELECT statement that constitutes your view is stored in a
LONG column. The statement to see the view is :
SELECT * FROM USER-VIEWS;
28.8 Moditying a View
As you have leamt, by creating a view on one or more physicai tables within a database, you can create a virtual
table for use throughout an SQL script or a database
application. After the view has been created using
,FIE'
the CREAIE VIEW...SELECT statement, you can
sQL)
modify a view using the OR REPLACE options. This 2 (rH0, rflfillE, D0J)
fiS
option replace the old version of the view. !r SELECT TN(l, THqNE, DOJ
Example CREATE OR REPLACE VIEW TEACH 5 FRO14 TEACHER
(TNO,TNAME,DOJ)
6 i,HERE DEPT-N0 ='D01';
AS Uie!, crrated -

SELECT TNO,TNAME,DOJ SqL> SELECT * FROH TEACH;


FROM TEAC}MR irtro rNoNE DoJ
WHEREDEPI-NO='D0l';
T03 Sfarnila Haur q6-JUN- U0
After modifying a view can view the changes Tg9 Uiuek Rauat 12-0CT - 0'r
using the select statement.
SQL>
SELECT XFROM TEACHI
The above command will produce the view
result in table TEACH as shown in Fig.28.2.
Fi1.28.2 Modified View result usang SELECT command.
28.9 Complex View
A complex view is one which is created from more than one table. It can also contain the group function. For
exampie, lets create a view using the group function using two tables.
Example CREAIE VIEW COM-TEACH (NAME, MIN--SAL, MAX-SAL)
AS SELECT
'
D.DEPTNAME, MIN(T.SALARD, .rh". E* 9.afch Qdbrs S*, :

MAX(LSALARY) sQt> CBEATE UIEI' COI,I TERCH


2 (l{fiNE, NIil_SnL, l,lAx_SAL)
FROM TEAC}IERT, RS SELECT
t{ D-DEPTilRNE, HrH(T-S0LABY), l4ex(r.SCLnBY]
DEPARTMENT D 5 FBOI{ TENCilEE T, DEPfiRII'IEHT D
6 \IHERE T"DEPI-NO - D-DEPT*NO
WHERETDEPT NO =D.DEIrI NO 7 GBOUP BV D.DEPTNRHE;
GROUPBY D.DEPTNAME;
'UieN created -
The above example create a complex
SQL> SELECT * FRol'l
view of the department name, minimum salary
and maximum salary by the department. You HR}tE NIN-SNL }IBX.SOL

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.

Fig. 28.3 Complex view result using SELECT command.


Creating Views and Privileges 637

28.10 Rules for Performing DML Operations on a View


You can perform DML operations on simple view. But you cannot remove a row if the view contains the
following:
tr Group functions
tr GROUPBYclause
tr DISTINCTkeyword
You are not able to modiff the view if the view contains the above mention condition and if the view
columns are defined by using expression. Also you will not able to add data into the view if the base table
contain NOT NULL columns which is not selected by the view.

28.11 Dropping Views


ln common with every other SQL CREATE... command, CREATEVIEWhas acorresponding DROP... command.
The syntax is as follows :

DROPVIEWview name;

Example DROP VIEWTEACH;

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.

28.13 Creating Users, Granting and Revoking Privileges


The Oracle system comes with two users already created, SYSTEM and SYS. you log on to the SYSTEM user
to create other users, since SYSTEM has the that privilege. The CRETAE USER coniinand is used to create a
user, the sl,ntax is as :

CREATE USER USERNAME IDENTIFIED BY PASSWORD;

ExampIC CREATEUSER MASTER IDENTIFIEDBY MAIN;


The above statement create a user with username 'MASTER' with a password 'MAIN'.
Each user in a SQL database has a set of privileges i.e.,the things the user is permitted to do. The SQL
privileges defined by ANSI are object privileges. This means that a user has a privilege to perform a given
command only on a ceftain object in the database. The user of a table has all privileges on their table and they
can assign them to others. These are :

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
:

GRANT SELECT ON EMPLOYEE TO TRANSACTION;


Norv. the user TRANSACTIoN can perform queries on the EMPLOYEE table. The user Transaction can
only perform query on the EMPLOYEE table. This user can't GRANT to tire other user onthe EMpLOyEE table
because the EMPLOYEE table is still owned by the I\4aster. The syntax is same for granting the other privileges.
For example to grant a INSERT privilege the comntand is :

GRANT INSERT ON EM PLOYEE TO TRAN SACTION;


You can give morc than one grant to tnore than one user in a single statement as shorvn in the example
given belor.v :

G RAN T SELECT, IN S ET{T ON EM PLO}'EE TO TRAN SACTION. SLA\ES


;

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
:

REVOKE PRI\/ILEGE TABLENAME FROM USERNAME;


For example, if you r+'ant to remove the select privilege given to the user TRANSACTION you can
write
the statement :

REVOKE SELECT ON EMPLOYEE FROM TRANSACTION;


Similarly, you can also revoke the other privileges.

28.1 4 Referencing Another User Table


If the table does not belong the user, the user can refer that table using the owner's name as a prefix. to the table
name. As we had created a user TRANSACTION in the above example. The TRANSACTION can
use the table
ofthe MASTER by using the MASTER as a prefix:
SELECT * FROM MASTER.EMPLOYEE;

28.15The Creating and Dropping Synonyms


A synonym is an another name oftable. It refers to the a table owned by another user and used to shorten the
lengthy names. As you know you can use the table of another user by using the owner's name followed by
a
period with a table name. Creating synonyms eliminates the need to qualifo the object name and provides you
the alternative name for a table or view. The syntax is :

CREATE IPUBLIC]SYNONYM name


FOR object;
The PUBLIC creates a synonym accessible by all the users. A private synonym must be distinct from all
other objects owned by the same user. only DBA can create or drop the publ,c synonym.

Exomple CREATE SYNONYN4 CT


FOR COM TEACH;
The above statement create a synonym for the COM-TEACH view for quicker reference. Now, instead of
wntlng a statement :
SELECT * FROM COM_TEACH;
You can write a statement :

SELECT*FROMCT;
When you will execute the above statement. SQL PLUS will display the synonyms as shown in Fi
9.28.4.

!s[L> cnEgTE SYMNyI'| CT


2 FOR C{IH_IEflCH;
sunonuD created_

SQL> SELECT * FRol,t CT;

11T___ ____ _
HrH sRL Hex snl
Eiology 5888 9100
Dhenistry 36BB 12295
Computer {708 8960
ll4aths s76B 15206
,f hysics 1S290 2@00
rsQL>

F19.28.4 Synonyms for COM_TEACH view.


Example CREATE PTIBUC SYNOI.{\t{ EMp
FOR MASTER.EMPLOYEE;
The above example create a PUBLIC synonym EMPfor the table EMPLOYEE owned bytheuserMASTER.
Now, any user can access the table using rhe word EMp instead of MASTER.EMPLOYEE.
To drop a synonym, use the DROP SYNONYM statement.

Example DROPSYNONYM EMP;


28.16 Renaming an Obiect
You can change the name of table, view, sequence, or synonym by using the RENAME statement. The syntax
1S:

RENAME OLD_NAME TO NEW_NAME


Example RENAME TEACHER1 TO TEACIIER2;
After executing the above statement the name of the table TEACHERI gets changed TEACHER2.
28.17 Truncating a Table
The TRUNCAIE TABLE statement is used to truncate a table. The TRUNCAIE TABLE stai.ement removes all
rows from a table and releases the storage space used by the table. You cannot roll back after using the
TRLINCATE. The syntax is:
TRTINCATE TABLE TABLE_NAME ;

Example TRUNCATE TABLETEACHERI;


Note. You can apply the TRUNCATE TABLE statement if you are the owner of the teble you have DELETE
TABLE system privileges to truncate a table.
640 Saraswati lnformatics practices (X!)

28.18 Adding a Comment to aTable


COMMEN'I statement is used to add comnents to a table or the column. You can add comment upto 2,000
bytes about a column, table, or view. The comment gets stored in the data dictionary and can be viewed in one
of the follow'ing data ciictionary views in the comments column.

EI ALL COL COMMENTS


tr USER COL COMMENTS
A ALL TAB COMMENTS
tr USER TAB COMMENTS
The syntax is as :

COMMENT ONTABLE table narne/table.colurnn narne


IS 'text':
Example COMMENT ON TABLE TEACHER
IS .THIS TABLE STORES THE DATA OF THE TEACHERS'I

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 :

ENO E\AME JOB MGR HIREDAf,E SAL COMM DEPT


7369 Sunita Sharnra CLERK 7902 I7-DEC-80 2g00 n
1499 Ashok Singhal SALESMAN 7698 2GFE&81 3600 300 30
. 1521 Rohit Rana SALESMAN 7698 22.FEB-81 y5O 500 30
7565 Jyoti Lamba MANAGER 7839 02-ApR-81 4yt5 n
7654 Mar-tin S. SALESMAN i69B 28-SEp-81 A5A 1400 30
7698 Binod Goel MANAGER iB39 0l-MAy-81 5850 30
7782 Chetan Gupta MANAGER 7839 09-JLIN-81 24SO t0
7788 Sudhir Rawat , ANALYST 75(f 19.ApR-87 5000 n
7839 Kavita Sharma PRESIDENT I7-NOV-81 5000 l0
78/4 Tushar Tiwari SALESMAN 7698 08-SEp-81 4500 0 30
7876 Anand Rathi CLERK iiBS 23-MAy-87 6100 n
Creatinq Views and Privileqes 641

7900 JagdeepRana CLERK 7698 03-DFC-81 4950 30

7942 sumitVats ANALYST 7566 03-DEC-81 35m 36m n


7934 Manoj Kaushik CLERK 77V2 23-JAN-82 5300 l0

(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. What is the difference between simple view and complex view ?

2. Howwill youretrieve datafrom a view ?


3. Which command is used to query a view ?
4. What are the rules to perform a DML ?
5. Howwilldropaview ?
6. What is a user ? How SQL identi! a user ?
7. How will refer the table of another user ?
8. How will create and drop a synonym ?
9. Consider the tables given below and answer the questions from (a) to (f):
TABLE: SUPPT,E.R
S# PName SName aty Price City
SI Bread Britannia 150 8.00 Delhi
52 Cake Britannia 250 20.00 Mumbai
53 Coffee Nescafe 170 45.m Mumbai
54 Chocolate Amul 380 10.00 Delhi
55 Souce Kissan 470 36.00 Jaipur
642 Saraswati lnformatics Practices (Xt)
56 Maggi Nestle W 10.00 Kolkata
57 Biscuit Marie 560 2t.N Chennai
58 Jam Kissan D0 40.00 Delhi
59 Pilalik y5 5.00 Kolkata
(a) create a view having the field pNAME, ery and pRICE where city as Delhi.
(6) Create a view with all the fields of the above table in the ascending order of the field SNAME.
(c) create a view with the fields ENAME and SALARy having price more than 20.00.
(d) Suppose their is another user Rahul and the user of the tiute suppLIER is Amit. write a granr
statement to give the select and insert privilege to the user Rahul.
(e) Revoke the privilege given to the user Rahu,L
U) Create a slmonym of the view cretaed in part (a).
k) Drop the syno4ym.
ft) Modi8 the view created in part (b) as include only PName and Sname for the supplier having city as
Mumbai.

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 :

0000 *0000 = Textl

The above form's object properties are :

Object lcon Property Property setting Property description


form Name Forml Identifies the form.
Caption General Purpose Form title bar display.
Calculator
Frame ar'r.
ir
lt

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.

Labd A Name firtAnswer Identifies the Label.


Caption Label value.
Change Sign J Name cmdChangeSign Identihes command button
Text that appeats on button.
Caedm Change Sign
TUtr 1 Tab order.
Answer ;J Nalte cmdAswer
Answer
Identifies command button
Text that appears on button.
Caption
Thblrdex 3 Tab order.
Next ;iJ Name crndNext Identifies command button
Caption Next Text that appears on button.
,,
thblrdex( Tab order.
Check _.* Name cmdCheckAnswer Identifies command button
Caption Check Text that appears on button
Thbfdex 4 Tab order.
Check v Name
Caption
chkRandomSign
Auto Change Sign
Identifies the Checkl.
CheckBox display.
Value 0'Unchecked Check value
Timer Name Timerl Identifies the Timer.
Emble Thre Initialtime display.
Interval 500 Timerinterval.
L€ft 2190 Left alignment.
frp 3735 Top alignment.
7 button t, Name qndNrrnber Identifies 7th button.
,",,,.$

Caption 7 Text that appears on button.


Index 0 Button index value.
8 button Name crrdNunber Identifies 8th button.
--* Caption 8 Text that appears on button.
Ind€x 1 Button index value.
9 button Name cnrdNrmber Identifies 9th button.
-,* Caption 9 Text that appears on button.
Ind€x ) Button index value.
4 button Name sndNumber Identifies 4th button.
"rJ Caption 4 Text that app€ars on btttton.
Index 3 Button index value.

5 button J Narne mdNtmber Identifies 5th button.


Catrion 5 Text that appears on button.
In&x 4 Button index value.
qrdNurnber Identifies 6th button.
6 button ."Jj Name
Caption 6 Text that appears on button.
Indo( 5 Button index- value.
I button J Narrrc crndlttmber Identifies Lst button.
Text that appears on button.
Caflim 1

Ird€x 6 Button index value.


mdNunber Identifies 2nd button.
2 button ) Name
,
Caplion Text that appears on button.
Ind€x 7 Button index value.
3 button J Name cmdNumber
3
Identifies 3rd button.
Text that appears on button.
Caption
Irdex 8 Button index value.
0 button J Name sndNtlnb€r
0
Identif,res Oth button.
Text that appears on button.
Caption
Index 9 Button index value.
Clear button J Name qndNrmber
Clear
Identifies Clear button.
Text that apPears on button.
Caption
Index 10 Button index value.

Quit button Name cmdQuit Identifies Quit button.


Captitxt Quit Text that appe:trs on button.
This project is developed by using only one form i.e.,fonnl (MathTest.frm). -
The startup object ofthe project is also the form l.

Source Listing of Math Test project

forml (MathTest.frm)

This project is developed by using only one form i.e.,forml(Mathrest.frm).


' Math Test

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

'Check Box/Auto Change Signs


Private Sub chkRandomSign_Cl ick0
If chkRandomsign.Value : I Then
Sample Project - MathTest

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

Private Sub cmdNumber_C I ick(Index As Integer)


Iflndexo l0 Then
txtAnswer.Text : txtAnswer. Text + Trim(Str(cmdNumbe(Index).Capion)
Else
b(Answer.Text: ""
. DisplayMessage "Math Test", 71, 86,220
EndIf
End Sub

'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

Remainder(lblNumberOne.Caption, lbNumberTwo.Caption) Then Exit Sub


End Select
DisplayMessage "Correct", 0, 255, 0
End Sub

'Reset Message and Colors


Private Sub txtAnswer_G otFocus0
txtAnswer.ForeColor : RGB(7, 86,220)
DisplayMessage "Math Test", 7, 86,220
End Sub
F--

Sarnple Proiect - MathT€st

'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

'Disable Command Buttons


Private Function DisableButtons0
cmdCheckAnswer.Enabled : False
ForvntTemp:0To l0
cmdNumber(vntTemp).Enabled : False
NextwtTemp
txtAnswer.Enabled : False
End Function

'Enable Command Buttons


Private Function EnableB uttons0
- cmdCheckAnswer.Enabled:True
ForvntTemp:0To l0
cmdNumber(vntTemp).Enabled : True
Next vntTemp
txtAnswer.Enabled : True
End Function

Private S ub Timer I _Timero


IfblnI.R Then
Forml.Caption :''r + Forml.Caption
Else
Fonnl.Caption : Right$(Forml.Caption, Len(Forml.Caption) - l)
End If
intCounter: intCounter + I
lfintCounter> l5 Then
intCounter:0
IfblnLR: True Then
blnLR: False
Else
blnlR:Tnie
End lf
End If
End Sub
650 Saraswati lnformatics Practices (Xl)

Private Sub cmdQuit_ClickQ


End'Terminate the math project
End Sub

Executing Math Test Project

Run the Math Test using Run >> Start or F5 function key. Thc follo',ving window will appear ;

.!.j,_J

Frorn the abore screen \ou can

D Enter a value at the answer part


O Check the answer using Check button
tr Change the mathematical sign
D Check anwer by clicking Answer button
tr Clear the ans\\'er
C Enter new ans\4'er from the Numeric keys and pre-<s Check button
Appendix A
SQL *Plus Editing Commands

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 *Plus File Gommands

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)

Anda mungkin juga menyukai