lesson02 学会使用where、order by子句

38
2-1 Copyright © 2011, www.OracleOnLinux.cn. Part rights reserved. Oracle OCP Oracle OCP Oracle OCP Oracle OCP 考试系列培训 1Z0-007 Lesson 1Z0-007 Lesson 1Z0-007 Lesson 1Z0-007 Lesson2 2 www.OracleOnLinux.cn www.OracleOnLinux.cn www.OracleOnLinux.cn www.OracleOnLinux.cn

Upload: renguzi

Post on 25-May-2015

1.666 views

Category:

Technology


6 download

DESCRIPTION

Oracle OCP考试之007第2章,学会使用WHERE、ORDER BY子句!

TRANSCRIPT

Page 1: Lesson02 学会使用WHERE、ORDER BY子句

2-1 Copyright © 2011, www.OracleOnLinux.cn. Part rights reserved.

Oracle OCPOracle OCPOracle OCPOracle OCP 考试系列培训之

1Z0-007 Lesson1Z0-007 Lesson1Z0-007 Lesson1Z0-007 Lesson2222www.OracleOnLinux.cnwww.OracleOnLinux.cnwww.OracleOnLinux.cnwww.OracleOnLinux.cn

Page 2: Lesson02 学会使用WHERE、ORDER BY子句

2222Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.2-2

Restricting and Sorting DataRestricting and Sorting DataRestricting and Sorting DataRestricting and Sorting Data

Page 3: Lesson02 学会使用WHERE、ORDER BY子句

2-3 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

ObjectivesObjectivesObjectivesObjectives

After completing this lesson, you should be able to do After completing this lesson, you should be able to do After completing this lesson, you should be able to do After completing this lesson, you should be able to do the following:the following:the following:the following:• Limit the rows that are retrieved by a queryLimit the rows that are retrieved by a queryLimit the rows that are retrieved by a queryLimit the rows that are retrieved by a query• Sort the rows that are retrieved by a querySort the rows that are retrieved by a querySort the rows that are retrieved by a querySort the rows that are retrieved by a query

Page 4: Lesson02 学会使用WHERE、ORDER BY子句

2-4 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

Limiting Rows Using a SelectionLimiting Rows Using a SelectionLimiting Rows Using a SelectionLimiting Rows Using a Selection

““““retrieve allretrieve allretrieve allretrieve allemployees in employees in employees in employees in department 90department 90department 90department 90””””

EMPLOYEESEMPLOYEESEMPLOYEESEMPLOYEES

…………

Page 5: Lesson02 学会使用WHERE、ORDER BY子句

2-5 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

Limiting the Rows That Are SelectedLimiting the Rows That Are SelectedLimiting the Rows That Are SelectedLimiting the Rows That Are Selected

• Restrict the rows that are returned by using the Restrict the rows that are returned by using the Restrict the rows that are returned by using the Restrict the rows that are returned by using the WHEREWHEREWHEREWHERE clause: clause: clause: clause:

• The The The The WHEREWHEREWHEREWHERE clause follows the clause follows the clause follows the clause follows the FROMFROMFROMFROM clause clause clause clause....

SELECT SELECT SELECT SELECT ****|{[DISTINCT] |{[DISTINCT] |{[DISTINCT] |{[DISTINCT] column|expressioncolumn|expressioncolumn|expressioncolumn|expression [ [ [ [aliasaliasaliasalias],...}],...}],...}],...}FROM FROM FROM FROM tabletabletabletable[WHERE [WHERE [WHERE [WHERE condition(s)condition(s)condition(s)condition(s)];];];];

Page 6: Lesson02 学会使用WHERE、ORDER BY子句

2-6 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

SELECT employee_id, last_name, job_id, department_idSELECT employee_id, last_name, job_id, department_idSELECT employee_id, last_name, job_id, department_idSELECT employee_id, last_name, job_id, department_idFROM employeesFROM employeesFROM employeesFROM employeesWHERE department_id = 90 ;WHERE department_id = 90 ;WHERE department_id = 90 ;WHERE department_id = 90 ;

Using the Using the Using the Using the WHEREWHEREWHEREWHERE Clause Clause Clause Clause

Page 7: Lesson02 学会使用WHERE、ORDER BY子句

2-7 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

SELECT last_name, job_id, department_idSELECT last_name, job_id, department_idSELECT last_name, job_id, department_idSELECT last_name, job_id, department_idFROM employeesFROM employeesFROM employeesFROM employeesWHERE last_name = 'Whalen' ;WHERE last_name = 'Whalen' ;WHERE last_name = 'Whalen' ;WHERE last_name = 'Whalen' ;

Character Strings and DatesCharacter Strings and DatesCharacter Strings and DatesCharacter Strings and Dates

• Character strings and date values are enclosed by Character strings and date values are enclosed by Character strings and date values are enclosed by Character strings and date values are enclosed by single quotation marks.single quotation marks.single quotation marks.single quotation marks.

• Character values are Character values are Character values are Character values are case-sensitivecase-sensitivecase-sensitivecase-sensitive, and date , and date , and date , and date values are values are values are values are format-sensitiveformat-sensitiveformat-sensitiveformat-sensitive....

• The default date format is DD-MON-RR.The default date format is DD-MON-RR.The default date format is DD-MON-RR.The default date format is DD-MON-RR.

Page 8: Lesson02 学会使用WHERE、ORDER BY子句

2-8 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

Comparison OperatorsComparison OperatorsComparison OperatorsComparison Operators

Not equal toNot equal toNot equal toNot equal to<><><><>

