Sie sind auf Seite 1von 19

Chapter 3

CHAPTER 3
---------------------------------------------------------------------------------------------------------------------
SINGLE TABLE QUERY BASICS
This chapter focuses on learning to write SELECT statements to retrieve information
from tables. This is termed querying a table, and this chapter covers single-table queries,
meaning that the information retrieved will come from a single database table. s !ou have
probabl! determined b! this point in !our studies, a database can be queried to produce both
small and large quantities of information. Simple queries often tend to produce large quantities
of information in terms of row output, while more comple" queries are capable of e"tracting
specific information from a database. #f a quer! produces a large quantit! of information,
managers who see$ to use the information to aid them in decision ma$ing ma! be overwhelmed
b! the sheer volume of information. %suall!, managers need specific pieces of information to
help them ma$e decisions. #n this chapter, !ou will initiall! learn to write simple queries, and
will progress to increasingl! comple" queries.
OBJECTIVES OBJECTIVES
&ou quer! relational database queries through use of the SELECT statement. Chapter '
introduced the SELECT statement. #n this chapter, !ou will master the basics of the SELECT
statement. &ou will learn to write queries to select both specific rows and specific columns from
a table. &ou will also learn to sort the output in various wa!s. dditionall!, !ou will learn to
avoid some of the common errors that can be made when writing a SELECT statement. The
learning ob(ectives for this chapter are)
*rite simple SELECT statements.
%se the C+L%,- command to format output.
%se the .#ST#-CT clause to eliminate duplicate rows in a result table.
%se the */E0E clause to specif! selection criteria and conditions.
+rder rows with the +0.E0 1& clause.
SIMPLE SELECT STATEMENTS SIMPLE SELECT STATEMENTS
The main element in a S2L quer! is the SELECT statement. properl! written SELECT
statement will alwa!s produce a result in the form of one or more rows of output. The SELECT
statement chooses 3selects4 rows from one or more tables according to specific criteria. #n this
chapter we focus on selecting rows from a single table. S2L E"ample 3.' shows the simplest
form of a quer!.
/* SQL Example 3.1 */
SELECT *
FROM Employee;
EMPLOYEEID SSN LASTNAME FIRSTNAME
!""" #$1!$#%& S'mmo() Le)*e+
333"" $#,"3&&& -o./+ea.x -e0e+ly
333%% $#,"3&$! A/am) A/am
0evised September 5, 6778 3 - '
Chapter 3
more rows and columns will be displayed
This quer! selects rows from the employee table. The asteris$ 394 tells +racle to select
3displa!4 all columns contained in the table employee. The resulting output is termed a result
table. The result table displa!ed in S2L E"ample 3.' onl! lists the first three rows and first four
columns of the result table. The full employee table is described in ppendi" and is part of the
,adison /ospital database. The full result table output will wrap around !our computer screen
because the rows of data are too large to displa! to a single line. dditionall!, !ou will notice
that the LastName, FirstName, and MiddleName columns are quite wide when the! displa! to
!our computer monitor because when the employee table was created, these columns were
defined to be large enough to store the largest last, first, or middle name data values that might
ever occur for an emplo!ee. Later in this chapter, !ou will learn to format the width of result
table columns.
This particular t!pe of quer! uses an asteris$ 394 s!mbol to tell +racle) :;ive me
ever!thing !ou have on emplo!ees. .on<t hold an!thing bac$.: ll rows and all columns are
selected. The SELECT statement in S2L E"ample 3.6 produces an identical result table b!
listing all column names in the employee table.
/* SQL Example 3.& */
SELECT EmployeeID1 SSN1 La)*(ame1 F'+)*Name1 M'//leName1
Depa+*me(*N.m2e+1 O33'4e1 Da*e5'+e/1 T'*le1 6o+7P8o(e1
P8o(eEx*e()'o(1 L'4e().+eN.m2e+1 Sala+y1 6a9eRa*e1 Pa+7'(9Spa4e1 :e(/e+1
S.pe+0')o+ID
FROM Employee;
Clearl!, it is simpler to t!pe the first quer! as opposed to the one given above that lists
each column name individuall!, but !ou would onl! use the asteris$ 394 in a SELECT statement
if !ou wished to displa! all columns in the result table. -ormall!, this is not the case.
-ote that a comma separates each column name. This s!nta" is required. The SELECT
statement also specifies the table name in a =0+, clause. =inall!, the semicolon at the end of
the quer! tells +racle that this is the end of the quer!. &ou ma! wonder about the ordering of the
column names. #t happens that the ordering of column names is immaterial e"cept that the result
table will displa! the columns in the order specified in the SELECT statement. Let<s e"amine the
data stored in the department table. *e<ll begin b! first describing the department table.
/* SQL Example 3.3 */
DESC Depa+*me(*;
Name N.ll Type
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;; ;;;;;;;;;;;;;;;;;
DEPARTMENTN<M-ER NOT N<LL N<M-ER=%>
DEPARTMENTNAME NOT N<LL ?ARC5AR&=&">
MANA:ERID C5AR=">
MANA:ERASSI:NEDDATE DATE
% +o@) )ele4*e/
There are onl! four columns in the department table. These columns store the
department number, department name, department manager<s identif!ing number,, and the date
that each department manager was assigned to the (ob of department manager. The two queries
in S2L E"amples 3.5 and 3.> produce e"actl! the same result table.
/* SQL Example 3.% */
0evised September 5, 6778 3 - 6
Chapter 3
SELECT *
FROM Depa+*me(*;
/* SQL Example 3." */
SELECT Depa+*me(*N.m2e+1 Depa+*me(*Name1 Ma(a9e+ID1 Ma(a9e+A))'9(e/Da*e
FROM Depa+*me(*;
DEPARTMENTN<M-ER DEPARTMENTNAME MANA:ERID MANA:ERASSI:NEDDATE
;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;; ;;;;;;;;;;;;;;;;;;;
1 Me/'4al S.+9'4al 6a+/ 1 &3&3& &1;A<:;#!
& Ra/'olo9y &3&%% 1,;AAN;,1
3 Eme+9e(4y;S.+9'4al 1,,%% 1";SEP;,&
more rows will be displayed

S2L E"ample 3.? is a revision of S2L E"ample 3.> to reorder the columns. The output
in terms of rows is identical, but the ordering of the columns changes to match the ordering in
the SELECT statement.
/* SQL Example 3. */
SELECT Depa+*me(*Name1 Depa+*me(*N.m2e+1 Ma(a9e+A))'9(e/Da*e1 Ma(a9e+ID
FROM Depa+*me(*;
DEPARTMENTNAME DEPARTMENTN<M-ER MANA:ERASSI:NEDDATE MANA:ERID
;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;; ;;;;;;;;;
Me/'4al S.+9'4al 6a+/ 1 1 &1;A<:;#! &3&3&
Ra/'olo9y & 1,;AAN;,1 &3&%%
Eme+9e(4y;S.+9'4al 3 1";SEP;,& 1,,%%
more rows will be displayed
Indenting SQL Code
/ave !ou noticed that we alwa!s start a new line for the =0+, clause in a SELECT statement.
*e have also indented four characters in listing the columns to be displa!ed where the list of
columns is too large to fit within a single line. #t is fairl! common to follow this t!pe of
indentation convention when writing a quer! because it ma$es a quer! easier to read. /owever,
+racle will process a quer! regardless of whether !ou t!pe an entire quer! on one line or indent.
+racle simpl! loo$s for the semicolon mar$ing the end of the quer!. This is because S2L is a
free-form language. This means that there are no rules about how man! words !ou can put on a
line or where !ou brea$ a line. =or e"ample, the S2L statements in S2L E"amples 3.8 and 3.@
are considered e"actl! the same.
/* SQL Example 3.! */
SELECT * FROM Employee;
/* SQL Example 3.$ */
SELECT
*
FROM
Employee;
lthough +racle does not require it, a new line should be started for each clause in a S2L
statement. This will increase maintenance and readabilit!. The following $e!words are !our
signal to start a new line)
0evised September 5, 6778 3 - 3
Chapter 3
SELECT
FROM
65ERE
:RO<P -Y
5A?IN:
ORDER -Y
Selecting Specific Columns
s !ou can see, using asteris$ 394 is a quic$ and eas! wa! to list all column names in a table.
/owever, in da!-to-da! queries !ou will rarel! need to specif! all of the available column names
in a table. #f !ou provided !our boss with all of the columns and rows from a table, the boss
would li$el! tell !ou that !ou were providing too much detailA Let<s suppose that !our boss
wants a listing of onl! emplo!ee identif!ing numbers, last names, and first names. The SELECT
statement to produce this output is shown in S2L E"ample 3.B.
/* SQL Example 3.# */
SELECT EmployeeID1 La)*(ame1 F'+)*Name
EMPLOYEEID LASTNAME FIRSTNAME
;;;;;;;;;; ;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;
!""" S'mmo() Le)*e+
333"" -o./+ea.x -e0e+ly
333%% A/am) A/am
more rows will be displayed
-+TE) Throughout this manual, the rows of a result table produced b! a quer! are
limited to onl! the number of rows needed in order for !ou to understand the quer!. s
!ou e"ecute each quer!, !ou will sometimes see that we have omitted rows of data output
for the purpose of brevit! or clarit!.
To review, the rules for writing a simple SELECT quer! are)
Specif! the column names !ou want displa!ed in the result set b! t!ping the e"act,
complete column names.
Separate each column name with a comma 3,4.
Specif! the name of the table after the =0+, clause.
Terminate the quer! with a semi-colon 3C4.
USING COLUMN COMMANDS TO FORMAT OUTPUT USING COLUMN COMMANDS TO FORMAT OUTPUT
t times !ou will write a quer! where the columnar output will not fit onto a single displa! line.
*hen this happens, the result table will displa! lines that :wrap: around to the ne"t line and the
information will be difficult to read. S2L E"ample 3.'7 produces output that wraps to the ne"t
line.
/* SQL Example 3.1, */
SELECT EmployeeID1 La)*Name1 F'+)*Name1 Da*e5'+e/1 S.pe+0')o+ID
FROM Employee;
EMPLO LASTNAME
;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
0evised September 5, 6778 3 - 5
Chapter 3
FIRSTNAME DATE5IRED S<PER
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;; ;;;;;
!""" S'mmo()
Le)*e+ ,3;MAR;#$
333"" -o./+ea.x
-e0e+ly 1";OCT;,1 !"""
333%% A/am)
A/am &#;AAN;$" 333""
more rows will be displayed
&ou can clean up the result table of such a quer! b! modif!ing the output displa! siDe of
specific columns. This is termed formatting the result table. Column output is formatted with
the C+L%,--=+0,T command. -ote that the +racle S2L .eveloper software does not
support the C+L%,- command within a Sql *or$sheet window.
The e"ample shown below formats the LastName and FirstName columns to restrict their
output to '> characters each. This is significantl! smaller than the >7-character column width
specified for each of these columns in the employee table. This means that emplo!ees with first
or last names larger than '> characters will have all characters after '> wrap to the ne"t line. #f
!ou do not want the output to wrap to the ne"t line, !ou can use the SET *0E +== command
to cause an! characters be!ond '> to simpl! truncate in the displa! of the result table. The
advantage is that each single row of output is displa!ed on a single lineC thereb! improving the
readabilit! of the information as is done in S2L E"ample 3.''.
/* SQL Example 3.11 */
SET 6RAP OFF;
COL<MN EmployeeID FORMAT A1,;
COL<MN La)*Name FORMAT A1";
COL<MN F'+)*Name FORMAT A1";
COL<MN S.pe+0')o+ID FORMAT A1&;
SELECT SSN1 La)*Name1 F'+)*Name1 Da*e5'+e/1 S.pe+0')o+ID
FROM Employee;
SSN LASTNAME FIRSTNAME DATE5IRED S<PER?ISORID
;;;;;;;;; ;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;; ;;;;;;;;; ;;;;;;;;;;;;
#$1!$#%& S'mmo() Le)*e+ ,3;MAR;#$
$#,"3&&& -o./+ea.x -e0e+ly 1";OCT;,1 !"""
$#,"3&$! A/am) A/am &#;AAN;$" 333""
more rows will be displayed
S2L E"ample 3.'' formatted character data. #f !ou are using the +racle S2L .eveloper
software to code statements, the SET *0E +== command will be ignored and column width
formatting will not affect the displa! for the Script +utput window. The width of column output
displa! in the 0esults window of +racle S2L .eveloper is automaticall! ad(usted to the largest
value displa!ed in the column.
&ou can also format the output of numeric columns. 1! default, a numeric column
displa!s with a width equal to the width of the heading. &ou can both increase or decrease the
width of a numeric column displa!ed in a result table. dditionall!, S2L9EL%S displa!s
numbers with as man! digits as necessar! in order to ensure that the numeric value is accuratel!
displa!ed. &ou can set the default width of numeric column displa!s with the SET command.
S2L E"ample 3.'6 sets the -%,*#.T/ parameter to @ characters of output displa! 3the default
value of -%,*#.T/ is normall! '74. &ou should understand that formatting commands such
0evised September 5, 6778 3 - >
Chapter 3
as -%,*#.T/ do not affect the actual table<s structure in an! wa! Fonl! the output displa!ed
in a result table is affected. #f !ou are using the +racle S2L .eveloper software to code
statements, the SET -%,*#.T/ command will be ignored
/* SQL Example 3.1& */
SET N<M6IDT5 $;
Setting the -%,*#.T/ parameter value overrides the width of numeric column
displa!s to ensure that the columnar output is at least -%,*#.T/ digits in widthA *hen using
the C+L%,- command to format numeric data, the placeholders :B: and :7: are used to denote
a position to displa! one digit of output. The placeholder :B: will format numeric output, but
values are not required to be displa!ed. The placeholder :7: also formats numeric output, but
requires output. S2L E"ample 3.'3 shows the use of the :B: placeholder.
/* SQL Example 3.13 */
COL<MN Sala+y FORMAT #####.##;
SELECT Sala+y
FROM Employee;
SALARY
;;;;;;;;;
&&,,,.,,
1!"&,.,,
"",,.,,
more rows will be displayed
#f the Salary is formatted as 77BBBBB.BB, the output displa! changes to reflect that output
is required in the first two-digit locations.
/* SQL Example 3.1% */
COL<MN Sala+y FORMAT ,,#####.##;
SELECT Sala+y
FROM Employee;
SALARY
;;;;;;;;;;;
,,&&,,,.,,
,,1!"&,.,,
,,,"",,.,,
more rows will be displayed
The output displa! is fairl! :plain: and ma! not satisf! managers simpl! because large
numbers are difficult to interpret if the! are not displa!ed in the manner in which managers are
used to seeing them displa!ed. #n this case, managers might prefer that salar! figures be
displa!ed with a dollar sign 3G4 and appropriate comma to separate the thousands and hundreds
digits. This is demonstrated in S2L E"ample 3.'>.
/* SQL Example 3.1" */
COL<MN Sala+y FORMAT B##1###.##;
SELECT Sala+y
FROM Employee;
SALARY
;;;;;;;;;;;
0evised September 5, 6778 3 - ?
Chapter 3
B&&1,,,.,,
B1!1"&,.,,
B"1",,.,,
more rows will be displayed
COMMON ERRORS COMMON ERRORS
lthough S2L is a free-form language, there are still s!ntactical rules that !ou must follow or
!ou will receive an error message instead of the desired result table. The +racle relational
database management s!stem communicates errors in SELECT statements b! providing unique
error numbers and accompan!ing error descriptions. Let<s e"amine some e"ample errors.
Invalid Column Name
The SELECT statement in S2L E"ample 3.'? has the emplo!ee SS- column name
spelled incorrectl!.
/* SQL Example 3.1 */
SELECT So4)e4(o
FROM Employee;
E++o+ )*a+*'(9 a* l'(e & '( 4omma(/C
SELECT So4)e4(o
FROM Employee
E++o+ a* Comma(/ L'(eC& Col.m(C!
E++o+ +epo+*C
SQL E++o+C ORA;,,#,%C DSOCSECNODC '(0al'/ '/e(*'3'e+
,,#,%. ,,,,, ; DE)C '(0al'/ '/e(*'3'e+D
+racle responds b! specif!ing which line has the error. /ere the error is in line 6 where
the emplo!ee SS- column should be SSN, not Socsecno. The +racle error number is +0-
77B75 and the accompan! message is invalid identifier. #f !ou receive this error message, chec$
the spelling of the column name for t!pographical errors.
FROM Keyword Missing
S2L E"ample 3.'8 shows a SELECT statement that is missing the =0+, clause so that no table
name is specified. *ithout a table name, the database management s!stem does not $now which
table to quer!.
/* SQL Example 3.1! */
SELECT SSN;
E++o+ )*a+*'(9 a* l'(e 1 '( 4omma(/C
SELECT SSN
E++o+ a* Comma(/ L'(eC1 Col.m(C1,
E++o+ +epo+*C
SQL E++o+C ORA;,,#&3C FROM 7ey@o+/ (o* 3o.(/ @8e+e expe4*e/
,,#&3. ,,,,, ; DFROM 7ey@o+/ (o* 3o.(/ @8e+e expe4*e/D
0evised September 5, 6778 3 - 8
Chapter 3
n!nown Command " Invalid Command Structure
#n S2L E"ample 3.'@, the order of the SELECT and =0+, clauses is reversed. +racle is ver!
confused b! this command and simpl! returns an un$nown command error message.
/* SQL Example 3.1$ */
FROM Employee SELECT SSN;
SP&;,!3%C .(7(o@( 4omma(/ 2e9'(('(9 DFROM Emplo...D ; +e)* o3 l'(e
'9(o+e/.
#rrors in $lacing Commas
Some t!pes of s!nta" errors cause +racle to return error messages that are not particularl!
helpful in debugging the error. #n S2L E"ample 3.'B, a comma is missing after the LastName
column specification. #nstead of reporting bac$ that there is a s!nta" error or that a comma is
missing, +racle produces a result set that is missing one column of data. t first glance, it
appears that +racle is listing onl! the SS- and first name for each emplo!ee, but a closer
inspection of the output rows reveals that the last name of each emplo!ee is listed, but the
column heading is wrongA +racle did not treat this as an error. #nstead, +racle thought that !ou
onl! wanted two columns of output, and that !ou wanted the second column to have a special
column heading other than the default of LST-,E.
/* SQL Example 3.1# */
SELECT EmployeeID1 La)*Name F'+)*Name
FROM Employee;
EMPLOYEEID FIRSTNAME
;;;;;;;;;; ;;;;;;;;;;;;;;;
!""" S'mmo()
333"" -o./+ea.x
333%% A/am)
more rows will be displayed
There is another possible t!pe of comma placement error and that is placing a comma
after the last column name specified in a SELECT statement as is done in S2L E"ample 3.67. #n
this situation, +racle returns the +0-77B3?) missing e"pression error. This means that +racle
e"pected !ou to provide an additional column specification after the FirstName column.
/* SQL Example 3.&, */
SELECT SSN1 La)*Name1 F'+)*Name1
FROM Employee;
ERROR a* l'(e &C
ORA;,,#3C m'))'(9 exp+e))'o(
THE DISTINCT CLAUSE: ELIMINATING DUPLICATE ROWS THE DISTINCT CLAUSE: ELIMINATING DUPLICATE ROWS
s we learned in Chapter 6, tables are generall! designed with a primar! $e! that guarantees that
each row in a table is unique. Thus, if !ou select all columns from a table, no two rows in the
result table will be duplicates. /owever, if a SELECT statement does not select all columns, it is
0evised September 5, 6778 3 - @
Chapter 3
possible for the result table to contain duplicate rows. This can occur when the SELECT
statement does not select the primar! $e! column3s4 as part of the output.
+racle provides a means for eliminating duplicate rows in a result table through use of
the .#ST#-CT $e!word. The SELECT statement in S2L E"ample 3.6' produces a simple
listing of salaries paid to emplo!ees. The result table contains rows with duplicate valuesF
remember that the Salary column was formatted earlier. close e"amination of the listing will
reveal some duplicate salar! levels.
/* SQL Example 3.&1 */
SELECT Sala+y
FROM Employee
65ERE Sala+y F 1,,,,;
SALARY
;;;;;;;;;;;
B"1",,.,,
B%1"",.,,
B1",,.,,
B%1$,,.,,
B&1&,,.,,
B&1&,,.,,
B%1$#".,,
7 rows selected.
*hen row output is duplicated, it is possible for the duplicate values to obscure the
relevant data that managers see$ to use in ma$ing decisions. The quer! is rewritten in S2L
E"ample 3.66 and uses the .#ST#-CT $e!word to eliminate duplicate rows. *hen the
.#ST#-CT $e!word is used, the output ordering of rows usuall! change unless the rows are
e"plicitl! sorted with the +0.E0 1& clause. .o not worr! about row order for now as !ou will
learn to control row output ordering later in this chapter.
/* SQL Example 3.&& */
SELECT DISTINCT Sala+y
FROM Employee
65ERE Sala+y F 1,,,,;

SALARY
;;;;;;;;;;;
B&1&,,.,,
B%1"",.,,
B%1$,,.,,
B%1$#".,,
B"1",,.,,
B1",,.,,
+o@) )ele4*e/.
The .#ST#-CT $e!word must immediatel! follow the SELECT $e!word and is not
separated from the first column name with a comma. #f !ou mista$enl! place the .#ST#-CT
$e!word other than immediatel! following the SELECT statement, the quer! will generate the
+0-77B63) =0+, $e!word not found where e"pected error message as is shown in S2L
E"ample 3.63.
0evised September 5, 6778 3 - B
Chapter 3
/* SQL Example 3.&3 */
SELECT Sala+y DISTINCT
FROM Employee
65ERE Sala+y F 1,,,,;

ERROR a* l'(e 1C
ORA;,,#&3C FROM 7ey@o+/ (o* 3o.(/ @8e+e expe4*e/
The .#ST#-CT $e!word also eliminates duplicate rows where more than one column is
displa!ed in the result table. S2L E"ample 3.65 shows a quer! of the bed table for the ,adison
/ospital database . -ote the duplicate rows highlighted in bold te"t. The quer! selects a total of
B7 rows.
/* SQL Example 3.&% */
COL<MN RoomN.m2e+ FORMAT A1,;
COL<MN -e/Type FORMAT A11;
SELECT RoomN.m2e+1 -e/Type
FROM -e/;
ROOMN<M-ER -EDTYPE
;;;;;;;;;; ;;;;;;;;;;;
MSS,,1 R1
MSS,,& R1
MSS,,3 R&
MSS,,% R1
MSS,," R&
MSS,, R1
MSS,1, R1
MSS,1, R&
MSS011 R2
MSS011 R2
more rows will be displayed
The .#ST#-CT clause eliminates duplicate row output as shown in S2L E"ample 3.6>.
This quer! onl! selects 85 rows. Si"teen duplicate rows were eliminated.
/* SQL Example 3.&" */
SELECT DISTINCT RoomN.m2e+1 -e/Type
FROM -e/;
ROOMN<M-ER -EDTYPE
;;;;;;;;;; ;;;;;;;;;;;
MSS,,1 R1
MSS,,& R1
MSS,,3 R&
MSS,,% R1
MSS,," R&
MSS,, R1
MSS,1, R1
MSS,1, R&
MSS011 R2
more rows will be displayed
0evised September 5, 6778 3 - '7
Chapter 3
SELECTING ROWS: THE WHERE CLAUSE SELECTING ROWS: THE WHERE CLAUSE
&ou have learned how to displa! specific columns from a table, as well as how to reduce the
number of rows displa!ed through use of the .#ST#-CT $e!word. s !ou ma! recall from
Chapter ', displa!ing specific columns from a table is $nown as a project operation. *e will
now focus on displa!ing specific rows of output. This is $nown as a select operation.
Specific rows can be selected b! adding a */E0E clause to a SELECT quer!. Suppose
that !our boss is wor$ing on the quarterl! budget for !our organiDation. s part of this activit!,
it is necessar! to produce a listing of each emplo!ee<s SS-, last name, first name, and salar!, but
onl! for emplo!ees that are paid at least G6>,777 annuall!. S2L E"ample 3.6? accomplishes this
tas$. -ote the use of the */E0E clause shown in bold te"t.
/* SQL Example 3.& */
COL<MN La)*Name FORMAT A1";
COL<MN F'+)*Name FORMAT A1";
SELECT EmployeeID1 La)*Name1 F'+)*Name1 Sala+y
FROM Employee
WHERE Salary >= 25000;
EMPLOYEEID LASTNAME FIRSTNAME SALARY
;;;;;;;;;; ;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;; ;;;;;;;;;;;
$$3,3 Ao(e) Q.'(4ey B3,1"",.,,
$$%,% -a+lo@ 6'll'am B&!1",,.,,
$$"," Sm'*8 S.)a( B3&1",,.,,
3 rows selected
s !ou can see, the result table contains onl! rows where the condition 3salar! HI 6>7774
is met. =urther, the dollar sign 3G4 and comma 3,4 are not used in specif!ing the numeric value
for the emplo!ee salar! in the */E0E clause. #n this e"ample, we used the greater-than-or-
equal-to operator 3HI4 equal. &ou could (ust as easil! request a list of emplo!ees that are paid
less than or equal to G'>,777 or an! other value for emplo!ee salar! as is done in S2L E"ample
3.68.
/* SQL Example 3.&! */
SELECT EmployeeID1 La)*Name1 F'+)*Name1 Sala+y
FROM Employee
65ERE Sala+y F 1",,,;
EMPLOYEEID LASTNAME FIRSTNAME SALARY
;;;;;;;;;; ;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;; ;;;;;;;;;;;
333%% A/am) A/am B"1",,.,,
$$!!! Sm'*8 Aly))a B%1"",.,,
%%% G.m@al* Ma+y B1",,.,,
more rows will be displayed
Comparison Operators
#n all, +racle has nine different comparison operators. These are listed in Table 3.'.
Table 3!
Operator Meaning
0evised September 5, 6778 3 - ''
Chapter 3
I equal to
J less than
H greater than
HI greater than or equal to
JI less than or equal to
AI not equal to
JH not equal to
AH not greater than
AJ not less than
Comparing C%aracter &ata
The use of comparison operators is not limited to numeric data. The! can also be used with
columns that store character data. *hen comparing C/0 and K0C/06 data, the less than
operator 3J4 means earlier in the alphabet 3 comes before 14, while the greater than operator
3H4 means later in the alphabet 3L comes after &4.
*hen !ou use comparison operators in a */E0E clause, the arguments 3ob(ects or
values !ou are comparing4 on both sides of the operator must be either a column name, or a
specific value. #f a specific value is used, then the value must be either a numeric value or a
literal string. #f the value is a character string or date, !ou must enter the value within single
quotation marks 3< <4. n e"ample will clarif! this requirement.
Suppose !our manager wants a listing of the emplo!ee identifier, last name, and first
name for all male emplo!ees. The SELECT quer! requires a */E0E clause that selects rows
based on the emplo!ee gender 3Gender4 column. The Gender column stores coded data wherein
, I male and = I female emplo!ees. S2L E"ample 3.6@ shows a SELECT statement with the
correct */E0E clause.
/* SQL Example 3.&$ */
COL<MN EmployeeID FORMAT A1,;
COL<MN La)*Name FORMAT A1";
COL<MN F'+)*Name FORMAT A1";
SELECT EmployeeID1 La)*Name1 F'+)*Name
FROM Employee
65ERE :e(/e+ H IMI;
EMPLOYEEID LASTNAME FIRSTNAME
;;;;;;;;;; ;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;
!""" S'mmo() Le)*e+
333%% A/am) A/am
333"$ T8o+(*o( -'lly
more rows will be displayed
-ote that the Gender column does not have to be specified in the listing of columns
selected for displa! in the result table in order to use the column name in the */E0E clause.
-ow let<s see what happens if !ou ma$e a mista$e and fail to enclose the emplo!ee gender code
within single quotation mar$s.
/* SQL Example 3.&# */
SELECT EmployeeID1 La)*Name1 F'+)*Name
FROM Employee
65ERE :e(/e+ H M;
0evised September 5, 6778 3 - '6
Chapter 3
ERROR a* l'(e 3C
ORA;,,#,%C DMDC '(0al'/ '/e(*'3'e+
+racle returns error +0-77B75) invalid identifier. *hile this error message does not
tell !ou e"actl! what !ou did wrong, it does identif! the line that has the error 3line 3 above4.
0ecall our earlier rule about the arguments in a */E0E clause. Since the literal string value
was not enclosed b! single quote mar$s, +racle assumed the letter , to be a column name. +f
course, there is no column named , in the employee table so an error is returned. So, when !ou
see this error with a reference to a line associated with a */E0E clause, !ou need to determine
whether or not the column referenced b! the */E0E clause stores character data.
&ou can also write SELECT statements that use operators other than the equal sign. =or
e"ample, suppose !our manager needs a listing of emplo!ees that have a first name that begins
with the letter :M,: or that begins with a letter that occurs later in the alphabet than the letter :M.:
S2L E"ample 3.37 shows the appropriate */E0E clause.
/* SQL Example 3.3, */
SELECT La)*Name1 F'+)*Name
FROM Employee
65ERE La)*Name JH IAI;
LASTNAME FIRSTNAME
;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;
S'mmo() Le)*e+
T8o+(*o( -'lly
6e22e+ E.9e(e
Sm'*8 Aly))a
more rows will be displayed
ORDERING ROWS: THE ORDER BY CLAUSE ORDERING ROWS: THE ORDER BY CLAUSE
-ormall!, when rows are added to a table the! are appended to the end of the table. This
produces a table containing unordered rows. This is clear when e"amining the result table for
S2L E"ample 3.37C the rows are not in alphabetic order.
*hen !ou displa! onl! a few rows of data, it ma! be unnecessar! to sort the outputC
however, when !ou displa! numerous rows, managers ma! be aided in decision ma$ing b!
having the information sorted. +utput from a SELECT statement can be sorted b! using the
optional +0.E0 1& clause. *hen !ou use the +0.E0 1& clause, the column name on which
!ou are ordering must also be a column name that is specified in the SELECT clause.
The quer! from S2L E"ample 3.37 is e"panded in S2L E"ample 3.3' to add an +0.E0
1& clause that sorts the result table b! the LastName column in ascending order. scending
order is the default sort order.
/* SQL Example 3.31 */
SELECT La)*Name1 F'+)*Name
FROM Employee
65ERE La)*Name JH IAI
ORDER -Y La)*Name;
LASTNAME FIRSTNAME
;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;
Ao(e) Q.'(4ey
Kleppe+ Ro2e+*
0evised September 5, 6778 3 - '3
Chapter 3
Q.a**+oma(' To('
S48.l*8e') Ro2e+*
more rows will be displayed

&ou can also sort data based on numeric column values. S2L E"ample 3.36 sorts
emplo!ees based on their monthl! salar!.
/* SQL Example 3.3& */
SELECT La)*Name1 F'+)*Name1 Sala+y
FROM Employee
65ERE Sala+y J &",,,
ORDER -Y Sala+y;
LASTNAME FIRSTNAME SALARY
;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;; ;;;;;;;;;;
-a+lo@ 6'll'am &!",,
Ao(e) Q.'(4ey 3,"",
Sm'*8 S.)a( 3&",,
Sort Order
#t is fairl! intuitive that numeric columns will sort b! default from smallest to largest values. 1ut
what about sorting character dataN Character data sorts are language dependent. The parameter
-LSOL-;%;E is set to support a specific national language when a database is created, for
e"ample -LSOL-;%;E I E-;L#S/. The -LSOL-;%;E can be e"plicitl! modified
for sort operations, but this is be!ond the scope of this boo$.
Table 3.6 displa!s the sort order that +racle uses when sorting English language and
special characters. The sort order here is based on the SC## character coding scheme. Lower
case letters come after upper case letters in the sort order. +racle converts the SC## character
codes to he"adecimal equivalents when sorting.
Table 3"
C%aracters' in (SCII Order
L D M B E N I = > * O 1 ; . / , 1 & 3 % " ! $ # C ; F H J P Q
A - C D E F : 5 I A K L M N O P Q R S T < ? 6 R Y G S T U V W X
a 2 4 / e 3 9 8 ' Y 7 l m ( o p Z + ) * . 0 @ x y [ \ ] ^ _ 
OR&#R )* wit% (SC and &#SC Options
1! default, the +0.E0 1& clause will sort output rows in the result table in ascending
order. /owever, there are situations when !ou will need to displa! the results in descending
order. Let<s rewrite S2L E"ample 3.36 to displa! the rows in reverse-salar! order, that is,
highest salaries first. *e will use the $e!word .ESC 3short for descending4 to force this
descending sort. The alternative default is SC which sorts in ascending order, but the SC
$e!word is rarel! used since it is the default.
*hen the SC or .ESC optional $e!word is used, it must follow the column name on
which !ou are sorting in the */E0E clause. S2L E"ample 3.33 demonstrates the .ESC
$e!word.
0evised September 5, 6778 3 - '5
Chapter 3
/* SQL Example 3.33 */
SELECT La)*Name1 F'+)*Name1 Sala+y
FROM Employee
65ERE Sala+y J &",,,
ORDER -Y Sala+y DESC;
LASTNAME FIRSTNAME SALARY
;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;; ;;;;;;;;;;
Sm'*8 S.)a( 3&",,
Ao(e) Q.'(4ey 3,"",
-a+lo@ 6'll'am &!",,
S2L E"ample 3.35 shows what happens when !ou misplace the .ESC $e!word. /ere
the .ESC is placed before Salary and the resulting error message is +0-77B3?) missing
e"pression.
/* SQL Example 3.3% */
SELECT La)*Name1 F'+)*Name1 Sala+y
FROM Employee
65ERE Sala+y J &",,,
ORDER -Y DESC Sala+y;
ERROR a* l'(e %C
ORA;,,#3C m'))'(9 exp+e))'o(
OR&#R )* wit% More +%an One Column
Thus far, !ou have learned how to sort output to a result table based upon a single columnC
however, there are occasions wherein it is necessar! to sort data based on more than one column.
Sorting b! multiple columns can improve the loo$ and usabilit! of information. s !our boss
learns more about the information !ou can e"tract from the compan! database, the demands on
!our s$ills increase. The latest request is for a listing of emplo!ees sorted alphabeticall! within
department. #n order to meet this request for information, !ou ma! wish to stud! the employee
table description provided in ppendi" or use the .ESC0#1E command within S2L9EL%S to
e"amine the structure of the employee table. #n addition to storing emplo!ee identif!ing
numbers, social securit! numbers, and name information, !ou note that each row has a column
named epartmentNumber. The values stored in this column are the department number to
which emplo!ees are assigned.
The t!pe of output desired b! !our manager involves a sort within a sort. *e will define
the epartmentNumber column as the ma(or sort column. The LastName column will serve as
the minor sort column. *e shall sort emplo!ees b! name within department b! listing the ma(or
sort column first in the +0.E0 1& clause, followed b! the minor sort column.
-ote that the result shown in S2L E"ample 3.3> lists emplo!ees sorted b! department
number first. *ithin each department, emplo!ees are sorted b! last name.
/* SQL Example 3.3" */
SELECT Depa+*me(*N.m2e+1 La)*Name1 F'+)*Name
FROM Employee
ORDER -Y Depa+*me(*N.m2e+1 La)*Name;
DEPARTMENTN<M-ER LASTNAME FIRSTNAME
;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;
0evised September 5, 6778 3 - '>
Chapter 3
1 -o47 Do.9la)
1 Ea7'( Max@ell
& -o+/olo' -'Yoy
& Sm'*8 Aly))a
& 6e22e+ E.9e(e
3 -a+lo@ 6'll'am
3 -e47e+ Ro2e+*
3 Ao(e) Q.'(4ey
3 Sm'*8 S.)a(
3 S.m(e+ El'[a2e*8
% Kleppe+ Ro2e+*
% G.m@al* Ma+y
" Q.a**+oma(' To('
-e47e+ Ro2e+*a
-+o47@ell Ma+y Elle(
S'mmo() Le)l'e
Yo.(9 Y0o((e
! -o./+ea.x -e**y
$ A/am) A/am
$ -o./+ea.x -e0e+ly
$ Cl'(*o( 6'll'am
$ S'mmo() Le)*e+
$ T8o+(*o( -'lly
# S48.l*8e') Ro2e+*
24 rows selected
&ou can combine both ascending and descending sort variables within a single +0.E0
1& clause. Suppose that !ou wish to displa! the data shown above, but sort the departments in
descending order while maintaining the emplo!ee names in ascending order b! last name. S2L
E"ample 3.3? shows the correct quer!.
/* SQL Example 3.3 */
SELECT Depa+*me(*N.m2e+1 La)*Name1 F'+)*Name
FROM Employee
ORDER -Y Depa+*me(*N.m2e+ DESC1 La)*Name;
DEPARTMENTN<M-ER LASTNAME FIRSTNAME
;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;
# S48.l*8e') Ro2e+*
$ A/am) A/am
$ -o./+ea.x -e0e+ly
$ Cl'(*o( 6'll'am
$ S'mmo() Le)*e+
$ T8o+(*o( -'lly
! -o./+ea.x -e**y
-e47e+ Ro2e+*a
-+o47@ell Ma+y Elle(
S'mmo() Le)l'e
Yo.(9 Y0o((e
" Q.a**+oma(' To('
% Kleppe+ Ro2e+*
% G.m@al* Ma+y
3 -a+lo@ 6'll'am
3 -e47e+ Ro2e+*
3 Ao(e) Q.'(4ey
3 Sm'*8 S.)a(
0evised September 5, 6778 3 - '?
Chapter 3
3 S.m(e+ El'[a2e*8
& -o+/olo' -'Yoy
& Sm'*8 Aly))a
& 6e22e+ E.9e(e
1 -o47 Do.9la)
1 Ea7'( Max@ell
24 rows selected
-ote that the department numbers are now in descending order, but within each
department, the emplo!ee names are still displa!ed in alphabetic order b! last name. #n
summar!, the +0.E0 1& clause is a powerful tool for improving the usabilit! of an! result
table listing, and it is eas! to use with ver! few rules.
&ou can include a ma"imum of '? column names in the +0.E0 1& clause.
&ou must separate column names within the +0.E0 1& clause with a comma 3,4 in
order to avoid s!nta" error messages.
SUMMARY SUMMARY
#n this chapter, we e"plored the power of simple SELECT statements. &ou learned to select
specific rows and columns from individual tables b! specif!ing column names to be displa!ed,
and b! using the */E0E clause to specif! conditions for displa!ing rows. dditionall!, !ou
learned to sort the information displa!ed b! using the +0.E0 1& clause. fter completing the
e"ercises at the end of this chapter !ou should feel comfortable e"ecuting simple queries.
REVIEW E#ERCISES REVIEW E#ERCISES
Learn +%ese +erms
'. S#L#C+Fthe S2L statement used to quer! a database.
6. FROM,the SELECT statement clause used to specif! the table3s4 from which data are to be
retrieved.
3. COLMN-FORM(+Fa statement used to format columnar output in order to restrict the
number of characters of output assigned to specific columns.
5. &IS+INC+Fa $e!word used as means for eliminating duplicate rows in a result table.
>. ./#R#Fa clause in a quer! used to specif! conditions for selecting rows to be displa!ed in
the result table.
?. Comparison operator,operators used in */E0E clauses that are used to specif!
conditions for selecting rows. There are nine operators with means such as :equal to,:less
than,: and :greater than,: as well as others.
8. OR&#R )*Fa clause used to sort the displa! of rows in a result table. The column name
on which !ou are sorting must be specified in the SELECT clause.
@. (SCFa $e!word used to specif! that the +0.E0 1& is in ascending order. This is the
default.
B. &#SCFa $e!word used to specif! that the +0.E0 1& is in descending order.
Concepts Qui0
'. E"plain what the asteris$ 394 means when used in a SELECT statement.
0evised September 5, 6778 3 - '8
Chapter 3
6. *hich clause is used to specif! the name of a table from which data are to be retrievedN
3. *hat can !ou do to create a result table that has columns ordered in a specific sequence or
orderingN
5. *hat special s!nta" is used to mar$ the end of a SELECT quer!N
>. *h! is a new line started for each clause in a S2L statementN
?. *hat does the following statement doN
COL<MN La)*Name FORMAT A1&;
8. *hat does the SET *0E +== command doN
@. *hat is the default width of a numeric column in a result tableN
B. *hich command is used to set the width of numeric column displa!sN
'7. *hat is the default value of -%,*#.T/N
''. #f the =+0,T for a numeric column is =+0,T GBB,BB7.77, what will be displa!ed if the
value for the column for a specific table row is -%LLN
'6. *hat error message is returned b! the +racle relational .1,S when a SELECT statement
specifies a column name that does not e"ist within the table that is being queriedN
'3. /ow does the +racle relational .1,S respond if the order of the SELECT and =0+,
clauses in a quer! is reversedN
'5. /ow does the +racle relational .1,S respond if !our quer! is missing a comma between
two column namesN
'>. *hat is the purpose of the .#ST#-CT $e!word in a quer!N
'?. *here is the .#ST#-CT $e!word placed in a quer!N
'8. *hat is the purpose of the */E0E clause in a quer!N
'@. List the nine comparison operators and their meaning.
'B. *hen comparing column values that are character data, what does the less than operator 3J4
meanN
67. #f !ou are comparing a column value that is character to a literal string, what s!nta" is used
to specif! the literal string of charactersN
6'. *hat is the purpose of the +0.E0 1& clauseN
66. /ow is the sort order for an +0.E0 1& clause determined when sorting b! a character
columnN
63. *hat is the optional $e!word used to specif! descending order for an +0.E0 1& clauseN
65. manager wants a result table sorted b! two columns, department number
3epartmentNumber4 and emplo!ee last name 3LastName4 within the department number.
*hich column is the ma(or sort column and which one is the minor sort column, and how is
this denoted in the +0.E0 1& clauseN
SQL Coding #1ercises and Questions
#n answering the S2L e"ercises and questions, submit a cop! of each command that !ou
e"ecute and an! messages that +racle generates while e"ecuting !our S2L commands. lso list
the output for an! result table that is generated b! !our S2L statements.
'. &our manager wants a listing that will displa! all of the data from the project!ssignment
table. *rite the quer!. &ou ma! wish to use the .ESC0#1E command to e"amine the
structure of the project!ssignment table.
6. *rite a quer! that will select all columns from the project!ssignment table without using the
394 in !our quer!.
0evised September 5, 6778 3 - '@
Chapter 3
3. &our manager wants the listing that !ou created for question 6 modified. The quer! should
list onl! the "mployee# and $ours%orked 3hours wor$ed on a pro(ect4 in the result table.
5. 0ewrite the quer! from question 3, but reverse the order in which the two columns are
displa!ed. .ispla! $ours%orked first and "mployee# second.
>. &our manager requires a listing of patients from the organiDation<s patient table in order to
meet the reporting requirements for a government agenc!. The listing must include each
patient<s last name 3LastName4, first name 3FirstName4, date of birth 3&irthate4 and assigned
bed number 3&edNo4. *rite the quer! to displa! the output sorted b! &irthate.
?. The last quer! caused the result table to displa! with rows wrapped because each line was too
long to fit onto a single line of output. %se the appropriate command to limit the output
column width for the patient last and first names to '> characters. E"ecute the quer! to
displa! the new result table.
8. ,anagement has requested a listing that includes information from the employee table. The
listing should include the "mployee#, LastName, FirstName, and Gender columns. The data
must be sorted first b! emplo!ee gender 3ma(or sort column is Gender4 and then b! emplo!ee
last name within gender 3minor sort column is LastName4. s such, the! want the Gender
column to be displa!ed first, followed b! the remainder of the columns. The column widths
for the emplo!ee last and first names should be '> characters.
@. &our boss<s boss is concerned about emplo!ee dependents. &our manager directs !ou to
prepare a listing of data from the dependent table. The listing should include dependent
names 3Name4, dates of birth 3&irthate4, and the relationship to emplo!ees
3'elationship(o"mployee4 from the dependent table. The first column displa!ed should be
the emplo!ee<s identif!ing number 3"mployee#4. Sort the output b! "mployee# 3ma(or sort
column4 and b! Name 3minor sort column4. The Name column should displa! no more than
67 characters of output.
B. Eroduce a second listing to that will onl! displa! emplo!ee dependents that are children 3the
value of the 'elationship(o"mployee column is either S+- or .%;/TE0, but not
SE+%SE4. The result table should displa! the "mployee#, Name, and
'elationship(o"mployee columns, and be sorted b! "mployee# in descending order. .o
-+T use a logical operator in writing the quer!.
'7. &our manager wonders what t!pes of dependent relationships are trac$ed within the
dependent table. Eroduce a simple listing of the 'elationship(o"mployee column that does
not contain duplicate output rows.
''. &our manager is concerned about the cost of hospital equipment. %sing the equipment table,
produce a listing that includes the "quipmentNumber, escription, and )riginal*ost where
the cost is greater than G',777.77. Sort the output in descending order b! )riginal*ost.
'6. .ata about services that can be provided to patients are stored in the ser+ice table.
,anagement needs a listing that includes the Ser+ice#, escription, and Standard*harge for
an! service where the standard charge is G>,777.77 or more. The output should be sorted
from most e"pensive to least e"pensive service.
'3. =rom the ser+ice table list the categories of services offered 3*ategory#4 without listing
an! duplicates. The result table for this quer! is a single column.
'5. ,anagement is concerned about prescriptions issued for medicine that falls within a specific
medicine code categor!. %sing the prescription table, list the medicines that have been
prescribed that fall within the medicine code value BBBB7'6. The listing should include
,rescriptionNumber, ,atient#, and Medicine*ode columns.
'>. ,odif! the quer! for question P'5 to sort the result table rows b! the ,atient# column.
0evised September 5, 6778 3 - 'B

Das könnte Ihnen auch gefallen