Presentacion Oracle SQL
Presentacion Oracle SQL
Objectives
Aftercompletingthislesson,youshouldbeableto
dothefollowing:
RetrievingDataUsing
theSQLSELECT Statement
LessonAgenda
BasicSELECT statement
ArithmeticexpressionsandNULL valuesintheSELECT
statement
Columnaliases
Useofconcatenationoperator,literalcharacterstrings,
alternativequoteoperator,andtheDISTINCT keyword
DESCRIBE command
d
ListthecapabilitiesofSQLSELECT statements
ExecuteabasicSELECT statement
CapabilitiesofSQLSELECT
Statements
Projection
Selection
Table1
Table1
Join
Table1
BasicSELECT Statement
SELECT *|{[DISTINCT] column|expression [alias],...}
FROM
table;
Table2
SelectingAllColumns
SELECT *
FROM
departments;
SELECT identifiesthecolumnstobedisplayed.
FROM identifiesthetablecontainingthosecolumns.
2/5/2013
SelectingSpecificColumns
SELECT department_id, location_id
FROM
departments;
WritingSQLStatements
SQLstatementsarenotcasesensitive.
SQLstatementscanbeenteredononeormorelines.
Keywordscannotbeabbreviatedorsplitacrosslines.
Clausesareusuallyplacedonseparatelines.
Indentsareusedtoenhancereadability.
In SQL Developer SQL statements can optionally be
InSQLDeveloper,SQLstatementscanoptionallybe
terminatedbyasemicolon(;).Semicolonsarerequired
whenyouexecutemultipleSQLstatements.
InSQL*Plus,youarerequiredtoendeachSQL
statementwithasemicolon(;).
ColumnHeadingDefaults
SQLDeveloper:
Defaultheadingalignment:Leftaligned
Defaultheadingdisplay:Uppercase
SQL*Plus:
CharacterandDatecolumnheadingsareleftaligned.
Numbercolumnheadingsareright
Number column headings are rightaligned
aligned.
Defaultheadingdisplay:Uppercase
ArithmeticExpressions
Createexpressionswithnumberanddatedatabyusing
arithmeticoperators.
Operator
BasicSELECT statement
ArithmeticexpressionsandNULL valuesintheSELECT
statement
ColumnAliases
Useofconcatenationoperator,literalcharacterstrings,
alternativequoteoperator,andtheDISTINCT keyword
DESCRIBE command
d
UsingArithmeticOperators
SELECT last_name, salary, salary + 300
FROM
employees;
Description
Add
Subtract
LessonAgenda
Multiply
/
Divide
2/5/2013
OperatorPrecedence
SELECT last_name, salary, 12*salary+100
FROM
employees;
DefiningaNullValue
1
Nullisavaluethatisunavailable,unassigned,unknown,
orinapplicable.
Nullisnotthesameaszeroorablankspace.
SELECT last_name, job_id, salary, commission_pct
FROM
O
e
employees;
p oyees;
LessonAgenda
NullValuesinArithmeticExpressions
Arithmeticexpressionscontaininganullvalueevaluatetonull.
SELECT last_name, 12*salary*commission_pct
FROM
employees;
BasicSELECT statement
ArithmeticexpressionsandNULL valuesintheSELECT
statement
Columnaliases
Useofconcatenationoperator,literalcharacterstrings,
alternativequoteoperator,andtheDISTINCT keyword
DESCRIBE command
d
DefiningaColumnAlias
UsingColumnAliases
Acolumnalias:
Renamesacolumnheading
Isusefulwithcalculations
Immediatelyfollowsthecolumnname(Therecanalsobethe
optionalAS keywordbetweenthecolumnnameandalias.)
Requiresdoublequotationmarksifitcontainsspacesor
specialcharacters,orifitiscasesensitive
l h
f
2/5/2013
LessonAgenda
BasicSELECT Statement
ArithmeticExpressionsandNULLvaluesinSELECT
statement
ColumnAliases
Useofconcatenationoperator,literalcharacterstrings,
alternativequoteoperator,andtheDISTINCT keyword
DESCRIBE command
d
ConcatenationOperator
Aconcatenationoperator:
Linkscolumnsorcharacterstringstoothercolumns
Isrepresentedbytwoverticalbars(||)
Createsaresultantcolumnthatisacharacterexpression
SELECT
FROM
LiteralCharacterStrings
Aliteralisacharacter,anumber,oradatethatisincludedin
theSELECT statement.
Dateandcharacterliteralvaluesmustbeenclosedwithin
singlequotationmarks.
Eachcharacterstringisoutputonceforeachrowreturned.
UsingLiteralCharacterStrings
SELECT last_name ||' is a '||job_id
AS "Employee Details"
FROM
employees;
AlternativeQuote(q)Operator
Specifyyourownquotationmarkdelimiter.
Selectanydelimiter.
Increasereadabilityandusability.
SELECT department_name || ' Department' ||
q'['s Manager Id: ]'
|| manager_id
AS "Department and Manager"
FROM departments;
DuplicateRows
Thedefaultdisplayofqueriesisallrows,includingduplicate
rows.
SELECT department_id
FROM
employees;
2/5/2013
LessonAgenda
BasicSELECT statement
ArithmeticexpressionsandNULL valuesintheSELECT
statement
Columnaliases
Useofconcatenationoperator,literalcharacterstrings,
alternativequoteoperator,andtheDISTINCT keyword
DESCRIBE command
d
UsingtheDESCRIBE Command
DisplayingtheTableStructure
UsetheDESCRIBE commandtodisplaythestructure
ofatable.
Or,selectthetableintheConnectionstreeandusethe
Columnstabtoviewthetablestructure.
DESC[RIBE] tablename
Summary
Inthislesson,youshouldhavelearnedhowto:
DESCRIBE employees
WriteaSELECT statementthat:
Returnsallrowsandcolumnsfromatable
Returnsspecifiedcolumnsfromatable
Usescolumnaliasestodisplaymoredescriptivecolumn
headings
Practice1:Overview
Thispracticecoversthefollowingtopics:
Selectingalldatafromdifferenttables
Describingthestructureoftables
Performingarithmeticcalculationsandspecifying
columnnames
2/5/2013
RestrictingandSortingData
2/5/2013
Objectives
Aftercompletingthislesson,youshouldbeableto
dothefollowing:
Limittherowsthatareretrievedbyaquery
Sorttherowsthatareretrievedbyaquery
Useampersandsubstitutiontorestrictandsortoutput
at run time
atruntime
LimitingRowsUsingaSelection
EMPLOYEES
LessonAgenda
Limitingrowswith:
The WHERE clause
Thecomparisonconditionsusing=,<=,BETWEEN,IN,
LIKE,andNULL conditions
LogicalconditionsusingAND,OR,andNOT operators
Rulesofprecedenceforoperatorsinanexpression
p
p
p
SortingrowsusingtheORDER BY clause
Substitutionvariables
DEFINE andVERIFY commands
LimitingtheRowsthatAreSelected
RestricttherowsthatarereturnedbyusingtheWHERE
clause:
SELECT*|{[DISTINCT]column|expression [alias],...}
FROMtable
[WHEREcondition(s)];
TheWHERE
The WHERE clausefollowstheFROM
clause follows the FROM clause.
clause
retrieve all
employees in
department 90
UsingtheWHERE Clause
SELECTemployee_id,last_name,job_id,department_id
FROMemployees
WHEREdepartment_id=90;
CharacterStringsandDates
Characterstringsanddatevaluesareenclosedwith
singlequotationmarks.
Charactervaluesarecasesensitiveanddatevaluesare
formatsensitive.
ThedefaultdatedisplayformatisDD-MON-RR.
SELECTlast_name,job_id,department_id
FROMemployees
WHERElast_name='Whalen';
SELECTlast_name
FROMemployees
WHEREhire_date='17FEB96';
2/5/2013
ComparisonOperators
Operator
Meaning
Equal to
>
Greater than
>=
SELECTlast_name,salary
FROMemployees
WHEREsalary<=3000;
<
Less than
<=
<>
Not equal to
BETWEEN
...AND...
IN(set)
LIKE
ISNULL
Is a null value
RangeConditionsUsingtheBETWEEN
Operator
UsetheBETWEEN operatortodisplayrowsbasedonarangeof
values:
Lower limit
UsetheIN operatortotestforvaluesinalist:
Upper limit
PatternMatchingUsingtheLIKE
Operator
UsetheLIKE operatortoperformwildcard
searchesofvalidsearchstringvalues.
Searchconditionscancontaineitherliteral
charactersornumbers:
% denoteszeroormanycharacters.
_ denotes
denotesonecharacter.
one character.
first_name
employees
first_nameLIKE'S%';
MembershipConditionUsingtheIN
Operator
SELECTemployee_id,last_name,salary,manager_id
FROMemployees
WHEREmanager_idIN(100,101,201);
SELECTlast_name,salary
FROMemployees
WHEREsalaryBETWEEN2500AND3500;
SELECT
FROM
WHERE
UsingComparisonOperators
CombiningWildcardCharacters
Youcancombinethetwowildcardcharacters(%,_)
withliteralcharactersforpatternmatching:
SELECTlast_name
FROMemployees
WHERElast_nameLIKE'_o%';
YoucanusetheESCAPE identifiertosearchforthe
actual% and_ symbols.
2/5/2013
UsingtheNULL Conditions
DefiningConditionsUsingtheLogical
Operators
SELECTlast_name,manager_id
FROMemployees
WHEREmanager_idISNULL;
OR
NOT
UsingtheAND Operator
AND requiresboththecomponentconditionstobetrue:
SELECTemployee_id,last_name,job_id,salary
FROMemployees
WHEREsalary>=10000
ANDjob_idLIKE'%MAN%';
Meaning
AND
UsingtheOR Operator
OR requireseithercomponentconditiontobetrue:
SELECTemployee_id,last_name,job_id,salary
FROMemployees
WHEREsalary>=10000
ORjob_idLIKE'%MAN%';
UsingtheNOT Operator
LessonAgenda
Limitingrowswith:
TheWHERE clause
Thecomparisonconditionsusing=,<=,BETWEEN,IN,
LIKE,andNULL operators
LogicalconditionsusingAND,OR,andNOT operators
SELECTlast_name,job_id
FROMemployees
WHEREjob_id
NOTIN('IT_PROG','ST_CLERK','SA_REP');
Rulesofprecedenceforoperatorsinanexpression
p
p
p
SortingrowsusingtheORDER BY clause
Substitutionvariables
DEFINE andVERIFY commands
2/5/2013
RulesofPrecedence
Operator
RulesofPrecedence
SELECTlast_name,job_id,salary
FROMemployees
WHEREjob_id='SA_REP'
ORjob_id='AD_PRES'
ANDsalary>15000;
Meaning
Arithmetic operators
Concatenation operator
Comparison conditions
IS [NOT] NULL,
NULL LIKE,
LIKE [NOT] IN
[NOT] BETWEEN
Not equal to
OR logical condition
SELECTlast_name,job_id,salary
FROMemployees
WHERE(job_id='SA_REP'
ORjob_id='AD_PRES')
ANDsalary>15000;
UsingtheORDER BY Clause
LessonAgenda
Limitingrowswith:
SortretrievedrowswiththeORDER BY clause:
TheWHERE clause
Thecomparisonconditionsusing=,<=,BETWEEN,IN,
LIKE,andNULL operators
LogicalconditionsusingAND,OR,andNOT operators
Rulesofprecedenceforoperatorsinanexpression
p
p
p
SortingrowsusingtheORDER BY clause
Substitutionvariables
DEFINE andVERIFY commands
ASC:Ascendingorder,default
DESC:Descendingorder
Sorting
Sorting
Sortingbyusingthecolumnsnumericposition:
Sortingindescendingorder:
SELECTlast_name,job_id,department_id,hire_date
FROMemployees
ORDERBYhire_dateDESC;
SELECTlast_name,job_id,department_id,hire_date
FROMemployees
ORDERBY3;
Sortingbymultiplecolumns:
SELECTemployee_id,last_name,salary*12annsal
Sortingbycolumnalias:
FROMemployees
ORDERBYannsal;
SELECTlast_name,department_id,salary
FROMemployees
ORDERBYdepartment_id,salaryDESC;
10
2/5/2013
LessonAgenda
SubstitutionVariables
Limitingrowswith:
TheWHERE clause
Thecomparisonconditionsusing=,<=,BETWEEN,IN,
LIKE,andNULL operators
LogicalconditionsusingAND,OR,andNOT operators
Rulesofprecedenceforoperatorsinanexpression
p
p
p
SortingrowsusingtheORDER BY clause
Substitutionvariables
DEFINE andVERIFY commands
SubstitutionVariables
Usesubstitutionvariablesto:
Temporarilystorevalueswithsingleampersand(&)anddouble
ampersand(&&)substitution
Usesubstitutionvariablestosupplementthefollowing:
WHERE conditions
ORDER BY clauses
Columnexpressions
Tablenames
EntireSELECT statements
UsingtheSingleAmpersand
SubstitutionVariable
... salary = ?
department_id = ?
... last_name = ? ...
I want
to query
different
values.
UsingtheSingleAmpersand
SubstitutionVariable
Useavariableprefixedwithanampersand(&)topromptthe
userforavalue:
SELECTemployee_id,last_name,salary,department_id
FROMemployees
WHEREemployee_id=&employee_num;
CharacterandDateValueswith
SubstitutionVariables
Usesinglequotationmarksfordateandcharactervalues:
SELECTlast_name,department_id,salary*12
FROMemployees
WHEREjob_id='&job_title';
11
2/5/2013
SpecifyingColumnNames,
Expressions,andText
SELECTemployee_id,last_name,job_id,&column_name
FROMemployees
WHERE&condition
ORDERBY&order_column;
UsingtheDoubleAmpersand
SubstitutionVariable
Usedoubleampersand(&&)ifyouwanttoreusethevariable
valuewithoutpromptingtheusereachtime:
SELECTemployee_id,last_name,job_id,&&column_name
FROMemployees
ORDERBY&column_name;
LessonAgenda
Limitingrowswith:
TheWHERE clause
Thecomparisonconditionsusing=,<=,BETWEEN,IN,
LIKE,andNULL operators
LogicalconditionsusingAND,OR,andNOT operators
Rulesofprecedenceforoperatorsinanexpression
p
p
p
SortingrowsusingtheORDER BY clause
Substitutionvariables
DEFINE andVERIFY commands
UsingtheDEFINE Command
UsetheDEFINE commandtocreateandassignavalue
toavariable.
UsetheUNDEFINE commandtoremoveavariable.
DEFINEemployee_num=200
SELECTemployee_id,last_name,salary,department_id
FROMemployees
WHEREemployee_id=&employee_num;
UNDEFINEemployee_num
UsingtheVERIFY Command
UsetheVERIFY commandtotogglethedisplayofthe
substitutionvariable,bothbeforeandafterSQL
Developerreplacessubstitutionvariableswithvalues:
SETVERIFYON
SELECTemployee_id,last_name,salary
FROM
FROMemployees
employees
WHEREemployee_id=&employee_num;
Summary
Inthislesson,youshouldhavelearnedhowto:
UsetheWHERE clausetorestrictrowsofoutput:
Usethecomparisonconditions
UsetheBETWEEN,IN,LIKE,andNULL operators
ApplythelogicalAND,OR,andNOT operators
UsetheORDER BY clausetosortrowsofoutput:
p
SELECT*|{[DISTINCT]column|expression [alias],...}
FROMtable
[WHEREcondition(s)]
[ORDERBY{column,expr,alias}[ASC|DESC]];
Useampersandsubstitutiontorestrictandsortoutput
at
runtime
12
2/5/2013
Practice2:Overview
Thispracticecoversthefollowingtopics:
Selectingdataandchangingtheorderoftherows
thataredisplayed
RestrictingrowsbyusingtheWHERE clause
SortingrowsbyusingtheORDER BY clause
Usingsubstitutionvariablestoaddflexibilitytoyour
Using substitution variables to add flexibility to your
SQLSELECT statements
13