Between two values (inclusive)Between two values (inclusive)Between two values (inclusive)Between two values (inclusive)BETWEENBETWEENBETWEENBETWEEN...AND......AND......AND......AND...

Match any of a list of values Match any of a list of values Match any of a list of values Match any of a list of values IN(set)IN(set)IN(set)IN(set)

Match a character pattern Match a character pattern Match a character pattern Match a character pattern LIKELIKELIKELIKE

Is a null value Is a null value Is a null value Is a null value IS NULLIS NULLIS NULLIS NULL

Less thanLess thanLess thanLess than<<<<

Less than or equal toLess than or equal toLess than or equal toLess than or equal to<=<=<=<=

Greater than or equal toGreater than or equal toGreater than or equal toGreater than or equal to>=>=>=>=

Greater thanGreater thanGreater thanGreater than>>>>

Equal toEqual toEqual toEqual to====MeaningMeaningMeaningMeaningOperatorOperatorOperatorOperator

Page 9: Lesson02 学会使用WHERE、ORDER BY子句

2-9 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

SELECT last_name, salarySELECT last_name, salarySELECT last_name, salarySELECT last_name, salaryFROM employeesFROM employeesFROM employeesFROM employeesWHERE salary <= 3000 ;WHERE salary <= 3000 ;WHERE salary <= 3000 ;WHERE salary <= 3000 ;

Using Comparison ConditionsUsing Comparison ConditionsUsing Comparison ConditionsUsing Comparison Conditions

Page 10: Lesson02 学会使用WHERE、ORDER BY子句

2-10 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

SELECT last_name, salarySELECT last_name, salarySELECT last_name, salarySELECT last_name, salaryFROM employeesFROM employeesFROM employeesFROM employeesWHERE salary BETWEEN 2500 AND 3500 ;WHERE salary BETWEEN 2500 AND 3500 ;WHERE salary BETWEEN 2500 AND 3500 ;WHERE salary BETWEEN 2500 AND 3500 ;

Using the Using the Using the Using the BETWEENBETWEENBETWEENBETWEEN Condition Condition Condition Condition

Use the Use the Use the Use the BETWEENBETWEENBETWEENBETWEEN condition to display rows based on a condition to display rows based on a condition to display rows based on a condition to display rows based on a range of values:range of values:range of values:range of values:

Lower limitLower limitLower limitLower limit Upper limitUpper limitUpper limitUpper limit

Page 11: Lesson02 学会使用WHERE、ORDER BY子句

2-11 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

SELECT employee_id, last_name, salary, manager_idSELECT employee_id, last_name, salary, manager_idSELECT employee_id, last_name, salary, manager_idSELECT employee_id, last_name, salary, manager_idFROM employeesFROM employeesFROM employeesFROM employeesWHERE manager_id IN (100, 101, 201) ;WHERE manager_id IN (100, 101, 201) ;WHERE manager_id IN (100, 101, 201) ;WHERE manager_id IN (100, 101, 201) ;

Using the Using the Using the Using the ININININ Condition Condition Condition Condition

Use the Use the Use the Use the ININININ membership condition to test for values in membership condition to test for values in membership condition to test for values in membership condition to test for values in a list:a list:a list:a list:

Page 12: Lesson02 学会使用WHERE、ORDER BY子句

2-12 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

SELECTSELECTSELECTSELECT first_namefirst_namefirst_namefirst_nameFROM FROM FROM FROM employeesemployeesemployeesemployeesWHEREWHEREWHEREWHERE first_name LIKE 'S%' ;first_name LIKE 'S%' ;first_name LIKE 'S%' ;first_name LIKE 'S%' ;

Using the Using the Using the Using the LIKELIKELIKELIKE Condition Condition Condition Condition

• Use the Use the Use the Use the LIKELIKELIKELIKE condition to perform condition to perform condition to perform condition to perform wildcard wildcard wildcard wildcard searches of valid search string values.searches of valid search string values.searches of valid search string values.searches of valid search string values.

• Search conditions can contain either literal Search conditions can contain either literal Search conditions can contain either literal Search conditions can contain either literal characters or numbers:characters or numbers:characters or numbers:characters or numbers:– %%%% denotes zero or many characters. denotes zero or many characters. denotes zero or many characters. denotes zero or many characters.– ____ denotes one character. denotes one character. denotes one character. denotes one character.

Page 13: Lesson02 学会使用WHERE、ORDER BY子句

2-13 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

• You can combine pattern-matching characters:You can combine pattern-matching characters:You can combine pattern-matching characters:You can combine pattern-matching characters:

• You can use the You can use the You can use the You can use the ESCAPEESCAPEESCAPEESCAPE identifier to search for the identifier to search for the identifier to search for the identifier to search for the actual actual actual actual %%%% and and and and ____ symbols. symbols. symbols. symbols.

SELECT last_nameSELECT last_nameSELECT last_nameSELECT last_nameFROM employeesFROM employeesFROM employeesFROM employeesWHERE last_name LIKE '_o%' ;WHERE last_name LIKE '_o%' ;WHERE last_name LIKE '_o%' ;WHERE last_name LIKE '_o%' ;

Using the Using the Using the Using the LIKELIKELIKELIKE Condition Condition Condition Condition

SELECT employee_id,last_name,job_idSELECT employee_id,last_name,job_idSELECT employee_id,last_name,job_idSELECT employee_id,last_name,job_idFROM employeesFROM employeesFROM employeesFROM employeesWHERE job_id LIKE '%SA\_%'WHERE job_id LIKE '%SA\_%'WHERE job_id LIKE '%SA\_%'WHERE job_id LIKE '%SA\_%' ESCAPE '\' ;ESCAPE '\' ;ESCAPE '\' ;ESCAPE '\' ;

