0 évaluation0% ont trouvé ce document utile (0 vote)
20 vues36 pages
SQL is the basic lan!ua!e used to manipulate and retrieve data from the "racle(i database$ "racle#s procedural extension of SQL7 allows embedded SQL operations in 7ava code$ 0n this chapter3 you will learn how to write basic SQL statements to retrieve data from tables$ 9ou will also learn how to limit the information retrieved and to display the results in a specific order$
SQL is the basic lan!ua!e used to manipulate and retrieve data from the "racle(i database$ "racle#s procedural extension of SQL7 allows embedded SQL operations in 7ava code$ 0n this chapter3 you will learn how to write basic SQL statements to retrieve data from tables$ 9ou will also learn how to limit the information retrieved and to display the results in a specific order$
SQL is the basic lan!ua!e used to manipulate and retrieve data from the "racle(i database$ "racle#s procedural extension of SQL7 allows embedded SQL operations in 7ava code$ 0n this chapter3 you will learn how to write basic SQL statements to retrieve data from tables$ 9ou will also learn how to limit the information retrieved and to display the results in a specific order$
Introduction to Oracle9i: SQL Exam Objectives Covered in this
Chapter: ritin! Basic SQL Select Statements o List the capabilities of SQL SELECT statements o Execute a basic SELECT statement "estrictin! and Sortin! #ata o Limit the rows retrieved by a query o Sort the rows retrieved by a query $ote Exam obectives are subect to chan!e at any time without prior notice and at "racle#s sole discretion$ %lease visit "racle#s Certification website &http://www.oracle.com/education/certification/' for the most current exam obectives listin!$ The "racle(i database provides many useful and powerful features$ )any of the features are incorporated at the SQL level$ SQL &pronounced *sequel*' has been adopted by most relational database mana!ement systems &+,-)S'$ The .merican /ational Standards 0nstitute &./S0' has been refinin! standards for the SQL lan!ua!e for the past 12 years$ "racle3 li4e many other companies3 has ta4en the ./S0 standard of SQL and extended it to include much additional functionality$ SQL is the basic lan!ua!e used to manipulate and retrieve data from the "racle(i database$ SQL is a nonprocedural lan!ua!e5it does not have pro!rammatic constructs such as loop structures$ %L6SQL is "racle#s procedural extension of SQL3 and SQL7 allows embedded SQL operations in 7ava code$ The scope of this test includes only SQL$ The SQL SELECT statement is used to query data from the database8stora!e structures3 such as tables and views$ 0n this chapter3 you will learn how to write basic SQL statements to retrieve data from tables$ 9ou will also learn how to limit the information retrieved and to display the results in a specific order$ SQL %undamentals The basic structure of data stora!e in "racle(i database is a table$ . table consists of columns and its characteristics$ ,ata is stored in the table as rows$ Creatin! and maintainin! tables are discussed in detail in Chapter :3 *)ana!in! Tables and Constraints$* To !et started with SQL in this chapter3 you will use the sample ;+ schema supplied with the "racle(i database$ $ote <hen you install "racle software3 choose the option to create a seed database$ This database will have the sample schemas used in this boo4$ The default 0,s and password for the seed database are S9STE)6)./.=E+3 S9S6C;./=E>"/>0/ST.LL$ The account S9S is the "racle dictionary owner3 and S9STE) is a ,-. account$ 0nitially3 the sample schemas are loc4ed$ 9ou need to connect to the database usin! S9STE)3 and then unloc4 the account usin! the ALTER USER statement$ To unloc4 the ;+ schema3 use ALTER USER HR IDENTIIED !" HR#ASS$%RD A&&%UNT UNL%&'?$ /ow you can connect to the ;+ schema usin! the password ;+%.SS<"+,$ SQL statements are li4e plain En!lish but with specific syntax$ SQL is a simple3 yet powerful3 lan!ua!e used to create3 access3 and manipulate data and structure in the database$ SQL statements can be cate!ori@ed as listed in Table 1$1$ Table &'&: SQL Statement Cate!ories SQL Cate!or( #escription ,ata )anipulation Lan!ua!e &,)L' Ased to access3 create3 modify3 or delete data in the existin! structures of the database$ ,)L statements include those to query information &SELE&T'3 add new rows &INSERT'3 modify existin! rows &U#DATE'3 delete existin! rows &DELETE'3 perform a conditional update or insert operation &(ER)E'3 see an execution plan of SQL &E*#LAIN #LAN'3 and loc4 a table to restrict access &L%&' TA!LE'$ ,ata ,efinition Lan!ua!e &,,L' Ased to define3 alter3 or drop database obects and their privile!es$ ,,L statements include those to create3 modify3 drop3 or rename obects &&REATE3 ALTER3 DR%#3 RENA(E'3 remove all rows from a database obect without droppin! the structure &TRUN&ATE'3 mana!e access privile!es &)RANT3 RE+%'E'3 audit database use &AUDIT3 N%AUDIT' and add a description about an obect to the dictionary &&%((ENT'$ Transaction Control Ased to !roup a set of ,)L statements as a sin!le transaction$ Asin! these statements3 you can save the chan!es &&%((IT' or discard the chan!es &R%LL!A&'' made by ,)L statements$ .lso included in the transaction8control statements are statements to set a point or mar4er in the transaction for possible rollbac4 &SA+E#%INT' and to define the properties for the transaction &SET TRANSA&TI%N'$ Session Control Ased to control the properties of a user session$ &. session is the point from which you are connected to the database until you disconnect$' Session8control statements include those to control the session properties &ALTER SESSI%N' and to enable6disable roles &SET R%LE'$ System Control Ased to mana!e the properties of the database$ There is only one statement in this cate!ory &ALTER S"STE('$ Table 1$1 provides an overview of all the statements that will be covered in this boo4$ ,o not worry if you do not understand certain terms3 such as role3 session3 privilege3 and so on$ <e will cover all the statements in the comin! chapters with many examples$ 0n this chapter3 we will be!in with writin! simple statements to query the database &SELE&T statements'$ -ut first3 we need to review some SQL fundamentals$ Oracle #atat(pes <hen you create a table to store data in the database3 you need to specify a datatype for all of the columns you define in the table$ "racle has many datatypes to suit application requirements$ "racle(i also supports ./S0 and ,-1 datatypes$ The "racle built8in datatypes can be broadly classified as shown in Table 1$1$ Table &'): Oracle Built*in #atat(pes Cate!or( #atat(pes Character C;.+3 /C;.+3 B.+C;.+13 /B.+C;.+1 Table &'): Oracle Built*in #atat(pes Cate!or( #atat(pes /umber /A)-E+ Lon! and raw L"/=3 L"/= +.<3 +.< ,ate and time ,.TE3 T0)EST.)%3 T0)EST.)% <0T; T0)E C"/E3 T0)EST.)% <0T; L"C.L T0)E C"/E3 0/TE+B.L 9E.+ T" )"/T;3 0/TE+B.L ,.9 T" SEC"/, Lar!e obect CL"-3 /CL"-3 -CL"-3 -D0LE +ow 0, +"<0,3 A+"<0, 0n this section3 we will discuss only a few of the built8in datatypes to !et started with SQL$ .ll the datatypes and their usa!e are discussed in detail in Chapter :$ C+,"-.size/0 The CHAR datatype is a fixed8len!th alphanumeric strin!3 which has a maximum len!th in bytes$ ,ata stored in C;.+ columns is space8padded to fill the maximum len!th$ 0ts si@e can ran!e from a minimum of 1 byte to a maximum of 1222 bytes$ The default si@e is 1$ <hen you create a column usin! the C;.+ datatype3 the database will ensure that all data placed in this column has the defined len!th$ 0f the data is shorter than the defined len!th3 it is space8padded on the ri!ht to the specified len!th$ 0f the data is lon!er3 an error is raised$ 1,"C+,")-.size/0 The VARCHAR2 datatype is a variable8len!th alphanumeric strin!3 which has a maximum len!th in bytes$ B.+C;.+1 columns require only the amount of space needed to store the data and can store up to E222 bytes$ There is no default si@e for the B.+C;.+1 datatype$ .n empty B.+C;.+1&1222' column ta4es up as much room in the database as an empty B.+C;.+1&1' column$ $ote The default si@e of a C;.+ datatype is 1$ Dor a B.+C;.+1 datatype3 you must always specify the si@e$ The B.+C;.+1 and C;.+ datatypes have different comparison rules for trailin! spaces$ <ith the C;.+ datatype3 trailin! spaces are i!nored$ <ith the B.+C;.+1 datatype3 trailin! spaces are not i!nored3 and they sort hi!her than no trailin! spaces$ ;ere#s an example:
C;.+ datatype: ,"o, - ,"o , B.+C;.+1 datatype: ,"o, . ,"o , $23BE" -.p/4 .s/0 The NUMBER datatype stores numbers with a precision of p di!its and a scale of s di!its$ The precision and scale values are optional$ /umeric datatypes are used to store ne!ative and positive inte!ers3 fixed8point numbers3 and floatin!8point numbers$ The precision can be between 1 and FG3 and the scale has a ran!e between 8GE and 11:$ 0f the precision and scale are omitted3 "racle assumes the maximum of the ran!e for both values$ 9ou can have precision and scale di!its in the inte!er part$ The scale rounds the value after the decimal point to s di!its$ Dor example3 if you define a column as /A)-E+&H31'3 the ran!e of values you can store in this column is from 8((($(( to ((($((? that is3 H81IF for the inte!er part3 and the decimal part is rounded to two di!its$ Even if you do not include the decimal part for the value inserted3 the maximum number you can store in a /A)-E+&H31' definition is ((($ "racle will round numbers inserted into numeric columns with a scale smaller than the inserted number$ Dor example3 if a column were defined as /A)-E+&E31' and you specified a value of 11$11H to !o into that column3 the resultin! number would be rounded to 11$1F before it was inserted into the column$ 0f the value exceeds the precision3 however3 an "racle error is returned$ 9ou cannot insert 11F$1 into a column defined as /A)-E+&E31'$ Specifyin! the scale and precision does not force all inserted values to be a fixed len!th$ 0f the scale is ne!ative3 the number is rounded to the left of the decimal$ -asically3 a ne!ative scale forces s number of @eros ust to the left of the decimal$ 0f you specify a scale that is !reater than the precision value3 the precision defines the maximum number of di!its to ri!ht of the decimal point after the @eros$ Dor example3 if a column is defined as /A)-E+&F3H'3 the ran!e of values you can store is from 82$22((( to 2$22(((? that is3 it requires two @eros &s8p' after the decimal point and rounds the decimal part to three di!its &p' after @eros$ Table 1$F shows several examples of how numeric data is stored with various definitions$ Table &'5: 6recision and Scale Examples 1alue #atat(pe Stored 1alue Explanation 11F$1HJE /A)-E+ 11F$1HJE +an!e and precision are set to the maximum3 so the datatype can store any value$ 11FE$(G:J /A)-E+&J31' 11FE$(( Since scale is only 13 the decimal part of the value is rounded to two di!its$ 11FEH$11FEH /A)-E+&J31' Error The ran!e of inte!er part is only from 8(((( to (((($ 11FEHJ /A)-E+&J31' Error %recision is lar!er than specified? ran!e is only from 8(((( to (((($ 11FE$(G:J /A)-E+&J' 11FH ,ecimal part rounded to the next inte!er$ 11FEHJ$1 /A)-E+&J' 11FEHJ ,ecimal part rounded$ 11FEH$FEH /A)-E+&H381' 11F22 /e!ative scale rounds the number KsL di!its left to the decimal point$ 81 rounds to hundreds$ 11FEHJ: /A)-E+&H381' 11FEJ22 +ounded to the nearest hundred$ 11FEHJ:G /A)-E+&H381' Error "utside ran!e? can have only five di!its3 excludin! the Table &'5: 6recision and Scale Examples 1alue #atat(pe Stored 1alue Explanation two @eros representin! hundreds3 for a total of seven di!its$ &s8&8 p'IsMpIHM1I:' 11FEHJ:G( /A)-E+&H38E' 11FEJ2222 +ounded to nearest 12222$ 11FEHJ:G(2 /A)-E+&H38E' Error "utside ran!e? can have only five di!its excludin! the four trailin! @eros$ 11FEH$HG /A)-E+&N3 1' 11FEH$J Ase of N in precision specifies the default limit &FG'$ 2$1 /A)-E+&E3H' Error +equires a @ero after the decimal point &H8EI1' 2$211FEHJ: /A)-E+&E3H' 2$211FH +ounded to four di!its after the decimal point and @ero$ 2$2(((( /A)-E+&E3H' 2$2(((( Stored as it is? only four di!its after the decimal point and @ero$ 2$2((((J /A)-E+&E3H' Error +oundin! this value to four di!its after the decimal and @ero results in 2$13 which is outside the ran!e$ #,TE The DATE datatype is used to store date and time information$ This datatype can be converted to other forms for viewin!3 but it has a number of special functions and properties that ma4e date manipulation and calculations simple$ The time component of the ,.TE datatype has a resolution of one second5no less$ The ,.TE datatype occupies a stora!e space of seven bytes$ The followin! information is contained within each ,.TE datatype: Century 9ear )onth ,ay ;our )inute Second ,ate values are inserted or updated in the database by convertin! either a numeric or character value into a ,.TE datatype usin! the function T%/DATE$ "racle defaults the format to display date as DDM!N""$ This format shows that the default date must be!in with a two8di!it day3 followed by a three8character abbreviation for the month3 followed by a two8di!it year$ 0f you specify the date without includin! a time component3 the time is defaulted to midni!ht3 or 22:22:22 in military time$ The S"SDATE function returns the current system date and time from the database server to which you#re currently connected$ $ote The default date format is specified usin! the initiali@ation parameter /LS>,.TE>D"+).T$ The value of this parameter can be chan!ed in the user#s environment or in the user#s session$ Operators and Literals .n operator is a manipulator that is applied to a data item in order to return a result$ Special characters represent different operations in "racle &M represents addition3 for example'$ "perators are commonly used in all pro!rammin! environments3 and you should already be familiar with the followin! operators3 which may be classified into two types: 2nar( operator A #nar$ operator has only one operand$ Examples are M1 and 8H$ They have the format KoperatorLKoperandL$ Binar( operator . binar$ operator has two operands$ Examples are HME and :NH$ They have the format Koperand%LKoperatorLKoperand2L$ 9ou can insert spaces between the operand and operator to improve readability$ ,rithmetic Operators Arit&'etic operators operate on numeric values$ Table 1$E shows the various arithmetic operators in "racle and how to use them$ Table &'7: ,rithmetic Operators Operator 6urpose Example M 8 Anary operators: Ase to represent positive or ne!ative data item$ Dor positive items3 the M is optional$ 81FE$EE M .ddition: Ase to add two data items or expressions$ 1ME 8 Subtraction: Ase to find the difference between two data items or expressions$ 12$E81 N )ultiplication: Ase to multiply two data items or expressions$ HN12 6 ,ivision: Ase to divide a data item or expression with another$ G$E61 $ote ,o not use two hyphens &88' to represent double ne!ation? use a space or parenthesis in between3 as in 8&812'$ Two hyphens represent the be!innin! of a comment in SQL$ Concatenation Operator The concatenation operator is used to concatenate or oin two character &text' strin!s$ The result of concatenation is another character strin!$ Concatenatin! a @ero8len!th strin! ,, or a NULL with another strin! results in a strin!3 not a NULL$ Two vertical bars 00 are used as the concatenation operator$ ;ere are two examples: ,%racle1i, 00 ,Data2a3e, results in ,%racle1iData2a3e, ,%racle1i , 00 ,Data2a3e, results in ,%racle1i Data2a3e, Set Operators Set operators are used in compound queries5queries that combine the results of two queries$ The number of columns selected in both queries must be the same$ Table 1$H lists the set operators and how to use them$ Set operators are discussed in detail in Chapter H3 *7oins and Subqueries$* Table &'8: Set Operators Operator 6urpose A/0"/ +eturns all rows from either queries? no duplicate rows A/0"/ .LL +eturns all rows from either query3 includin! duplicates 0/TE+SECT +eturns distinct rows that are returned by both queries )0/AS +eturns distinct rows that are returned by the first query but not returned by the second$ Operator 6recedence 0f multiple operators are used in the same expression3 "racle evaluates them in the order o( precedence set in the database en!ine$ "perators with hi!her precedence are evaluated before operators with lower precedence$ "perators with the same precedence are evaluated from left to ri!ht$ Table 1$J lists the precedence$ Table &'9: SQL Operator 6recedence 6recedence Operator 6urpose 1 4 5 Anary operators3 ne!ation 1 6 / )ultiplication3 division F 5 4 00 .ddition3 subtraction3 concatenation Asin! parentheses chan!es the order of precedence$ The innermost parenthesis is evaluated first$ 0n the expression 1M1NF3 the result is :3 because 1NF is evaluated first and the result is added to 1$ 0n the expression &1M1'NF3 1M1 is evaluated first3 and the result is multiplied by F3 !ivin! ($ Literals Literals are values that represent a fixed value &constant'$ There are four types of literals: Text &or character' 0nte!er /umber 0nterval 9ou can use literals within many of the SQL functions3 expressions3 and conditions$ Text The text literal must be enclosed in sin!le quotation mar4s$ .ny character between the quotation mar4s is considered part of the text value$ "racle treats all text literals as thou!h they were C;.+ datatypes$ The maximum len!th of a text literal is E222 bytes$ Sin!le quotation mar4s can be included in the literal text value by precedin! it with another sin!le quotation mar4$ ;ere are some examples of text literals: #The Quic4 -rown Dox# #That man##s suit is blac4# #.nd 0 quote: *This will never do$* # #118SE%81221# Integer 0nte!er literals can be any number of numerals3 excludin! a decimal separator and up to FG di!its lon!$ ;ere are two examples: 1E 8EHJ Number /umber literals can include scientific notation3 as well as di!its and the decimal separator$ ;ere are some examples: 1E 8FEH$JH 1FE812 Interval 0nterval literals specify a period of time in terms of years and months or in terms of days and seconds$ These literals correspond to the "racle datatype 0/TE+B.L 9E.+ T" )"/T; and 0/TE+B.L ,.9 T" SEC"/,$ These datatypes will be discussed in more detail in Chapter :$ ritin! Simple Queries . )#er$ is a request for information from the database tables$ Simple queries are those that retrieve data from a sin!le table$ The basis of a query is the SELE&T statement$ Queries usin! multiple tables are discussed in later chapters$ 2sin! the SELECT Statement The SELE&T statement is the most commonly used statement in SQL$ 0t allows you to retrieve information already stored in the database$ The statement be!ins with the 4eyword SELE&T3 followed by the column names whose data you want to query$ 9ou can either select information from all the columns &denoted by 6' or name specific columns in the SELE&T clause to retrieve data$ The R%( clause provides the name of the table3 view3 or materiali@ed view to use in the query$ These obects are discussed in detail in later chapters$ Dor simplicity3 we will use tables for the rest of this chapter$ Let#s use the 7"-S table defined in the ;+ schema of the "racle(i seed database created durin! installation$ The 7"-S table definition is provided in Table 1$:$ Table &':: ;OBS Table #e<inition Column $ame #atat(pe len!th 7"->0, B.+C;.+1 12 7"->T0TLE B.+C;.+1 F2 Table &':: ;OBS Table #e<inition Column $ame #atat(pe len!th )0/>S.L.+9 /A)-E+ J32 ).O>S.L.+9 /A)-E+ J32 The simple form of a SELE&T statement to retrieve all the columns and rows from the 7"-S table is as follows &only part of output result set is shown here': S7L8 SELE&T 6 R%( 9o23: ;%!/ID ;%!/TITLE (IN/SALAR" (A*/SALAR" 4444444444 4444444444444444444444444444444 4444444444 4444444444 AD/#RES #re3ident <==== >==== AD/+# Admini3tration +ice #re3ident ?@=== A==== AD/ASST Admini3tration A33i3tant A=== B=== I/()R inance (anaCer D<== ?B=== I/A&&%UNT Accountant ><== 1=== E E E E E IT/#R%) #roCrammer >=== ?==== ('/(AN (arFetinC (anaCer 1=== ?@=== ('/RE# (arFetinC Repre3entatiGe >=== 1=== HR/RE# Human Re3ource3 Repre3entatiGe >=== 1=== #R/RE# #u2lic Relation3 Repre3entatiGe >@== ?=@== ?1 row3 3elected. S7L8 $ote The 4eywords3 column names3 and table names are case insensitive$ "nly literals enclosed in sin!le quotation mar4s are case sensitive in "racle$ ;ow do you list only the ob title and minimum salary from this tableP 0f you 4now the column names and the table name3 writin! the query is simple$ ;ere3 the column names are 7"->T0TLE and )0/>S.L.+93 and the table name is 7"-S$ Execute the query by endin! the query with a semicolon$ 0n SQLN%lus3 you can execute the query by enterin! a slash on a line by itself or by usin! the RUN command$ S7L8 SELE&T 9o2/titleH min/3alarI R%( 9o23: ;%!/TITLE (IN/SALAR" 44444444444444444444444444444444444 4444444444 #re3ident <==== Admini3tration +ice #re3ident ?@=== Admini3tration A33i3tant A=== inance (anaCer D<== Accountant ><== AccountinC (anaCer D<== #u2lic Accountant ><== E E E E E #roCrammer >=== (arFetinC (anaCer 1=== (arFetinC Repre3entatiGe >=== Human Re3ource3 Repre3entatiGe >=== #u2lic Relation3 Repre3entatiGe >@== ?1 row3 3elected. S7L8 /otice that the numeric column &)0/>S.L.+9' is ali!ned to the ri!ht and the character column &7"->T0TLE' is ali!ned to the left$ ,oes it seem that the column headin! )0/>S.L.+9 should be more meanin!fulP <ell3 you can provide a col#'n alias to appear in the query results$ Column ,lias $ames The column alias name is defined next to the column name with a space or by usin! the 4eyword AS$ 0f you want a space in the column alias name3 you must enclose it in double quotation mar4s$ The case is preserved only when the alias name is enclosed in double quotation mar4s? otherwise3 the display will be uppercase$ The followin! example demonstrates usin! an alias name for the column headin! in the previous query$ S7L8 SELE&T 9o2/title AS TitleH < min/3alarI AS J(inimum SalarIJ R%( 9o23 S7L8 / TITLE (inimum SalarI 44444444444444444444444444444444444 44444444444444 #re3ident <==== Admini3tration +ice #re3ident ?@=== Admini3tration A33i3tant A=== inance (anaCer D<== Accountant ><== AccountinC (anaCer D<== E E E E E #roCrammer >=== (arFetinC (anaCer 1=== (arFetinC Repre3entatiGe >=== Human Re3ource3 Repre3entatiGe >=== #u2lic Relation3 Repre3entatiGe >@== ?1 row3 3elected. S7L8 0n this listin!3 the column alias name Title appears in all capital letters because we did not enclose it in double quotation mar4s$ $ote The asteris4 &6' is used to select all columns in the table$ This is very useful when you do not 4now the column names or when you are too la@y to type all of the column names$ Ensurin! 2ni=ueness The D*ST*NCT 4eyword &or UNI7UE 4eyword' followin! SELE&T ensures that the resultin! rows are unique$ Aniqueness is verified a!ainst the complete row3 not the first column$ 0f you need to find the unique departments in the E)%L"9EES table3 issue this query: S7L8 SELE&T DISTIN&T department/id R%( emploIee3: DE#ART(ENT/ID 4444444444444 ?= <= A= >= @= B= K= D= 1= ?== ??= ?< row3 3elected. S7L8 To demonstrate that uniqueness is enforced across the row3 let#s do one more query usin! the SELE&T DISTIN&T clause$ /otice ,E%.+T)E/T>0, repeatin! for each 7"->0, value$ S7L8 SELE&T DISTIN&T department/idH 9o2/id R%( emploIee3: DE#ART(ENT/ID ;%!/ID 4444444444444 4444444444 ?= AD/ASST <= ('/(AN <= ('/RE# A= #U/&LER' A= #U/(AN >= HR/RE# @= SH/&LER' @= ST/&LER' @= ST/(AN E E E E E ?== I/A&&%UNT ?== I/()R ??= A&/A&&%UNT ??= A&/()R SA/RE# <= row3 3elected. S7L8 $ote SELE&T 6 R%( TA!: shows all the tables and views in your schema$ The #2,L Table The DUAL table is a dummy table available to all users in the database$ 0t has one column and one row$ The ,A.L table is used to select system variables or to evaluate an expression$ ;ere are a few examples: S7L8 SELE&T S"SDATEH USER R%( dual: S"SDATE USER 444444444 444444444444444444444444444444 ?D4SE#4=< HR S7L8 SELE&T ,I,,m , 00 u3er 00 , TodaI i3 , 00 S"SDATE < R%( dual: ,I,,(,00USER00,T%DA"IS,00S"SDATE / 44444444444444444444444444444444444444444444444444444 I,m HR TodaI i3 ?D4SE#4=< S7L8 $ote S"SDATE and USER are built8in functions that provide information about the environment$ These functions are discussed in Chapter F3 *Sin!le8+ow Dunctions$* Limitin! "o>s . +HERE clause in the SELE&T statement is used to limit the number of rows processed$ .ny lo!ical conditions of the $HERE clause use the comparison operators$ +ows are returned or operated upon where the data satisfies the lo!ical condition&s' of the $HERE clause$ 9ou can use column names or expressions in the $HERE clause3 but not column alias names$ The $HERE clause follows the R%( clause in the SELE&T statement$ ;ow do you list the employees who wor4 for department (2P The followin! example shows how to limit the query to only the records belon!in! to department (2 by usin! a $HERE clause$ S7L8SELE&T fir3t/name 00,,00la3t/name JNameJH < department/id A R%( emploIee3 > $HERE department/id -1=: Name DE#ART(ENT/ID 4444444444444444444444444444444444444444444 4444444444444 SteGen 'inC 1= Neena 'ochhar 1= LeL De Haan 1= S7L8 $ote 9ou need not include the column names in the SELE&T clause to use them in the $HERE clause$ Barious operators available in "racle(i can be used in the $HERE clause to limit the number of rows$ Comparison Operators Co'parison operators compare two values or expressions and !ive a -oolean result of TRUE3 ALSE3 or NULL$ The comparison operators include those that test for equality3 inequality3 less than3 !reater than3 and value comparisons$ = (Equality) The - operator tests for equality$ The test evaluates to TRUE if the values or results of an expression on both sides of the operator are equal$ S7L8SELE&T fir3t/name 00,,00la3t/name JNameJH < department/id A R%( emploIee3 > $HERE department/id -1=: Name DE#ART(ENT/ID 4444444444444444444444444444444444444444444 4444444444444 SteGen 'inC 1= Neena 'ochhar 1= LeL De Haan 1= S7L8 !=, !, "r #= (Inequality) 9ou can use any one of these three operators to test for inequality$ The test evaluates to TRUE if the values on both sides of the operator do not match$ The operator .8 wor4s on all platforms3 the use of other operators for inequality chec4in! is not supported in all platforms$ S7L8SELE&T fir3t/name 00,,00la3t/name JNameJH < commi33ion/pct A R%( emploIee3 > $HERE commi33ion/pct M-.A@: Name &%((ISSI%N/#&T 444444444444444444444444444444444444444444 44444444444444 ;ohn Ru33ell .> 'aren #artner3 .A Al2erto ErraNuriN .A )erald &am2rault .A E E E E E E ;acF LiGinC3ton .< 'im2erelI )rant .?@ &harle3 ;ohn3on .? A< row3 3elected. S7L8 (Less T$an) The . operator evaluates to TRUE if the left side &expression or value' of the operator is less than the ri!ht side of the operator$ S7L8SELE&T fir3t/name 00,,00la3t/name JNameJH < commi33ion/pct A R%( emploIee3 > $HERE commi33ion/pct ..?@: Name &%((ISSI%N/#&T 444444444444444444444444444444444444444444 44444444444444 (attea (arGin3 .? DaGid Lee .? Sundar Ande .? Amit !anda .? Sundita 'umar .? &harle3 ;ohn3on .? B row3 3elected. S7L8 ! (%"re T$an) The 8 operator evaluates to TRUE if the left side &expression or value' of the operator is !reater than the ri!ht side of the operator$ S7L8SELE&T fir3t/name 00,,00la3t/name JNameJH < commi33ion/pct A R%( emploIee3 > $HERE commi33ion/pct 8.A@: Name &%((ISSI%N/#&T 444444444444444444444444444444444444444444 44444444444444 ;ohn Ru33ell .> S7L8 = (Less T$an "r Equal t") The .- operator evaluates to TRUE if the left side &expression or value' of the operator is less than or equal to the ri!ht side of the operator$ S7L8SELE&T fir3t/name 00,,00la3t/name JNameJH < commi33ion/pct A R%( emploIee3 > $HERE commi33ion/pct .-.?@: Name &%((ISSI%N/#&T 444444444444444444444444444444444444444444 44444444444444 %liGer TuGault .?@ Danielle )reene .?@ (attea (arGin3 .? DaGid Lee .? Sundar Ande .? Amit !anda .? $illiam Smith .?@ EliNa2eth !ate3 .?@ Sundita 'umar .? 'im2erelI )rant .?@ &harle3 ;ohn3on .? ?? row3 3elected. S7L8 != (&reater T$an "r Equal t") The 8- operator evaluates to TRUE if the left side &expression or value' of the operator is !reater than or equal to the ri!ht side of the operator$ S7L8SELE&T fir3t/name 00,,00la3t/name JNameJH < commi33ion/pct A R%( emploIee3 > $HERE commi33ion/pct 8-.A@: Name &%((ISSI%N/#&T 444444444444444444444444444444444444444444 44444444444444 ;ohn Ru33ell .> ;anette 'inC .A@ #atricF SullI .A@ Allan (cEwen .A@ S7L8 ,$? "r SO3E The AN" or S%(E operators are used to compare a value to each value in a list or subquery$ The AN" and S%(E operators always must be preceded by the comparison operators -3 M-3 .3 83 .-3 or 8-$ S7L8SELE&T fir3t/name 00,,00la3t/name JNameJH < department/id A R%( emploIee3 > $HERE department/id .-AN" O?=H?@H<=H<@P: Name DE#ART(ENT/ID 4444444444444444444444444444444444444444444 4444444444444 ;ennifer $halen ?= (ichael Hart3tein <= #at aI <= S7L8 ,LL The ALL operator is used to compare a value to every value in a list or sub8query$ The ALL operator must always be preceded by the comparison operators -3 M-3 .3 83 .-3 or 8-$ S7L8SELE&T fir3t/name 00,,00la3t/name JNameJH < department/id A R%( emploIee3 > $HERE department/id 8-ALL OD=H1=H?==P: Name DE#ART(ENT/ID 4444444444444444444444444444444444444444444 4444444444444 NancI )reen2erC ?== Daniel aGiet ?== ;ohn &hen ?== I3mael Sciarra ?== ;o3e (anuel Urman ?== Lui3 #opp ?== ShelleI HiCCin3 ??= $illiam )ietN ??= D row3 3elected. S7L8 Dor all the comparison operators discussed3 if one side of the operator is NULL3 the result is NULL$ Lo!ical Operators Logical operators are used to combine the results of two comparison conditions to produce a sin!le result or to reverse the result of a sin!le comparison$ N%T3 AND3 and %R are the lo!ical operators$ $OT The N%T operator is used to reverse the result$ 0t evaluates to TRUE if the operand is ALSE3 evaluates to ALSE if the operand is TRUE$ N%T returns NULL if the operand is NULL$ S7L8 SELE&T fir3t/nameH department/id < R%( emploIee3 A6 $HERE not Odepartment/id 8- A=P: IRST/NA(E DE#ART(ENT/ID 44444444444444444444 4444444444444 ;ennifer ?= (ichael <= #at <= S7L8 ,$# The AND operator evaluates to TRUE if both operands are TRUE$ 0t evaluates to ALSE if either operand is ALSE$ "therwise3 it returns NULL$ S7L8 SELE&T fir3t/nameH 3alarI < R%( emploIee3 A $HERE la3t/name - ,Smith, >6 AND 3alarI 8 K@==: IRST/NA(E SALAR" 44444444444444444444 4444444444 Lind3eI D=== S7L8 O" The %R operator evaluates to TRUE if either operand is TRUE$ 0t evaluates to ALSE if both operands are ALSE$ "therwise3 it returns NULL$ S7L8 SELE&T fir3t/nameH la3t/name < R%( emploIee3 A $HERE fir3t/name - ,'ellI, >6 %R la3t/name - ,Smith,: IRST/NA(E LAST/NA(E 44444444444444444444 4444444444444444444444444 Lind3eI Smith $illiam Smith 'ellI &hunC S7L8 L"gi'al (perat"r Trut$ Tables The followin! tables can be used as truth tables for the three lo!ical operators$ ./, Truth Table
T"2E ALSE %,LSE TRUE $2LL NULL Other Operators 0n this section3 we will discuss all the operators that can be used in the $HERE clause of the SQL statement that were not discussed earlier$ IN and N(T IN The IN and N%T IN operators are used to test a membership condition$ IN is equivalent to the -AN" operator3 which evaluates to TRUE if the value exists in the list or the result set from a subquery$ The N%T IN operator is equivalent to the M-ALL operator3 which evaluates to TRUE if the value does not exist in the list or the result set from a subquery$ The followin! examples demonstrate the use of these two operators$ S7L8 SELE&T fir3t/nameH la3t/nameH department/id < R%( emploIee3 A $HERE department/id IN O?=H <=H 1=P: IRST/NA(E LAST/NA(E DE#ART(ENT/ID 44444444444444444444 4444444444444444444444444 4444444444 SteGen 'inC 1= Neena 'ochhar 1= LeL De Haan 1= ;ennifer $halen ?= (ichael Hart3tein <= #at aI <= B row3 3elected. S7L8 SELE&T fir3t/nameH la3t/nameH department/id < R%( emploIee3 A $HERE department/id N%T IN >6 O?=H A=H >=H @=H B=H D=H 1=H ??=H ?==P S7L8 / IRST/NA(E LAST/NA(E DE#ART(ENT/ID 44444444444444444444 4444444444444444444444 4444444444444 (ichael Hart3tein <= #at aI <= Hermann !aer K= S7L8 $ote <hen usin! the N%T IN operator3 if any value in the list or the result returned from the subquery is NULL3 the query returns no rows$ Dor example3 la3t/name not in O,Smith,3 ,Thoma3,3 NULLP evaluates to la3t/name M- ,Smith, AND la3t/name M- ,Thoma3, AND la3t/name M- NULL$ .ny comparison on a NULL value results in NULL$ )ET*EEN The !ET$EEN operator is used to test a ran!e$ !ET$EEN A AND ! evaluates to TRUE if the value is !reater than or equal to A and less than or equal to B$ 0f N%T is used3 the result is the reverse$ The followin! example lists all the employees whose salary is between QH3222 and QJ3222$ S7L8 SELE&T fir3t/nameH la3t/nameH 3alarI < R%( emploIee3 A6 $HERE 3alarI !ET$EEN @=== AND B===: IRST/NA(E LAST/NA(E SALAR" 44444444444444444444 4444444444444444444444444 4444444444 !ruce Ern3t B=== 'eGin (ourCo3 @D== #at aI B=== S7L8 E+ISTS The E*ISTS operator is always followed by a subquery in parentheses$ &Dor more information on subqueries3 refer to Chapter H$' E*ISTS evaluates to TRUE if the subquery returns at least one row$ The followin! example lists the employees who wor4 for .dministration department$ S7L8 SELE&T la3t/nameH fir3t/nameH department/id < R%( emploIee3 e A $HERE E*ISTS O3elect ? R%( department3 d > $HERE d.department/id - e.department/id @6 AND d.department/name - ,Admini3tration,P: LAST/NA(E IRST/NA(E DE#ART(ENT/ID 4444444444444444444444 44444444444444444444 4444444444444 $halen ;ennifer ?= S7L8 IS N,LL and IS N(T N,LL To find the NULL values or N%T NULL values3 you need to use the IS NULL operator$ The - or M - operator will not wor4 with NULL values$ IS NULL evaluates to TRUE if the value is NULL. IS N%T NULL evaluates to TRUE if the value is not NULL$ To find the employees who do not have a department assi!ned3 use this query: S7L8 SELE&T la3t/nameH department/id < R%( emploIee3 A $HERE department/id IS NULL: LAST/NA(E DE#ART(ENT/ID 4444444444444444444444444 4444444444444 )rant S7L8 LI-E Asin! the LI'E operator3 you can perform pattern matchin!$ The pattern8search character Q is used to match any character and any number of characters$ The pattern8search character > is used to match any sin!le character$ 0f you are loo4in! for the actual character Q or > in the pattern search3 you can include an escape c&aracter in the search strin! and notify "racle usin! the ES&A#E clause$ The followin! query searches for all employees whose first name be!ins with S# and last name does not be!in with S$ S7L8 SELE&T fir3t/nameH la3t/name < R%( emploIee3 A $HERE fir3t/name LI'E ,SuQ, >6 AND la3t/name N%T LI'E ,SQ,: IRST/NA(E LAST/NA(E 44444444444444444444 4444444444444444444444444 Sundar Ande Sundita 'umar Su3an (aGri3 S7L8 The followin! example loo4s for all 7"->0, values that be!in with AC,$ Since > is a pattern8 matchin! character3 we must qualify it with an escape character$ "racle does not have a default escape character$ S7L8 SELE&T 9o2/idH 9o2/title < R%( 9o23 A $HERE 9o2/id liFe ,A&R/Q, ES&A#E ,R,: ;%!/ID ;%!/TITLE 4444444444 44444444444444444444444444444444444 A&/()R AccountinC (anaCer A&/A&&%UNT #u2lic Accountant S7L8 Table 1$G shows more examples of pattern matchin!$ Table &'@: 6attern*3atchin! Examples 6attern 3atches #oes $ot 3atch RS"/0>1 S"/0C13 ALT+.S"/011 S"/0CS13 S"/0F1H >0)E T0)E3 L0)E 0)E3 C+0)E SRS"/0>1 ESC.%E #S# RS"/0C13 RS"/0(1 S"/0C13 ALT+.S"/0C1 R)ES> > >LE ESC.%E #S# C+0)E>D0LE3 T0)E>%"LE C+0)ES%0LE3 C+0)E>.LE << Previous Top of page Next >> Sortin! "o>s The SELE&T statement may include the %RDER !" clause to sort the resultin! rows in a specific order based on the data in the columns$ <ithout the %RDER !" clause3 there is no !uarantee that the rows will be returned in any specific order$ 0f an %RDER !" clause is specified3 by default3 the rows are returned by ascendin! order of the columns specified$ 0f you need to sort the rows in descendin! order3 use the 4eyword DES& next to the column name$ 9ou may specify the 4eyword AS& to explicitly state to sort in ascendin! order3 althou!h it is the default$ The %RDER !" clause follows the R%( clause and $HERE clause in the SELE&T statement$ To retrieve all employee names of department (2 from the E)%L"9EES table ordered by last name3 use this query: S7L8 SELE&T fir3t/name 00 , , 00 la3t/name JEmploIee NameJ < R%( emploIee3 A $HERE department/id - 1= >6 %RDER !" la3t/name: EmploIee Name 4444444444444444444444444444444444444444444444 LeL De Haan SteGen 'inC Neena 'ochhar S7L8 9ou can specify more than one column in the %RDER !" clause$ 0n this case3 the result set will be ordered by the first column in the %RDER !" clause3 then the second3 and so on$ Columns or expressions not used in the SELE&T clause can also be used in the %RDER !" clause$ The followin! example shows the use of DES& and multiple columns in the %RDER !" clause$ S7L8 SELE&T fir3t/nameH hire/dateH 3alarIH manaCer/id mid < R%( emploIee3 A $HERE department/id IN O??=H?==P >6 %RDER !" mid AS&H 3alarI DES&H hire/date: IRST/NA(E HIRE/DATE SALAR" (ID 44444444444444444444 444444444 4444444444 4444444444 ShelleI =K4;UN41> ?<=== ?=? NancI ?K4AU)41> ?<=== ?=? Daniel ?B4AU)41> 1=== ?=D ;ohn <D4SE#41K D<== ?=D ;o3e (anuel =K4(AR41D KD== ?=D I3mael A=4SE#41K KK== ?=D Lui3 =K4DE&411 B1== ?=D $illiam =K4;UN41> DA== <=@ D row3 3elected. S7L8 $ote 9ou can use column alias names in the "+,E+ -9 clause$ 0f the DISTIN&T 4eyword is used in the SELE&T clause3 you can use only those columns listed in the SELE&T clause in the %RDER !" clause$ 0f you have used any operators on columns in the SELE&T clause3 the %RDER !" clause also should use them$ ;ere is an example: S7L8 SELE&T DISTIN&T ,ReCion , 00 reCion/id < R%( countrie3 A %RDER !" reCion/id: %RDER !" reCion/id 6 ERR%R at line A: %RA4=?K1?: not a SELE&Ted eLpre33ion S7L8 SELE&T DISTIN&T ,ReCion , 00 reCion/id < R%( countrie3 A %RDER !" ,ReCion , 00 reCion/id: ,RE)I%N,00RE)I%N/ID 44444444444444444444444444444444444444444444444 ReCion ? ReCion < ReCion A ReCion > S7L8 /ot only can you use the column name or column alias to sort the result set of a query3 you can also sort the results by specifyin! the position of the column in the SELE&T clause$ This is very useful if you have a len!thy expression in the SELE&T clause and you need the results sorted on this value$ The followin! example sorts the result set usin! positional values$ S7L8 SELE&T fir3t/nameH hire/dateH 3alarIH manaCer/id mid < R%( emploIee3 A $HERE department/id IN O??=H?==P >6 %RDER !" >H <H A: IRST/NA(E HIRE/DATE SALAR" (ID 44444444444444444444 444444444 4444444444 4444444444 ShelleI =K4;UN41> ?<=== ?=? NancI ?K4AU)41> ?<=== ?=? Daniel ?B4AU)41> 1=== ?=D ;ohn <D4SE#41K D<== ?=D I3mael A=4SE#41K KK== ?=D ;o3e (anuel =K4(AR41D KD== ?=D Lui3 =K4DE&411 B1== ?=D $illiam =K4;UN41> DA== <=@ D row3 3elected. S7L8 $ote The %RDER !" clause cannot have more than 1HH columns or expressions$ Sortin! N,LLs -y default3 in an ascendin! order sort3 the NULL values appear at the bottom of the result set? that is3 NULLs are sorted hi!her$ Dor descendin! order sorts3 NULL values appear at the top of the result set5a!ain3 NULL values are sorted hi!her$ The default behavior can be chan!ed by usin! the NULLS IRST or NULLS LAST 4eywords3 alon! with the column names &or alias names or positions'$ The followin! examples demonstrate the use of NULLS IRST in an ascendin! sort$ S7L8 SELE&T la3t/nameH commi33ion/pct < R%( emploIee3 A $HERE la3t/name LI'E ,RQ, >6 %RDER !" commi33ion/pct AS&H la3t/name DES&: LAST/NA(E &%((ISSI%N/#&T 4444444444444444444444444 44444444444444 Ru33ell .> RoCer3 RaphaelI Ra93 S7L8 SELE&T la3t/nameH commi33ion/pct < R%( emploIee3 A $HERE la3t/name LI'E ,RQ, >6 %RDER !" commi33ion/pct AS& NULLS IRSTH la3t/name DES&: LAST/NA(E &%((ISSI%N/#&T 4444444444444444444444444 44444444444444 RoCer3 RaphaelI Ra93 Ru33ell .> S7L8 "eal orld Scenario: h( #o e Limit and Sort "o>sA The power of an +,-)S and SQL lies in !ettin! exactly what we want from the database$ The sample tables we considered under the ;+ schema are small3 so even if you !et all the information from the table3 you can still find the specific data that you#re see4in!$ -ut what if you have a hu!e transaction table3 with millions of rowsP 9ou 4now how easy it is to loo4 throu!h a catalo! in the library to find a particular boo43 or to search throu!h an alphabetical listin! to find your name$ <hen queryin! a lar!e table3 ma4e sure you 4now what you want$ The $HERE clause lets you query for exactly what you#re loo4in! for$ The %RDER !" clause lets you sort rows$ The followin! steps can be used as an approach to query data from sin!le table$ 1$ Tnow the columns of the table$ 9ou may issue the DES&RI!E command to !et the column names and datatype$ Anderstand which column has what information$ 1$ %ic4 the column names you are interested in includin! in the query$ Ase these columns in the SELE&T clause$ F$ 0dentify the column or columns where you can limit the rows or the columns that can show you only the rows of interest$ Ase these columns in the $HERE clause of the query3 and supply the values as well as the appropriate operator$ E$ 0f the query returns more than few rows3 you may be interested in havin! them sorted in a particular order$ Specify the column names and the sortin! order in the %RDER !" clause of the query$ Let#s consider a table named %A+C;.SE>"+,E+S$ Dirst3 use the DES&RI!E command to list the columns$ S7L8 DES&RI!E purcha3e/order3 Name NullS TIpe 444444444444444444444 44444444 44444444444444 %RDERT N%T NULL NU(!ER O?BP %RDER/DT N%T NULL DATE &UST%(ERT N%T NULL +AR&HAR< O?<P !A&'/%RDER &HAR O?P %RD/STATUS &HAR O?P T%TAL/A(T N%T NULL NU(!ER O?DH>P SALES/TA* NU(!ER O?<H<P The obective of the query is to find the completed orders that do not have any sales tax$ 9ou want to see the order number and total amount of the order$ The correspondin! columns that appear in the SELE&T clause are "+,E+U and T"T.L>.)T$ Since you#re interested in only the rows with no sales tax in the completed orders3 the columns to appear in the $HERE clause are S.LES>T.O &chec4in! for @ero sales tax' and "+,>ST.TAS &chec4in! for completeness of order3 status code C'$ Since the query returns multiple rows3 you want to order them by the order number$ /otice that the S.LES>T.O column can be NULL3 so you want to ma4e sure that you !et all rows that have a sales tax amount of @ero or NULL$ SELE&T orderTH total/amt R%( purcha3e/order3 $HERE ord/3tatu3 - ,&, AND O3ale3/taL IS NULL %R 3ale3/taL - =P %RDER !" orderT: .n alternative is to use the N+L function to deal with the NULL values$ This function is discussed in Chapter F$ 2sin! Expressions .n e-pression is a combination of one or more values3 operators3 and SQL functions that result in a value$ The result of an expression !enerally assumes the datatype of its components$ The simple expression HMJ evaluates to 11 and assumes a datatype of /A)-E+$ Expressions can appear in the followin! clauses: The SELE&T clause of queries The $HERE clause3 %RDER !" clause3 and HA+IN) clause The +ALUES clause of the INSERT statement The SET clause of the U#DATE statement <e will review the syntax of usin! these statements in later chapters$ 9ou can include parentheses to !roup and evaluate expressions3 and then apply the result to the rest of the expression$ <hen parentheses are used3 the expression in the innermost parentheses is evaluated first$ ;ere is an example of a compound expression: &&1NE'6&FM1''N12$ The result of 1NE is divided by the result of FM1$ Then the result from the division operation is multiplied by 12$ The C.SE Expression The CASE expression is new to "racle(i and can be used to derive the 0DVT;E/VELSE lo!ic in SQL$ ;ere is the syntax of the simple &ASE expression: &ASE .expression8 $HEN .compare value8 THEN .return value8 E E E UELSE .return value8V END The &ASE expression be!ins with the 4eyword &ASE and ends with the 4eyword END$ The ELSE clause is optional3 the $HEN clause can be repeated for 11G times$ The followin! query displays a description for the +E=0"/>0, column based on the value$ S7L8 SELE&T countrI/nameH reCion/idH < &ASE reCion/id $HEN ? THEN ,Europe, A $HEN < THEN ,America, > $HEN A THEN ,A3ia, @ ELSE ,%ther, END &ontinent B R%( countrie3 K6 $HERE countrI/name LI'E ,IQ,: &%UNTR"/NA(E RE)I%N/ID &%NTINE 44444444444444444444 4444444444 4444444 I3rael > %ther India A A3ia ItalI ? Europe S7L8 The other form of the &ASE expression is the searched &ASE3 where the values are derived based on a condition$ This version has the followin! syntax: &ASE $HEN .condition8 THEN .return value8 E E E UELSE .return value8V END The followin! example cate!ori@es the salary as Low3 )edium3 and ;i!h usin! a searched &ASE expression$ S7L8 SELE&T fir3t/nameH department/idH 3alarIH < &ASE $HEN 3alarI . B=== THEN ,Low, A $HEN 3alarI . ?==== THEN ,(edium, > $HEN 3alarI 8- ?==== THEN ,HiCh, END &ateCorI @ R%( emploIee3 B $HERE department/id .- A= K6 %RDER !" fir3t/name: IRST/NA(E DE#ART(ENT/ID SALAR" &ATE)% 44444444444444444444 4444444444444 4444444444 444444 AleLander A= A?== Low Den A= ??=== HiCh )uI A= <B== Low ;ennifer ?= >>== Low 'aren A= <@== Low (ichael <= ?A=== HiCh #at <= B=== (edium Shelli A= <1== Low SiCal A= <D== Low 1 row3 3elected. S7L8 Summar( ,ata in the "racle database is mana!ed and accessed usin! SQL$ . SELE&T statement is used to query data from a table or view$ 9ou can limit the rows selected by usin! a $HERE clause and order the retrieved data usin! the %RDER !" clause$ 0n this chapter3 we reviewed fundamentals of SQL3 includin! datatypes and operators$ The C;.+ and B.+C;.+1 datatypes are used to store alphanumeric information$ The /A)-E+ datatype is used to store any numeric value$ ,ate values can be stored usin! the ,.TE datatype$ "racle has a wide ran!e of operators: arithmetic3 concatenation3 set3 comparison3 membership3 lo!ical3 pattern matchin!3 ran!e3 and existence and NULL chec4in!$ The &ASE expression is new to "racle(i$ 0t is used to brin! conditional lo!ic to SQL$ Exam Essentials 2nderstand the operators' Tnow the various operators that can be used in queries$ The parentheses around an expression chan!e the precedence of the operators$ Bno> ho> to execute a SQL statement' 9ou can execute a SQL statement by endin! the statement with a semicolon3 and in SQLN%lus3 by havin! the / on a line by itself or by usin! the RUN command$ 2nderstand the +E"E clause' The $HERE clause specifies a condition to limit the number or rows returned$ 9ou cannot use column alias names in this clause$ 2nderstand the O"#E" B? clause' The %RDER !" clause is used to sort the result set from a query$ 9ou can specify ascendin! order or descendin! order for the sort$ .scendin! order is the default$ Bno> the order o< clauses in the SELECT statement' The SELE&T statement must have a R%( clause$ The $HERE clause3 if it exists3 should follow the R%( clause and precede the %RDER !" clause$ Bno> the use o< the #2,L table' The ,A.L table is a dummy table in "racle with one column and one row$ This table is commonly used to !et the values of system variables such as S"SDATE or USER$ Bno> the characters used <or pattern matchin!' The R character is used to match @ero or more characters$ The > character is used to match one3 and only one3 character$ The SQL operator used with pattern8matchin! character is LI'E$ Be( Terms -efore you ta4e the exam3 be certain you are familiar with the followin! terms:
unary operator lo!ical operators arithmetic operators /A)-E+ binary operators operator &ASE order of precedence C;.+ precision column alias query comparison operators scale concatenation operator seed database ,.TE SELE&T DISTIN&T "evie> Questions &' 9ou issue the followin! query: SELE&T 3alarI JEmploIee SalarIJ R%( emploIee3: ;ow will the column headin! appear in the resultP .$ E)%L"9EE S.L.+9 -$ E)%L"9EE>S.L.+9 C$ Employee Salary ,$ employee>salary )' The E)% table is defined as follows: E36 Table Column #atat(pe Len!th E)%/" /A)-E+ E E/.)E B.+C;.+1 F2 S.L.+9 /A)-E+ 1E31 C")) /A)-E+ 1231 ,E%T/" /A)-E+ 1 9ou perform the followin! two queries: ?. SELE&T empno enum2erH ename <. R%( emp %RDER !" ?: F$ >. SELE&T empnoH ename @. R%( emp %RDER !" empno AS&: J$ <hich of the followin! is trueP .$ Statements 1 and 1 will produce the same result$ -$ Statement 1 will execute? statement 1 will return an error$ C$ Statement 1 will execute? statement 1 will return an error$ ,$ Statements 1 and 1 will execute but produce different results$ 5' 9ou issue the followin! SELE&T statement on the E)% table shown in question 1$ SELE&T O<==5OO3alarI6=.?P/<PP R%( emp: <hat will happen to the result if all of the parentheses are removedP .$ /o difference3 because the answer will always be NULL$ -$ /o difference3 because the result will be the same$ C$ The result will be hi!her$ ,$ The result will be lower$ 7' 0n the followin! SELE&T statement3 which component is a literalP &Choose all that apply$' SELE&T ,EmploIee Name: , 00 ename R%( emp where deptno - ?=: .$ 12 -$ ename C$ Employee /ame: ,$ WW 8' <hen you try to save FEHJ:$11HH into a column defined as /A)-E+&:31' what value is actually savedP .$ FEHJ:$22 -$ FEHJ:$1F C$ FEHJ:$11 ,$ FEHJ$11 9' <hat is the default display len!th of the ,.TE datatype columnP .$ G -$ ( C$ 1( ,$ J :' <hat will happen if you query the E)% table shown in question 1 with the followin!P SELE&T empnoH DISTIN&T enameH 3alarI R%( emp: .$ E)%/"3 unique values of E/.)E and then S.L.+9 are displayed$ -$ E)%/"3 unique values of the two columns3 E/.)E and S.L.+93 are displayed$ C$ DISTIN&T is not a valid 4eyword in SQL$ ,$ /o values will be displayed because the statement will return an error$ @' <hich clause in a query limits the rows selectedP .$ %RDER !" -$ $HERE C$ SELE&T ,$ R%( 9' The followin! listin! shows the records of the E)% table$ E(#N% ENA(E SALAR" &%(( DE#TN% 444444444 4444444444 444444444 444444444 444444444 KAB1 S(ITH D== <= K>11 ALLEN ?B== A== A= K@<? $ARD ?<@= @== A= K@BB ;%NES <1K@ <= KB@> (ARTIN ?<@= ?>== A= KB1D !LA'E <D@= A= KKD< &LAR' <>@= <>@== ?= KKDD S&%TT A=== <= KDA1 'IN) @=== @==== ?= KD>> TURNER ?@== = A= KDKB ADA(S ??== <= K1== ;A(ES 1@= A= K1=< %RD A=== <= K1A> (ILLER ?A== ?A=== ?= <hen you issue the followin! query3 which value will be displayed in the first rowP SELE&T empno R%( emp $HERE deptno - ?= %RDER !" ename DES&: .$ )0LLE+ -$ :(FE C$ :G:J ,$ /o rows will be returned because ename cannot be used in the %RDER !" clause$ &C' +efer to the listin! of records in the E)% table in question ($ ;ow many rows will the followin! query returnP SELE&T 6 R%( emp $HERE ename !ET$EEN ,A, AND ,&, .$ E -$ 1 C$ . character column cannot be used in the !ET$EEN operator$ ,$ F &&' +efer to the E)% table in question 1$ <hen you issue the followin! query3 which line has an errorP SELE&T empno JEnum2erJH ename JEmpNameJ R%( emp $HERE deptno - ?= AND JEnum2erJ - KKD< %RDER !" JEnum2erJ: .$ 1 -$ H C$ E ,$ /o error? the statement will finish successfully$ &)' 9ou issue the followin! query: SELE&T empnoH ename R%( emp $HERE empno - KKD< %R empno - KDKB: <hich other operator can replace the %R condition in the $HERE clauseP .$ IN -$ !ET$EEN .. AND .. C$ LI'E ,$ .- E$ 8- &5' The followin! are clauses of the SELE&T statement: 1$ $HERE 1$ R%( F$ %RDER !" 0n which order should they appear in a queryP .$ 13 F3 1 -$ 13 13 F C$ 13 F3 1 ,$ The order of these clauses does not matter$ &7' <hich statement searches for %+",ACT>0, values that be!in with ,0> from the "+,E+S tableP A. SELE&T 6 R%( %RDERS !. $HERE #R%DU&T/ID - ,DIQ,: C$ D. SELE&T 6 R%( %RDERS E. $HERE #R%DU&T/ID LI'E ,DI/, ES&A#E ,R,: D$ ). SELE&T 6 R%( %RDERS H. $HERE #R%DU&T/ID LI'E ,DIR/Q, ES&A#E ,R,: 0$ ;. SELE&T 6 R%( %RDERS '. $HERE #R%DU&T/ID LI'E ,DIR/, ES&A#E ,R,: L$ (. SELE&T 6 R%( %RDERS N. $HERE #R%DU&T/ID LI'E ,DI/Q, ES&A#E ,R,: "$ &8' C"A/T+9>/.)E and +E=0"/>0, are valid column names in the C"A/T+0ES table$ <hich one of the followin! statements will execute without an errorP A. SELE&T countrI/nameH reCion/idH !. &ASE reCion/id - ? THEN ,Europe,H &. reCion/id - < THEN ,America,H D. reCion/id - A THEN ,A3ia,H E. ELSE ,%ther, END &ontinent . R%( countrie3: =$ H. SELE&T countrI/nameH reCion/idH I. &ASE OreCion/id $HEN ? THEN ,Europe,H ;. $HEN < THEN ,America,H '. $HEN A THEN ,A3ia,H L. ELSE ,%ther,P &ontinent (. R%( countrie3: /$ %. SELE&T countrI/nameH reCion/idH #. &ASE reCion/id $HEN ? THEN ,Europe, 7. $HEN < THEN ,America, R. $HEN A THEN ,A3ia, S. ELSE ,%ther, END &ontinent T. R%( countrie3: A$ +. SELE&T countrI/nameH reCion/idH $. &ASE reCion/id $HEN ? THEN ,Europe, *. $HEN < THEN ,America, ". $HEN A THEN ,A3ia, W. ELSE ,%ther, &ontinent AA. R%( countrie3: --$ &9' <hich special character is used to query all the columns from the table without listin! each column by nameP .$ Q -$ X C$ Y ,$ 6 &:' The E)%L"9EE table has the followin! data: E(#/NA(E HIRE/DATE SALAR" 4444444444 444444444 4444444444 S(ITH ?K4DE&41= D== ALLEN <=4E!41? ?B== $ARD <<4E!41? ?<@= ;%NES =<4A#R41? @1K@ $ARDEN <D4SE#41? ?<@= !LA'E =?4(A"41? <D@= <hat will be the value in the first row of the result set when the followin! query is executedP SELE&T hire/date R%( emploIee %RDER !" 3alarIH emp/name: .$ 218.%+8(1 -$ 1:8,EC8(2 C$ 1G8SE%8(1 ,$ The query is invalid3 because you cannot have a column in the %RDER !" clause that is not part of the SELE&T clause$ &@' <hich SQL statement will query the E)%L"9EES table for D0+ST>/.)E3 L.ST>/.)E3 and S.L.+9 of all employees in ,E%.+T)E/T>0, E2 in the alphabetical order of last nameP A. SELE&T fir3t/name la3t/name 3alarI !. R%( emploIee3 &. %RDER !" la3t/name D. $HERE department/id - >=: E$ . SELE&T fir3t/nameH la3t/nameH 3alarI ). R%( emploIee3 H. %RDER !" la3t/name AS& I. $HERE department/id - >=: 7$ '. SELE&T fir3t/name la3t/name 3alarI L. R%( emploIee3 (. $HERE department/id - >= N. %RDER !" la3t/name AS&: "$ #. SELE&T fir3t/nameH la3t/nameH 3alarI 7. R%( emploIee3 R. $HERE department/id - >= S. %RDER !" la3t/name: T$ U. SELE&T fir3t/nameH la3t/nameH 3alarI +. R%( TA!LE emploIee3 $. $HERE department/id IS >= *. %RDER !" la3t/name AS&: 9$ &9' <hen doin! pattern matchin! usin! the LI'E operator3 which character is used as the default escape character by "racleP .$ W -$ 6 C$ S ,$ There is no default escape character in "racle(i$ )C' Column alias names cannot be used in which clauseP .$ SELE&T clause -$ $HERE clause C$ %RDER !" clause ,$ /one of the above ,ns>ers &' C$ Column alias names enclosed in quotation mar4s will appear as typed$ Spaces and mixed case appear in the column alias name only when the alias is enclosed in double quotation mar4s$ )' .$ Statements 1 and 1 will produce the same result$ 9ou can use the column name3 column alias3 or column position in the %RDER !" clause$ The default sort order is ascendin!$ Dor a descendin! sort3 you must explicitly specify that order with the DES& 4eyword$ 5' -$ 0n the arithmetic evaluation3 multiplication and division have precedence over addition and subtraction$ Even if you do not include the parentheses3 3alarI6=.? will be evaluated first$ The result is then divided by 13 and its result is added to 122$ 7' .3 C$ Character literals in the SQL statement are enclosed in sin!le quotation mar4s$ Literals are concatenated usin! 00$ Employee /ame: is a character literal3 and 12 is a numeric literal$ 8' -$ Since the numeric column is defined with precision : and scale 13 you can have five di!its in the inte!er part and two di!its after the decimal point$ The di!its after the decimal are rounded$ 9' -$ The default display format of the ,.TE column is DDM!N""3 whose len!th is ($ This is A$S$ specific and will be different as user settin!s vary$ :' ,$ DISTIN&T is used to display a unique result row3 and it should follow immediately after the 4eyword SELE&T$ Aniqueness is identified across the row3 not a sin!le column$ @' -$ The $HERE clause is used to limit the rows returned from a query$ The $HERE clause condition is evaluated3 and rows are returned only if the result is TRUE$ The %RDER !" clause is used to display the result in certain order$ 9' -$ There are three records belon!in! to ,E%T/" 12: E)%/" :(FE &)0LLE+'3 :GF( &T0/='3 and ::G1 &CL.+T'$ <hen you sort their names by descendin! order3 )0LLE+ is the first row to display$ 9ou can use alias names and columns that are not in the SELE&T clause in the %RDER !" clause$ &C' ,$ ;ere3 a character column is compared a!ainst a strin! usin! the !ET$EEN operator3 which is equivalent to ename 8- ,A, AND ename .- ,&,$ The name CL.+T will not be included in this query3 because ,&LAR', is 8 ,&,$ &&' C$ Column alias names cannot be used in the $HERE clause$ They can be used in the %RDER !" clause$ &)' .$ The IN operator can be used$ 9ou can write the $HERE clause as +E"E empno I$ -::@)4 :@:90D &5' -$ The R%( clause appears after the SELE&T statement3 followed by $HERE and %RDER !" clauses$ The R%( clause specifies the table names3 the $HERE clause limits the result set3 and the %RDER !" clause sorts the result$ &7' C$ Since > is a special pattern8matchin! character3 you need to include the ES&A#E clause in LI'E$ The R character matches any number of characters includin! 23 and > matches a sin!le character$ &8' C$ . &ASE expression be!ins with the 4eyword &ASE and ends with 4eyword END$ &9' ,$ .n asteris4 &6' is used to denote all columns in a table$ &:' -$ The default sortin! order for numeric column is ascendin!$ The columns are sorted first by salary and then by name3 so the row with the lowest salary is displayed first$ 0t is perfectly valid to use a column in the %RDER !" clause that is not part of the SELE&T clause$ &@' ,$ 0n the SELE&T clause3 the column names should be separated by commas$ .n alias name may be provided for each column with a space or usin! the 4eyword AS$ The R%( clause should appear after the SELE&T clause$ The $HERE clause appears after the R%( clause$ The %RDER !" clause comes after the $HERE clause$ &9' ,$ There is no default escape character in "racle(i$ 0f your search includes pattern8matchin! characters such as > or Q3 define an escape character usin! the ES&A#E 4eyword in the LI'E operator$ )C' -$ Column alias names cannot be used in the $HERE clause of the SQL statement$ 0n the %RDER !" clause3 you can use the column name or alias name3 or indicate the column by its position in the SELE&T clause$