Basics QL Statements
Basics QL Statements
Writing Basic
SQL Statements
1
Objectives
After completing this lesson, you shoul be able to o the
follo!ing"
List the capabilities of SQL S#L#C$ statements
#%ecute a basic S#L#C$ statement
&ifferentiate bet!een SQL statements an SQL'(lus
commans
Lesson Aim
To extract data from the database. you need to use the structured query
language (SQL) SELECT statement You may need to restrict the columns
that are dislayed. This lesson describes all !he SQL statements that you need
to erform these actions.
You may "ant to create SELECT statements that can be used time and time
again. Tins lesson also co#ers the use of SQL$%lus commands to execute
SQL statements
2
Capabilities of SQL S#L#C$
Statements
Selection Projection
Table
1
Table
2
Capabilities of SQL SELECT Statements
& SELECT statement retrie#es information from the database. 'sing a
SELECT statement( you can do the follo"ing)
Selection) You can use the selection caability in SQL to choose the ro"s in
a table that you "ant returned by a query. You can use #arious criteria to
selecti#ely restrict the ro"s that you see.
%ro*ection) You can use the ro*ection caability in SQL to choose the
columns in a table that you "ant returned by your query. You can choose as
fe" or as many columns of the table as you require.
+oin) You can use the *oin caability in SQL to bring together data that is
stored in different tables by creating a lin, through a column that both the
tables share. You "ill learn more about *oins in a later lesson.
3
Basic S#L#C$ Statement
SELECT [DISTINCT] {! col"mn [alias]!##!$
%&'( table;
S#L#C$ ientifies what columns)
*+O, ientifies which table)
)asic SELECT Statement
!n its simlest form( a SELECT statement must include the follo"ing
& SELECT clause( "hich secifies the columns to be dislayed.
A FROM clause, "hich secifies the table containing the columns
listed in the SELECT clause.
!n the syntax)
SELECT is a list of one or more columns.
-!ST!.CT suresses dulicates.
$ selects all columns
column selects the named column.
alias gi#es selected columns different headings.
FROM table secifies the table containing the columns.
Note: Throughout this course( the "ords ,ey"ord( clause( and statement are
used.
& keyword refers to an indi#idual SQL element. /or examle( SELECT and
FROM are ,ey"ords.
& clause is a art of an SQL statement. /or examle. SELECT empno,
ename, is a clause.
& statement is a combination of t"o or more clauses. /or examle. SELECT
* FROM emp is a SQL statement.
1 *o:s selecte#.
/uplicate Ro:s
'nless you indicate other"ise. SQL$%lus dislays die results of a query "ithout
eliminating dulicate ro"s. The examle on the slide dislays all the deartment
numbers from the E9% table. .otice that the deartment numbers are reeated.
2"
#liminating &uplicate +o!s
#liminate uplicate ro!s by using the &BS$B/C$ 7ey!or in the S#L#C$
clause,
SELECT DISTINCT .e-tno
%&'( em-/
DEPTNO
6;
<;
=;
D"-licate &o,s 9contin"e.:
To eliminate dulicate ro"s in the result( include the -!ST!.CT ,ey"ord m
the SELECT clause immediately after the SELECT ,ey"ord. !n the examle
on the slide( the E9% table actually contains fourteen ro"s but there are only
three unique deartment numbers in the table.
You can secify multile columns after the -!ST!.CT qualifier. The
-!ST!.CT qualifier affects all the selected columns( and the result reresents
a distinct combination of the columns
SELECT DISTINCT .e-tno! job
%&'( em-/
DEPTNO JOB
<; CLE40
6; S&LES9&.
<; 9&.&BE4
6; CLE40
=; %4ES!-E.T
6; 9&.&BE4
=; CLE40
=; 9&.&BE4
<; &.&LYST
8 ro"s selected.
2%
SQL an SQL'(lus
Bnteraction
SQL an. SQLPl"s
SOL is a command language for communication "ith the 3racle Ser#er from
any tool or alication. 3racle SQL contains many extensions. 2hen you
enter a SQL statement( it is stored in a art of memory called the SOL buffer
and remains there until you enter a ne" statement.
SOL*Plus is an 3racle tool that recogniHes and submits SQL statements to
the 3racle Ser#er or for cxecution and contains its o"n command language.
S:L&P)u+
Se!;e!
SQLPL7S
Comman.s
Q"er3
&es"lts
%ormatte.
&e-ort
2&
SQL
Statements
)"ffer SQL
Statements
%ormatte.
'"t-"t
7e"tu!e+ o< S:L
Can be used by a range of users( including those "ith little or no
rogramming exerience.
!s a nonrocedural language.
4educes the amount of time required for creating and maintaining
systems.
!s an EnglishDli,e language.
/eatures of SQLK%lus
&ccets ad hoc entry of statements
&ccets SQL inut from files
%ro#ides a line editor for modifying SQL statements
Controls en#ironmental settings
/ormats query results into a basic reort.
&ccesses local and remote databases
2'
SQL Statements <ersus
SQL'(lus Commans
SQL
SQLPl"s
& language &n en#ironment
&.S! standard 3racle rorietary
0ey"ord cannot be abbre#iated 0ey"ords can be abbre#iated
Statements maniulate data and table
definitions in the database
Commands do not allo" maniulation of
#alues in the databasese
SQL an. SQLPl"s
9contin"e.:
The follo"ing table comares SQL and SQL$%lus)
SQL SQLPl"s
!s a language for communicating Ser#er to
access data
4ecogniHes the ser#er
!s the 3racle
!s entered one line at a time) not stored in
the SQL buffer
3(
Overvie! of SQL'(lus
Log in to SQL'(lus)
&escribe the table structure)
#it your SQL statement)
#%ecute SQL from SQL'(lus)
Save SQL statements to files an
appen SQL statements to files)
#%ecute save files)
Loa commans from file to buffer to eit)
SQL=Pl"s
SQL$%lus is ail en#ironment tn TThich you can do the follo"ing)
Execute SQL statements to retrie#e( modify( add. and remo#e data from
the database /ormat( erform calculations on. store( and rint query
results in the form of reorts Create scrit files to store SQL statements
for reetitue use in the future
SQL$%lus commands can be di#ided into the follouing main categories.
C"tego!1 Pu!o+e
En#ironment &ffects the general beha#ior of SQL statements for the session
/ormat /ormats query results
/ile maniulation Sa#es( loads( and runs scrit files
Execution Sends SQL statements from SQL buffer to 3racieS Ser#er
Edit 9odifies SQL statements in the buffer
!nteraction &l,ms you to create and ass #ariables to SQL statements(
rint #ariable #alues( and rint messages to the screen
9iscellaneous :as #arious commands to connect to the database( maniulate
the SQL$%lus en#ironment( and dislay column definitions
31
&isplaying $able Structure
1se the SQL'(lus &#SC+BB# comman to isplay the structure
of a table)
-ESCU4!CEV tablename
&isplaying T"'l$ S%.u0%u.$
!n SQL$%lus( you can dislay The structure of a table using the
-ESC4!CE command. The result of the command is to see the column
names and datatyes as "ell as "hether a column must contain data.
!n the syntax)
tablename is the name of any existing table( #ie"( or synonym
accessible to the user.
DESC em- /
/ame /ullG $ype
EMPNO NOT NULL NUMBER849
ENAME :ARCHAR28109
;OB :ARCHAR28<9
MGR NUMBER849
HIREDATE DATE
SAL NUMBER8=(29
COMM NUMBER8=(29
DEPTNO NUMBER829
DESC .e-t/
/ame /ullG $ype
DEPTNO NUMBER829
DNAME :ARCHAR28149
LOC :ARCHAR28139
DESC sal+ra.e /
/ame /ullG $ype
GRADE NUMBER
LOSAL NUMBER
HISAL NUMBER
32
&isplaying $able Structure
D!/l"5n) $able S%.u0%u.$ 80,n%nu$*9
The examle on the slide dislays the information about the structure of the
-E%T table. !n the result)
Null? indicates "hether a column must contain data) .3T .'LL
indicates that a column must contain data
Type dislays the datatye for a column
The datatyes are described m the follo"ing table)
D"t"t1e De+c!ition
N=MBER'>+(
.umber #alue ha#ing a maximum number
of digits ( the number of digits to the
right of the decimal oint s
*ARCHAR%'+(
WariableDlength character #alue of
maximum siHe s
DATE
-ate and time #alue bet"een +anuary =.
@5=< C.C. and -ecember 6=.8888 &.-
CHAR'+(
/ixedDlength character #alue of siHe s
De+c!ition
33
SQL'(lus #iting Commans
AH((#/&I text
CH0A/J#I 5ol 5ne!
CH0A/J#I te%t
CLH#A+I B1**H#+I
&#L
&#Ln
&#L m n
SQL=Pl"s E#itin9 Comman#s
SQLTlus commands arc entered one line at a time and are not stored in the
SQL buffer.
Command -escrition
&U%%E.-V tet &dds text to the end of the current line
CU:&.BEV>ci>e>>X"9D Changes old text to mK" in the current line
CU:&.BEV>text > -eletes tet from the current line
CLUE&4V C'//UE4V -eletes all lines from the SQL buffer
-EL -eletes current line
Buidelines
!f you ress U4eturnV before comleting a command. SQL$%lus
romts you "ith a line number.
You terminate the SQL buffer by either entering one of the terminator
characters (semicolon or slash) or ressing U4eturnV t"ice. You then
see the SQL romt.
+nt*o#uction to 'racle> SQL an. PL?SQL 12@8
3
SQLPl"s E.itin+ Comman.s
I[NP7T]
I[NP7T] text
L[IST]
L[IST] n
L[IST] m n
&[7N]
n
n text
8 text
SQLPl"s E.itin+ Comman.s 9contin"e.:
Command -escrition
!U.%' TV !nserts an indefinite number of lines
!U.%'TV tet !nserts a line consisting of rf.#r
!.U!STV Lists all lines in the S3L buffer
LU!STV n Lists one line (secified b# n!
LU!STV m n Lists a ranae of lines "m to n!
4U'.l -isla#s and runs the current SQL statement m the buffer
n Secifies the line to ma,e the current line
n tet 4elaces line n "ith tet
; tet !nserts a line before line =
You can enter onh one SQL$%!us command er SQL romt.
SQL$%lus commands are not stored in the buffer To continue a
SQL$%lus command on the next line( end the current line "ith a
hyhen (D).
3!
SQLPl"s %ile Comman.s
SA;E filename
AET filename
STA&T filename
@filename
EDIT filename
SP''L filename
SQLPl"s %ile Comman#s
SQL statements communicate "ith the 3racle Ser#er. SQL$%lus commands control the
en#ironment( format query results( and manage files. You can use the commands identified
in the follo"ing table
Co00"n# De+c!ition
S&WfE+ filename U.extV
U4E%UL&CL+&%%UE.-VV
Sa#es current contents of SQL buffer to a
file. 'se &%%E.- to add to an existing file)
use 4E%L&CE to o#er"rite an existing file.
The default extension is D sql.
#$% filename.extV 2rites the contents of a re#iously saTed file
to the SQL buffer. The default extension for
the filename is D sql.
STA;RT< filename[ext]
4uns a re#iously sa#ed command file.
Y filename 4uns a re#iously saTed command file (same
as ST&4T).
E- U!TV !n#o,es the editor and sa#es the buffer
contents to a file named
E/;+T< [filename[ext]]
!n#o,es the editor to edit contents to a sa#ed
file
S)O;OL< ;=ilename;e>t<< ?
OFF?O4T
Stores query results in a file. 3// closes the
sool file and sends the file results to the
system rinter
E@+T
Lea#es SQL$%L'S
3"
S"mmar3
SELECT ;/+ST+-CT< A*,column ;alias< , . . . B FROM tableC
1se SQL'(lus as an environment to"
#%ecute SQL statements
#it SQL statements
S#L#C$ S%"%$2$n%
!n this lesson( you ha#e learned about retrie#ing data from a database table "ith the
SELECT statement. The syntax is as follo"s)
SELECT U-!ST!.CTV Z $ ( column[name UaliasV( \N
/439 table[name 1
+n t8is sDnta>,t8e *oles o= EeD :o*#s a*eF
SELECT is a list of at least one column
/+ST+-CT suresses dulicates
$ selects all columns
ColumnGname selects the named column
Alias gi#es selected column a different heading
FROM secifies the table containing the columns
3%
(ractice Overvie!
Selecting all ata from ifferent tables
&escribing the structure of tables
(erforming arithmetic calculations an specifying column
names
1sing SQL'(lus eitor
P."0%0$ O#$.#$-
This is the first of many ractices. The solutions (if you require them) can be
found in &endix &. %ractices are intended to introduce all toics co#ered
in the lesson. Questions <D@ are aerDbased.
!n any ractice( there may be &if you have time& or &if you want etra
challen'e& questions. -o these only if you ha#e comleted all other
questions "ithin the allocated time and "ould li,e a further challenge to
your s,ills.
Ta,e the ractice slo"ly and recisely. You can exeriment "ith sa#ing and
running command files. !f you ha#e any questions at any time( attract the
instructorKs attention.
P"e!?B"+e# :ue+tion+
/or questions <D@ circle either True or /alse.
3&
P!"ctice $
=.!nitiate a SQL$%lus session using the user !- and ass"ord ro#ided by the
instructor.
<.SQL$%lus commands access the database.
True>/alse
6.2ill the SELECT statement execute successfully]
True>/alse
SHLI SELECT ename, Job, sal Sala*D
FROM emp $
@.2ill the SELECT statement execute successfully]
True>/alse
SHLI SELECT *
FROM sal9*a#e
(. There are four coding errors in this statement. Can you identify them]
SHLI SELECT empno, ename
Sala*D > 12 A--4AL SALARK
FROM emp$
7. Sho" the structure of the -E%T table. Select all data from the -E%T table.
N"0e Nu))@ T1e
-E%T.3 .'9CE4(<)
-.&9E W&4C:&4<(=@)
L3C W&4C:&4<(=6)
DEPTNO DNAME LOC
=; &CC3'.T!.B .E2 Y340
<; 4ESE&4C: -&LL&S
6; S&LES C:!C&B3
@; 3%E4&T!3.S C3ST3.
3'
(ractice 1 80,n%nu$*9
5. Sho" the structure of the E9% table. Create a query to dislay the name(
*ob. hire date( and emloyee number for each emloyee( "ith emloyee
number aearing first. Sa#e your SQL statement to a file named pl)*.s)l.
N"0e Nu))@ T1e
E9%.3 .3T .'LL .'9CE4(@)
E.&9E W&4C:&4<(=;)
+3C W&4C:&4<(8)
9B4 .'9CE4(@)
:!4E-&TE -&TE
S&L .'9CE4(5(<)
C399 .'9CE4(5(<)
-E%T.3 .'9CE4(<)
?. 4un your query in the file lq5.sql.
E(PN' ENA(E B') 0I&EDATE
%3"' SM+T, CLER2 1%C12C1'&(
%'' ALLE- SALESMA- 2(C(2C1'&1
%!21 .AR/ SALESMA- 22C(2C1'&1
%!"" 0O-ES MA-A3ER (2C(C1'&1
%"! MART+- SALESMA- 2&C('C1'&1
%"'& 1LA2E MA-A3ER (1C(!C1'&1
%%&2 CLAR2 MA-A3ER ('C("C1'&1
%%&& SCOTT A-ALKST ('C12C1'&2
%&3' 2+-3 )RES+/E-T 1%C11C1'&1
%& T4R-ER SALESMA- (&C('C1'&1
%&%" A/AMS CLER2 12C(1C1'&3
%'(( 0AMES CLER2 (3C12C1'&1
%'(2 FOR/ A-ALKST (3C12C1'&1
%'3 M+LLER CLER2 23C(1C1'&2
=@ ro"s selected.
(
(ractice 1 :continue;
8. Create a query to dislay unique *obs from the E9% table.
B')
A-ALKST
CLER2
MA-A3ER
)RES+/E-T
SALESMA-
!f you ha#e time( comlete the follo"ing exercises)
=;. Loadplc+*.s)l into the SQL buffer. .ame the column headings Em O( Emloyee( +ob(
and :ire -ate( resecti#ely. 4erun your query.
Em- C Em-lo3ee Bob 0ire Date
%33' 2+-3 )RES+/E-T 1%L-OML&1
%"'& 1LA2E MA-A3ER (1 LMAKL &1
%%&2 CLAR2 MA-A3ER ('L04-L&1
%!"" 0O-ES MA-A3ER (2 LA)RL &1
%"! MART+- SALESMA- 2&LSE)L&1
%'' ALLE- SALESMA- 2(LFE1L&1
%& T4R-ER SALESMA- (&LSE)L&1
%'(( 0AMES CLER2 (3L/ECL&1
%!21 .AR/ SALESMA- 22LFE1L&1
%'(2 FOR/ A-ALKST (3L/ECL&1
%3"' SM+T, CLER2 1%L/ECL&(
%%&& SCOTT A-ALKST ('L/ECL&2
%&%" A/AMS CLER2 12 L0A-L & 3
%'3 M+LLER CLER2 2 3L 0A-L & 2
1 *o:s selecte#
1
(ractice 1 :continue;
==. -islay the name concatenated "ith the *ob. searated by a comma
and sace( and name the column Emloyee and Title.
EmploDee an# Title
2+-3, )RES+/E-T 1LA2E, MA-A3ER
CLAR2, MA-A3ER 0O-ES, MA-A3ER
MART+-, SALESMA- ALLE-,
SALESMA- T4R-ER, SALESMA-
0AMES, CLER2 .AR/, SALESMA-
FOR/, A-ALKST SM+T,, CLER2
SCOTT, A-ALKST A/AMS, CLER2L
M+LLER, CLER2 1 *o:s selecte#.
!f you "ant extra challenge( comlete the follo"ing exercise)
=<. Create a query to dislay all the data from the E9% table. Searate
each column by a comma. .ame the column T:E 3'T%'T.
T:E 3'T%'T
%33',2+-3,)RES+/E-T, ,1%L-OML&1,!(((, , 1(
%"'3,1LA2E,MA-A3ER,%&3',(1LMAKL31, 23!(, ,3(
%%32,CLAR2,MA-A3ER,%33',('L04-L31, 2!(, , 1(
%!"",0O-ES, MA-A3ER,%33',(2LA)RL31, 2'%!, , 2(
%"!,MART+-,SALESMA-,%"'&,2&LSE)L&1, 12!(, 1((,3(
%'',ALLE-,SALESMA-,%"'&,2(LFE1L&1, 1"((,3((,3(
%3,T4R-ER, SALESMA-,%"'&,(&LSE)L&1, 1!((, (,3(
%'((,0AMES,CLER2,%"'&,(3L/ECL&1,'!(,,3(
%!21,.AR/,SALESMA-,%"'&,22LFE1L&1,12!(, !((,3(
%'(2,FOR/,A-ALKST,%!"",(3L/ECL&1, 3(((, , 2(
%3"',SM+T,,CLER2,%'(2,1%L/ECL&(,&((,,2(
%%&&,SCOTT,A-ALKST,%!"",('L/ECL&2,3(((,,2(