Page 14: Lesson02 学会使用WHERE、ORDER BY子句

2-14 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

• You can combine pattern-matching number:You can combine pattern-matching number:You can combine pattern-matching number:You can combine pattern-matching number:SELECT last_name,salarySELECT last_name,salarySELECT last_name,salarySELECT last_name,salaryFROM employeesFROM employeesFROM employeesFROM employeesWHERE salary LIKE '1____' ;WHERE salary LIKE '1____' ;WHERE salary LIKE '1____' ;WHERE salary LIKE '1____' ;

Using the Using the Using the Using the LIKELIKELIKELIKE Condition Condition Condition Condition

Page 15: Lesson02 学会使用WHERE、ORDER BY子句

2-15 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

SELECT last_name, manager_idSELECT last_name, manager_idSELECT last_name, manager_idSELECT last_name, manager_idFROM employeesFROM employeesFROM employeesFROM employeesWHERE manager_id IS NULL ;WHERE manager_id IS NULL ;WHERE manager_id IS NULL ;WHERE manager_id IS NULL ;

Using the Using the Using the Using the NULLNULLNULLNULL Conditions Conditions Conditions Conditions

Test for nulls with the Test for nulls with the Test for nulls with the Test for nulls with the IS NULLIS NULLIS NULLIS NULL operator. operator. operator. operator.

SELECT last_name, manager_idSELECT last_name, manager_idSELECT last_name, manager_idSELECT last_name, manager_idFROM employeesFROM employeesFROM employeesFROM employeesWHERE manager_id = NULL ;WHERE manager_id = NULL ;WHERE manager_id = NULL ;WHERE manager_id = NULL ;

SELECT last_name, manager_idSELECT last_name, manager_idSELECT last_name, manager_idSELECT last_name, manager_idFROM employeesFROM employeesFROM employeesFROM employeesWHERE manager_id <> NULL ;WHERE manager_id <> NULL ;WHERE manager_id <> NULL ;WHERE manager_id <> NULL ;

Page 16: Lesson02 学会使用WHERE、ORDER BY子句

2-16 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

Logical ConditionsLogical ConditionsLogical ConditionsLogical Conditions

Returns Returns Returns Returns TRUETRUETRUETRUE if the following if the following if the following if the following condition is falsecondition is falsecondition is falsecondition is false

NOTNOTNOTNOT

Returns Returns Returns Returns TRUETRUETRUETRUE if if if if either either either either component component component component condition is truecondition is truecondition is truecondition is true

OROROROR

Returns Returns Returns Returns TRUETRUETRUETRUE if if if if both both both both component component component component conditions are trueconditions are trueconditions are trueconditions are true

ANDANDANDAND

MeaningMeaningMeaningMeaningOperatorOperatorOperatorOperator

Page 17: Lesson02 学会使用WHERE、ORDER BY子句

2-17 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

SELECT employee_id, last_name, job_id, salarySELECT employee_id, last_name, job_id, salarySELECT employee_id, last_name, job_id, salarySELECT employee_id, last_name, job_id, salaryFROM employeesFROM employeesFROM employeesFROM employeesWHERE salary >=10000WHERE salary >=10000WHERE salary >=10000WHERE salary >=10000AND job_id LIKE '%MAN%' ;AND job_id LIKE '%MAN%' ;AND job_id LIKE '%MAN%' ;AND job_id LIKE '%MAN%' ;

Using the Using the Using the Using the ANDANDANDAND Operator Operator Operator Operator

ANDANDANDAND requires both conditions to be true: requires both conditions to be true: requires both conditions to be true: requires both conditions to be true:

Page 18: Lesson02 学会使用WHERE、ORDER BY子句

2-18 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

SELECT employee_id, last_name, job_id, salarySELECT employee_id, last_name, job_id, salarySELECT employee_id, last_name, job_id, salarySELECT employee_id, last_name, job_id, salaryFROM employeesFROM employeesFROM employeesFROM employeesWHERE salary >= 10000WHERE salary >= 10000WHERE salary >= 10000WHERE salary >= 10000OR job_id LIKE '%MAN%' ;OR job_id LIKE '%MAN%' ;OR job_id LIKE '%MAN%' ;OR job_id LIKE '%MAN%' ;

Using the Using the Using the Using the OROROROR Operator Operator Operator Operator

OROROROR requires either condition to be true: requires either condition to be true: requires either condition to be true: requires either condition to be true:

Page 19: Lesson02 学会使用WHERE、ORDER BY子句

2-19 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

SELECT last_name, job_idSELECT last_name, job_idSELECT last_name, job_idSELECT last_name, job_idFROM employeesFROM employeesFROM employeesFROM employeesWHERE job_id WHERE job_id WHERE job_id WHERE job_id NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP') ; NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP') ; NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP') ; NOT IN ('IT_PROG', 'ST_CLERK', 'SA_REP') ;

Using the Using the Using the Using the NOTNOTNOTNOT Operator Operator Operator Operator

SELECT last_name, job_idSELECT last_name, job_idSELECT last_name, job_idSELECT last_name, job_idFROM employeesFROM employeesFROM employeesFROM employeesWHERE NOT (job_id WHERE NOT (job_id WHERE NOT (job_id WHERE NOT (job_id IN ('IT_PROG', 'ST_CLERK', 'SA_REP')) ; IN ('IT_PROG', 'ST_CLERK', 'SA_REP')) ; IN ('IT_PROG', 'ST_CLERK', 'SA_REP')) ; IN ('IT_PROG', 'ST_CLERK', 'SA_REP')) ;

Page 20: Lesson02 学会使用WHERE、ORDER BY子句

2-20 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

Rules of PrecedenceRules of PrecedenceRules of PrecedenceRules of Precedence

You can use parentheses to override rules of precedence.You can use parentheses to override rules of precedence.You can use parentheses to override rules of precedence.You can use parentheses to override rules of precedence.

Not equal toNot equal toNot equal toNot equal to6666NOTNOTNOTNOT logical condition logical condition logical condition logical condition7777ANDANDANDAND logical condition logical condition logical condition logical condition8888

OROROROR logical condition logical condition logical condition logical condition9999

ISISISIS [NOT][NOT][NOT][NOT] NULLNULLNULLNULL, , , , LIKELIKELIKELIKE, , , , [NOT][NOT][NOT][NOT] ININININ4444[NOT] BETWEEN[NOT] BETWEEN[NOT] BETWEEN[NOT] BETWEEN5555

Comparison conditionsComparison conditionsComparison conditionsComparison conditions3333Concatenation operatorConcatenation operatorConcatenation operatorConcatenation operator2222Arithmetic operatorsArithmetic operatorsArithmetic operatorsArithmetic operators1111MeaningMeaningMeaningMeaningOperatorOperatorOperatorOperator

Page 21: Lesson02 学会使用WHERE、ORDER BY子句

2-21 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

SELECT last_name, job_id, salarySELECT last_name, job_id, salarySELECT last_name, job_id, salarySELECT last_name, job_id, salaryFROM employeesFROM employeesFROM employeesFROM employeesWHERE job_id = 'SA_REP'WHERE job_id = 'SA_REP'WHERE job_id = 'SA_REP'WHERE job_id = 'SA_REP'OR job_id = 'AD_PRES'OR job_id = 'AD_PRES'OR job_id = 'AD_PRES'OR job_id = 'AD_PRES'AND salary > 15000;AND salary > 15000;AND salary > 15000;AND salary > 15000;

Rules of PrecedenceRules of PrecedenceRules of PrecedenceRules of Precedence

SELECT last_name, job_id, salarySELECT last_name, job_id, salarySELECT last_name, job_id, salarySELECT last_name, job_id, salaryFROM employeesFROM employeesFROM employeesFROM employeesWHERE WHERE WHERE WHERE ((((job_id = 'SA_REP'job_id = 'SA_REP'job_id = 'SA_REP'job_id = 'SA_REP'OR job_id = 'AD_PRES'OR job_id = 'AD_PRES'OR job_id = 'AD_PRES'OR job_id = 'AD_PRES'))))AND salary > 15000;AND salary > 15000;AND salary > 15000;AND salary > 15000;

1111

2222

Page 22: Lesson02 学会使用WHERE、ORDER BY子句

2-22 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

Using the Using the Using the Using the ORDER BYORDER BYORDER BYORDER BY Clause Clause Clause Clause

• Sort retrieved rows with the Sort retrieved rows with the Sort retrieved rows with the Sort retrieved rows with the ORDER BYORDER BYORDER BYORDER BY clause: clause: clause: clause:– ASCASCASCASC: ascending order, default: ascending order, default: ascending order, default: ascending order, default– DESCDESCDESCDESC: descending order: descending order: descending order: descending order

• The The The The ORDER BYORDER BYORDER BYORDER BY clause comes last in the clause comes last in the clause comes last in the clause comes last in the SELECTSELECTSELECTSELECT statementstatementstatementstatement::::

SELECT last_name, job_id, department_id, hire_dateSELECT last_name, job_id, department_id, hire_dateSELECT last_name, job_id, department_id, hire_dateSELECT last_name, job_id, department_id, hire_dateFROM employeesFROM employeesFROM employeesFROM employeesORDER BY hire_date ;ORDER BY hire_date ;ORDER BY hire_date ;ORDER BY hire_date ;

…………

Page 23: Lesson02 学会使用WHERE、ORDER BY子句

2-23 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

SortingSortingSortingSorting

• Sorting in descending order:Sorting in descending order:Sorting in descending order:Sorting in descending order:

• Sorting by column alias:Sorting by column alias:Sorting by column alias:Sorting by column alias:

• Sorting by multiple columns:Sorting by multiple columns:Sorting by multiple columns:Sorting by multiple columns:

SELECT last_name, job_id, department_id, hire_dateSELECT last_name, job_id, department_id, hire_dateSELECT last_name, job_id, department_id, hire_dateSELECT last_name, job_id, department_id, hire_dateFROM employeesFROM employeesFROM employeesFROM employeesORDER BY hire_date DESC ;ORDER BY hire_date DESC ;ORDER BY hire_date DESC ;ORDER BY hire_date DESC ; 1111

SELECT employee_id, last_name, salarySELECT employee_id, last_name, salarySELECT employee_id, last_name, salarySELECT employee_id, last_name, salary****12 annsal12 annsal12 annsal12 annsalFROM employeesFROM employeesFROM employeesFROM employeesORDER BY annsal ;ORDER BY annsal ;ORDER BY annsal ;ORDER BY annsal ;

2222

SELECT last_name, department_id, salarySELECT last_name, department_id, salarySELECT last_name, department_id, salarySELECT last_name, department_id, salaryFROM employeesFROM employeesFROM employeesFROM employeesORDER BY department_id, salary DESC;ORDER BY department_id, salary DESC;ORDER BY department_id, salary DESC;ORDER BY department_id, salary DESC;

3333

Page 24: Lesson02 学会使用WHERE、ORDER BY子句

2-24 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

Substitution VariablesSubstitution VariablesSubstitution VariablesSubstitution Variables

... salary = ? ... salary = ? ... salary = ? ... salary = ? …………………… department_id = ? department_id = ? department_id = ? department_id = ? ………… ... last_name = ? ...... last_name = ? ...... last_name = ? ...... last_name = ? ...

I want I want I want I want to query to query to query to query different different different different values.values.values.values.

Page 25: Lesson02 学会使用WHERE、ORDER BY子句

2-25 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

Substitution VariablesSubstitution VariablesSubstitution VariablesSubstitution Variables

• Use Use Use Use iiiiSQLSQLSQLSQL****Plus substitution variables to:Plus substitution variables to:Plus substitution variables to:Plus substitution variables to:– Temporarily store values with single-ampersand ( Temporarily store values with single-ampersand ( Temporarily store values with single-ampersand ( Temporarily store values with single-ampersand (&&&&) ) ) )

and double-ampersandand double-ampersandand double-ampersandand double-ampersand ((((&&&&&&&&) substitution) substitution) substitution) substitution• Use substitution variables to supplement the Use substitution variables to supplement the Use substitution variables to supplement the Use substitution variables to supplement the

following:following:following:following:– WHEREWHEREWHEREWHERE conditions conditions conditions conditions– ORDER BYORDER BYORDER BYORDER BY clauses clauses clauses clauses– Column expressionsColumn expressionsColumn expressionsColumn expressions– Table namesTable namesTable namesTable names– Entire Entire Entire Entire SELECTSELECTSELECTSELECT statements statements statements statements

Page 26: Lesson02 学会使用WHERE、ORDER BY子句

2-26 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

SELECT employee_id, last_name, salary, department_idSELECT employee_id, last_name, salary, department_idSELECT employee_id, last_name, salary, department_idSELECT employee_id, last_name, salary, department_idFROM employeesFROM employeesFROM employeesFROM employeesWHERE employee_id = &employee_num ;WHERE employee_id = &employee_num ;WHERE employee_id = &employee_num ;WHERE employee_id = &employee_num ;

Using the Using the Using the Using the &&&& Substitution Variable Substitution Variable Substitution Variable Substitution Variable

Use a variable prefixed with an ampersand (Use a variable prefixed with an ampersand (Use a variable prefixed with an ampersand (Use a variable prefixed with an ampersand (&&&&) to ) to ) to ) to prompt the user for a value:prompt the user for a value:prompt the user for a value:prompt the user for a value:

Page 27: Lesson02 学会使用WHERE、ORDER BY子句

2-27 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

Using the Using the Using the Using the &&&& Substitution Variable Substitution Variable Substitution Variable Substitution Variable

101101101101

11112222

Page 28: Lesson02 学会使用WHERE、ORDER BY子句

2-28 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

SELECT last_name, department_id, salarySELECT last_name, department_id, salarySELECT last_name, department_id, salarySELECT last_name, department_id, salary****12121212FROM employeesFROM employeesFROM employeesFROM employeesWHERE job_id = '&job_title' ;WHERE job_id = '&job_title' ;WHERE job_id = '&job_title' ;WHERE job_id = '&job_title' ;

Character and Date Values Character and Date Values Character and Date Values Character and Date Values with Substitution Variableswith Substitution Variableswith Substitution Variableswith Substitution Variables

Use single quotation marks for date and character Use single quotation marks for date and character Use single quotation marks for date and character Use single quotation marks for date and character values:values:values:values:

Page 29: Lesson02 学会使用WHERE、ORDER BY子句

2-29 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

Specifying Column Names, Specifying Column Names, Specifying Column Names, Specifying Column Names, Expressions, and TextExpressions, and TextExpressions, and TextExpressions, and Text

SELECT employee_id, last_name, job_id,&column_nameSELECT employee_id, last_name, job_id,&column_nameSELECT employee_id, last_name, job_id,&column_nameSELECT employee_id, last_name, job_id,&column_nameFROM employeesFROM employeesFROM employeesFROM employeesWHERE &conditionWHERE &conditionWHERE &conditionWHERE &conditionORDER BY &order_column ;ORDER BY &order_column ;ORDER BY &order_column ;ORDER BY &order_column ;

salarysalarysalarysalary

salary > 15000salary > 15000salary > 15000salary > 15000

last_namelast_namelast_namelast_name

Page 30: Lesson02 学会使用WHERE、ORDER BY子句

2-30 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

SELECT employee_id, last_name, job_id, &&column_nameSELECT employee_id, last_name, job_id, &&column_nameSELECT employee_id, last_name, job_id, &&column_nameSELECT employee_id, last_name, job_id, &&column_nameFROM employeesFROM employeesFROM employeesFROM employeesORDER BY &column_name ;ORDER BY &column_name ;ORDER BY &column_name ;ORDER BY &column_name ;

…………

Using the Using the Using the Using the &&&&&&&& Substitution Variable Substitution Variable Substitution Variable Substitution Variable

Use the double ampersand (Use the double ampersand (Use the double ampersand (Use the double ampersand (&&&&&&&&) if you want to reuse ) if you want to reuse ) if you want to reuse ) if you want to reuse the variable value without prompting the user each the variable value without prompting the user each the variable value without prompting the user each the variable value without prompting the user each time:time:time:time:

Page 31: Lesson02 学会使用WHERE、ORDER BY子句

2-31 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

Using the Using the Using the Using the iiiiSQLSQLSQLSQL****Plus Plus Plus Plus DEFINEDEFINEDEFINEDEFINE Command Command Command Command

• Use the Use the Use the Use the iiiiSQLSQLSQLSQL****Plus Plus Plus Plus DEFINEDEFINEDEFINEDEFINE command to create and command to create and command to create and command to create and assign a value to a variable.assign a value to a variable.assign a value to a variable.assign a value to a variable.

• Use the Use the Use the Use the iiiiSQLSQLSQLSQL****Plus Plus Plus Plus UNDEFINEUNDEFINEUNDEFINEUNDEFINE command to remove command to remove command to remove command to remove a variable. a variable. a variable. a variable.

DEFINE employee_num = 200DEFINE employee_num = 200DEFINE employee_num = 200DEFINE employee_num = 200

SELECT employee_id, last_name, salary, department_idSELECT employee_id, last_name, salary, department_idSELECT employee_id, last_name, salary, department_idSELECT employee_id, last_name, salary, department_idFROM employeesFROM employeesFROM employeesFROM employeesWHERE employee_id = &employee_num ;WHERE employee_id = &employee_num ;WHERE employee_id = &employee_num ;WHERE employee_id = &employee_num ;

UNDEFINE employee_numUNDEFINE employee_numUNDEFINE employee_numUNDEFINE employee_num

Page 32: Lesson02 学会使用WHERE、ORDER BY子句

2-32 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

old 3: WHERE employee_id = &employee_numold 3: WHERE employee_id = &employee_numold 3: WHERE employee_id = &employee_numold 3: WHERE employee_id = &employee_numnew 3: WHERE employee_id = 200new 3: WHERE employee_id = 200new 3: WHERE employee_id = 200new 3: WHERE employee_id = 200

SET VERIFY ONSET VERIFY ONSET VERIFY ONSET VERIFY ONSELECT employee_id, last_name, salary, department_idSELECT employee_id, last_name, salary, department_idSELECT employee_id, last_name, salary, department_idSELECT employee_id, last_name, salary, department_idFROM employeesFROM employeesFROM employeesFROM employeesWHERE employee_id = &employee_num;WHERE employee_id = &employee_num;WHERE employee_id = &employee_num;WHERE employee_id = &employee_num;

Using the Using the Using the Using the VERIFYVERIFYVERIFYVERIFY Command Command Command Command

Use the Use the Use the Use the VERIFYVERIFYVERIFYVERIFY command to toggle the display of the command to toggle the display of the command to toggle the display of the command to toggle the display of the substitution variable, both before and after substitution variable, both before and after substitution variable, both before and after substitution variable, both before and after iiiiSQLSQLSQLSQL****Plus Plus Plus Plus replaces substitution variables with values:replaces substitution variables with values:replaces substitution variables with values:replaces substitution variables with values:

Page 33: Lesson02 学会使用WHERE、ORDER BY子句

2-33 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

SELECT SELECT SELECT SELECT ****|{[DISTINCT] |{[DISTINCT] |{[DISTINCT] |{[DISTINCT] column|expressioncolumn|expressioncolumn|expressioncolumn|expression [ [ [ [aliasaliasaliasalias],...}],...}],...}],...}FROM FROM FROM FROM tabletabletabletable[WHERE [WHERE [WHERE [WHERE condition(s)condition(s)condition(s)condition(s)]]]][ORDER BY {[ORDER BY {[ORDER BY {[ORDER BY {column, expr, aliascolumn, expr, aliascolumn, expr, aliascolumn, expr, alias} [ASC|DESC]] ;} [ASC|DESC]] ;} [ASC|DESC]] ;} [ASC|DESC]] ;

SummarySummarySummarySummary

In this lesson, you should have learned how to: In this lesson, you should have learned how to: In this lesson, you should have learned how to: In this lesson, you should have learned how to: • Use the Use the Use the Use the WHEREWHEREWHEREWHERE clause to restrict rows of output: clause to restrict rows of output: clause to restrict rows of output: clause to restrict rows of output:

– Use the comparison conditionsUse the comparison conditionsUse the comparison conditionsUse the comparison conditions– Use the Use the Use the Use the BETWEENBETWEENBETWEENBETWEEN, , , , ININININ, , , , LIKELIKELIKELIKE, and , and , and , and NULLNULLNULLNULL conditions conditions conditions conditions– Apply the logical Apply the logical Apply the logical Apply the logical ANDANDANDAND, , , , OROROROR, and , and , and , and NOTNOTNOTNOT operators operators operators operators

• Use the Use the Use the Use the ORDER BYORDER BYORDER BYORDER BY clause to sort rows of output: clause to sort rows of output: clause to sort rows of output: clause to sort rows of output:

• Use ampersand substitution in Use ampersand substitution in Use ampersand substitution in Use ampersand substitution in iiiiSQLSQLSQLSQL****Plus to Plus to Plus to Plus to restrict and sort output at run time restrict and sort output at run time restrict and sort output at run time restrict and sort output at run time

Page 34: Lesson02 学会使用WHERE、ORDER BY子句

2-34 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

Practice 2: OverviewPractice 2: OverviewPractice 2: OverviewPractice 2: Overview

This practice covers the following topics:This practice covers the following topics:This practice covers the following topics:This practice covers the following topics:• Selecting data and changing the order ofSelecting data and changing the order ofSelecting data and changing the order ofSelecting data and changing the order of

the rows that are displayedthe rows that are displayedthe rows that are displayedthe rows that are displayed• Restricting rows by using the Restricting rows by using the Restricting rows by using the Restricting rows by using the WHEREWHEREWHEREWHERE clause clause clause clause• Sorting rows by using the Sorting rows by using the Sorting rows by using the Sorting rows by using the ORDER BYORDER BYORDER BYORDER BY clause clause clause clause• Using substitution variables to add flexibility to Using substitution variables to add flexibility to Using substitution variables to add flexibility to Using substitution variables to add flexibility to

your SQL your SQL your SQL your SQL SELECTSELECTSELECTSELECT statements statements statements statements

Page 35: Lesson02 学会使用WHERE、ORDER BY子句

2-35 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

Practice 2Practice 2Practice 2Practice 2Q1:The EMPLOYEES table contains these columns:Q1:The EMPLOYEES table contains these columns:Q1:The EMPLOYEES table contains these columns:Q1:The EMPLOYEES table contains these columns:EMPLOYEE_ID NUMBER(4) EMPLOYEE_ID NUMBER(4) EMPLOYEE_ID NUMBER(4) EMPLOYEE_ID NUMBER(4) LAST_NAME VARCHAR2 (25) LAST_NAME VARCHAR2 (25) LAST_NAME VARCHAR2 (25) LAST_NAME VARCHAR2 (25) JOB_ID VARCHAR2(10) JOB_ID VARCHAR2(10) JOB_ID VARCHAR2(10) JOB_ID VARCHAR2(10) You want to search for strings that contain 'SA_' in the JOB_ID You want to search for strings that contain 'SA_' in the JOB_ID You want to search for strings that contain 'SA_' in the JOB_ID You want to search for strings that contain 'SA_' in the JOB_ID column. Which SQL statement do you use? column. Which SQL statement do you use? column. Which SQL statement do you use? column. Which SQL statement do you use?

AAAA. SELECT employee_id, last_name, job_id . SELECT employee_id, last_name, job_id . SELECT employee_id, last_name, job_id . SELECT employee_id, last_name, job_id FROM employees WHERE job_id LIKE '%SA\_%' ESCAPE '\'; FROM employees WHERE job_id LIKE '%SA\_%' ESCAPE '\'; FROM employees WHERE job_id LIKE '%SA\_%' ESCAPE '\'; FROM employees WHERE job_id LIKE '%SA\_%' ESCAPE '\'; B. SELECT employee_id, last_name, job_id B. SELECT employee_id, last_name, job_id B. SELECT employee_id, last_name, job_id B. SELECT employee_id, last_name, job_id FROM employees WHERE job_id LIKE '%SA_'; FROM employees WHERE job_id LIKE '%SA_'; FROM employees WHERE job_id LIKE '%SA_'; FROM employees WHERE job_id LIKE '%SA_'; C. SELECT employee_id, last_name, job_id C. SELECT employee_id, last_name, job_id C. SELECT employee_id, last_name, job_id C. SELECT employee_id, last_name, job_id FROM employees WHERE job_id LIKE '%SA_' ESCAPE "\"; FROM employees WHERE job_id LIKE '%SA_' ESCAPE "\"; FROM employees WHERE job_id LIKE '%SA_' ESCAPE "\"; FROM employees WHERE job_id LIKE '%SA_' ESCAPE "\"; D. SELECT employee_id, last_name, job_id D. SELECT employee_id, last_name, job_id D. SELECT employee_id, last_name, job_id D. SELECT employee_id, last_name, job_id FROM employees WHERE job_id = '%SA_'; FROM employees WHERE job_id = '%SA_'; FROM employees WHERE job_id = '%SA_'; FROM employees WHERE job_id = '%SA_';

Page 36: Lesson02 学会使用WHERE、ORDER BY子句

2-36 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

Practice 2Practice 2Practice 2Practice 2QQQQ2222: The STUDENT_GRADES table has these columns: : The STUDENT_GRADES table has these columns: : The STUDENT_GRADES table has these columns: : The STUDENT_GRADES table has these columns: STUDENT_ID NUMBER(12) STUDENT_ID NUMBER(12) STUDENT_ID NUMBER(12) STUDENT_ID NUMBER(12) SEMESTER_END DATE SEMESTER_END DATE SEMESTER_END DATE SEMESTER_END DATE GPA NUMBER(4,3) GPA NUMBER(4,3) GPA NUMBER(4,3) GPA NUMBER(4,3) The registrar requested a report listing the students' grade point The registrar requested a report listing the students' grade point The registrar requested a report listing the students' grade point The registrar requested a report listing the students' grade point averages (GPA) sorted from highest grade point average to lowest. averages (GPA) sorted from highest grade point average to lowest. averages (GPA) sorted from highest grade point average to lowest. averages (GPA) sorted from highest grade point average to lowest. Which statement produces a report that displays the student ID Which statement produces a report that displays the student ID Which statement produces a report that displays the student ID Which statement produces a report that displays the student ID and GPA in the sorted order requested by the registrar? and GPA in the sorted order requested by the registrar? and GPA in the sorted order requested by the registrar? and GPA in the sorted order requested by the registrar? A. SELECT student_id, gpa FROM student_grades A. SELECT student_id, gpa FROM student_grades A. SELECT student_id, gpa FROM student_grades A. SELECT student_id, gpa FROM student_grades ORDER BY gpa ASC; ORDER BY gpa ASC; ORDER BY gpa ASC; ORDER BY gpa ASC; B. SELECT student_id, gpa FROM student_grades B. SELECT student_id, gpa FROM student_grades B. SELECT student_id, gpa FROM student_grades B. SELECT student_id, gpa FROM student_grades SORT ORDER BY gpa ASC; SORT ORDER BY gpa ASC; SORT ORDER BY gpa ASC; SORT ORDER BY gpa ASC; C. SELECT student_id, gpa FROM student_grades C. SELECT student_id, gpa FROM student_grades C. SELECT student_id, gpa FROM student_grades C. SELECT student_id, gpa FROM student_grades SORT ORDER BY gpa; SORT ORDER BY gpa; SORT ORDER BY gpa; SORT ORDER BY gpa; D. SELECT student_id, gpa FROM student_grades D. SELECT student_id, gpa FROM student_grades D. SELECT student_id, gpa FROM student_grades D. SELECT student_id, gpa FROM student_grades ORDER BY gpa; ORDER BY gpa; ORDER BY gpa; ORDER BY gpa; E. SELECT student_id, gpa FROM student_grades E. SELECT student_id, gpa FROM student_grades E. SELECT student_id, gpa FROM student_grades E. SELECT student_id, gpa FROM student_grades SORT ORDER BY gpa DESC; SORT ORDER BY gpa DESC; SORT ORDER BY gpa DESC; SORT ORDER BY gpa DESC; FFFF. SELECT student_id, gpa FROM student_grades . SELECT student_id, gpa FROM student_grades . SELECT student_id, gpa FROM student_grades . SELECT student_id, gpa FROM student_grades ORDER BY gpa DESC; ORDER BY gpa DESC; ORDER BY gpa DESC; ORDER BY gpa DESC;

Page 37: Lesson02 学会使用WHERE、ORDER BY子句

2-37 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

Practice 2Practice 2Practice 2Practice 2QQQQ3333:Evaluate these two SQL statements: :Evaluate these two SQL statements: :Evaluate these two SQL statements: :Evaluate these two SQL statements: SELECT last_name, salary , hire_date SELECT last_name, salary , hire_date SELECT last_name, salary , hire_date SELECT last_name, salary , hire_date FROM EMPLOYEES FROM EMPLOYEES FROM EMPLOYEES FROM EMPLOYEES ORDER BY salary DESC; ORDER BY salary DESC; ORDER BY salary DESC; ORDER BY salary DESC; SELECT last_name, salary , hire_date SELECT last_name, salary , hire_date SELECT last_name, salary , hire_date SELECT last_name, salary , hire_date FROM EMPLOYEES FROM EMPLOYEES FROM EMPLOYEES FROM EMPLOYEES ORDER BY 2 DESC; ORDER BY 2 DESC; ORDER BY 2 DESC; ORDER BY 2 DESC; What is true about them? What is true about them? What is true about them? What is true about them? AAAA. The two statements produce identical results. . The two statements produce identical results. . The two statements produce identical results. . The two statements produce identical results. B. The second statement returns a syntax error. B. The second statement returns a syntax error. B. The second statement returns a syntax error. B. The second statement returns a syntax error. C. There is no need to specify DESC because the results are C. There is no need to specify DESC because the results are C. There is no need to specify DESC because the results are C. There is no need to specify DESC because the results are sorted in descending order by default. sorted in descending order by default. sorted in descending order by default. sorted in descending order by default. D. The two statements can be made to produce identical results D. The two statements can be made to produce identical results D. The two statements can be made to produce identical results D. The two statements can be made to produce identical results by adding a column alias for the salary column by adding a column alias for the salary column by adding a column alias for the salary column by adding a column alias for the salary column in the second SQL statement. in the second SQL statement. in the second SQL statement. in the second SQL statement.

Page 38: Lesson02 学会使用WHERE、ORDER BY子句

2-38 Copyright © 2011, www.OracleOnLinuxOracleOnLinuxOracleOnLinuxOracleOnLinux.cn. Part rights reserved.

Practice 2Practice 2Practice 2Practice 2QQQQ4444: Examine this statement: : Examine this statement: : Examine this statement: : Examine this statement: SELECT student_id, gpa SELECT student_id, gpa SELECT student_id, gpa SELECT student_id, gpa FROM student_grades FROM student_grades FROM student_grades FROM student_grades WHERE gpa > &&value; WHERE gpa > &&value; WHERE gpa > &&value; WHERE gpa > &&value; You run the statement once, and when prompted you enter a value You run the statement once, and when prompted you enter a value You run the statement once, and when prompted you enter a value You run the statement once, and when prompted you enter a value of 2.0. A report is produced. What happens when you run the of 2.0. A report is produced. What happens when you run the of 2.0. A report is produced. What happens when you run the of 2.0. A report is produced. What happens when you run the statement a second time? statement a second time? statement a second time? statement a second time? A. An error is returned. A. An error is returned. A. An error is returned. A. An error is returned. B. You are prompted to enter a new value. B. You are prompted to enter a new value. B. You are prompted to enter a new value. B. You are prompted to enter a new value. CCCC. A report is produced that matches the first report produced. . A report is produced that matches the first report produced. . A report is produced that matches the first report produced. . A report is produced that matches the first report produced. D. You are asked whether you want a new value or if you want to D. You are asked whether you want a new value or if you want to D. You are asked whether you want a new value or if you want to D. You are asked whether you want a new value or if you want to run the report based on the previous value. run the report based on the previous value. run the report based on the previous value. run the report based on the previous value.