Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 2Ć2Schedule: Timing Topic 35 minutes Lecture 30 minutes Practice 65 minutes Total Class Management Note: Demonstration l2be
Trang 1Limiting Selected Rows
2
Trang 2Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 2Ć2
Schedule: Timing Topic
35 minutes Lecture
30 minutes Practice
65 minutes Total
Class Management Note:
Demonstration l2betw.sql, l2in.sql, l2and.sql, l2or.sql, l2sal1.sql, l2sal2.sql
Practice: None
Trang 3While retrieving data from the database, you may need to restrict the rows of data that are displayed or specify the order in which the rows are displayed This lesson explains the commands you will use to perform these actions.
At the end of this lesson you should be able to
D Sort row output using the ORDER BY clause
D Enter search criteria using the WHERE clause
Trang 4Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 2Ć4
If the ORDER BY clause is not used, the sort order is undefined, and the Oracle7Server may not fetch rows in the same order for the same query twice Use theORDER BY clause to display the rows in a specific order
Trang 5Ordering Rows with the ORDER BY Clause
The order of rows returned in a query result is undefined The ORDER BY clausemay be used to sort the rows If used, you must place the ORDER BY clause last.You can specify an expression or use position to sort
Syntax
[ORDER BY {column,expr} [ASC|DESC]];
where: ORDER BY specifies the order in which the retrieved rows
Trang 6Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 2Ć6
Trang 7Ordering Rows with the ORDER BY Clause continuedDefault Ordering of Data
The default sort order is ascending:
D Numeric values are displayed with the lowest values first, for example 1-999
D Date values are displayed with the earliest value first, for example 01-JAN-92before 01-JAN-95
D Character values are displayed in alphabetical order, for example A first and Zlast
D In Oracle7, null values are displayed last for ascending sequences and first fordescending sequences
Reversing the Default Order
To reverse the order in which rows are displayed, the command word DESC is
specified after the column name in the ORDER BY clause
3 ORDER BY start_date DESC;
LAST_NAME DEPT_ID START_DAT
Trang 8Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 2Ć8
Trang 9Ordering Rows with the ORDER BY Clause continuedOrdering by Position
Another method for sorting query results is to sort by position This is especiallyuseful when sorting by a long expression Rather than typing the expression again,you can specify its position in the SELECT list
SQL> SELECT last_name, salary*12
2 FROM s_emp
3 ORDER BY 2;
Ordering by Many Columns
You can sort query results by more than one column The sort limit is the number ofcolumns in the table
In the ORDER BY clause, specify the columns, and separate the column names usingcommas If you want to reverse the order of a column, specify DESC after its name orposition You can order by columns that are not in the SELECT list
3 ORDER BY dept_id, salary DESC;
LAST_NAME DEPT_ID SALARY
Trang 10Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 2Ć10
Trang 11Limiting Selected Rows with the WHERE Clause
You can restrict the rows returned from the query by using the WHERE clause AWHERE clause contains a condition that must be met, and directly follows the
where: WHERE restricts the query to rows that meet a condition.
condition is composed of column names, expressions,
constants, and comparison operators
Comparison Operators
Comparison operators are divided into two categories: logical and SQL They areused in the WHERE clause to compare one expression to another using the followingformat
Syntax
WHERE expr operator value
Example WHERE conditions
WHERE dept_id = 42
Class Management Note:
Remind students that the expr cannot be an alias.
Trang 12Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 2Ć12
Trang 13Comparison Operators
Character Strings and Dates
Character strings and dates in the WHERE clause must be enclosed in single
quotation marks (‘ ’) Number constants, however, must not
3 WHERE last_name = ’Magee’;
FIRST_NAME LAST_NAME TITLE
- -
-Colin Magee Sales Representative
Class Management Note:
Some students may ask how to override this Later in the course, we willcover single row functions such as UPPER and LOWER to override thecase sensitivity
Trang 14Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 2Ć14
Trang 15Comparison Operators continuedComparison Operators
Logical operators test the following conditions:
BETWEEN AND Between two values (inclusive)
IN(list) Match any of a list of values
LIKE Match a character pattern
IS NULL Is a null value
Trang 16Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 2Ć16
Trang 17Negating Expressions
You may find that it is easier to find the rows that do not meet a condition, rather thanthose that do Use the comparison and SQL operators with a negative expression.Negating Logical Operators
Operator Description
!= Not equal to (VAX, UNIX, PC)
^ =
: =
Not equal to (IBM)
<> Not equal to (all operating systems)
NOT colname = Not equal to
NOT colname > Not greater than
Negating SQL Operators
Operator Description
NOT BETWEEN AND Not between two specified values
NOT IN (list) Not in specified list of values
NOT LIKE Not like comparison string
IS NOT NULL Is not a null value
If you want to compare a known value to a null value, use either IS or IS NOT NULLcomparison operators If you compare null values using the other operators, the result
is always FALSE
For example, COMMISSION_PCT! = NULL is always FALSE because a null valuemay not be either equal or unequal to any other value, even another null value Notethat an error is not raised, the result is simply always FALSE
Class Management Note:
The point here is that it may be faster and easier to eliminate rather than
Trang 18Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 2Ć18
SQL> SELECT first_name, last_name, start_date
DEMO: l2in.sql
PURPOSE: Demonstrate the use of the IN operator
Trang 19SQL Operators
The BETWEEN Operator
You can display rows based on a range of values using the BETWEEN operator Therange you specify contains a lower range and an upper range
Trang 20Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 2Ć20
SQL> SELECT last_name
2 FROM s_emp
3 WHERE last_name LIKE ’M%’;
Trang 21SQL Operators continuedThe LIKE Operator
You may not always know the exact value to search for You can select rows thatmatch a character pattern by using the LIKE operator The character pattern matching
operation is referred to as a wildcard search Two symbols can be used to construct
the search string
Symbol Description
% Represents any sequence of zero or more characters
_ Represents any single character
Trang 22Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 2Ć22
Trang 23SQL Operators continuedThe LIKE operator can be used as a shortcut for some BETWEEN comparisons.Example
Display the last name and start date for employees who started with the company in1991
SQL> SELECT last_name, start_date
2 FROM s_emp
3 WHERE start_date LIKE ’%91’;
Combine Wildcard Characters
The % and _ symbols may be used in any combination with literal characters
Example
Display the last names of employees whose last name has an “a” as the second letter
SQL> SELECT last_name
2 FROM s_emp
3 WHERE last_name LIKE ’_a%’;
The ESCAPE Option
When you need to have an exact match for the actual “%” and “_” characters, use theESCAPE option This option specifies what the ESCAPE character is
Trang 24Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 2Ć24
Trang 26Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 2Ć26
SQL> SELECT last_name, salary, dept_id, title
2 FROM s_emp
3 WHERE dept_id = 41
4 AND title = ’Stock Clerk’;
Class Management Note:
Additionally, you may want to use the truth tables to further explain this
topic See the Oracle7 Server SQL Reference, Release 7.3, “Logical
Operators” for the truth tables
Trang 27Querying Data with Multiple Conditions
You may need to specify complex criteria by combining several search conditions.The AND and OR operators may be used to make compound logical expressions.The AND operator returns TRUE if both conditions evaluate to TRUE, whereas the
OR operator returns TRUE if either condition is TRUE
In the following two examples, the conditions are the same, but the operator is
different See how the result is dramatically changed
4 OR title = ’Stock Clerk’;
Note: OR is a less restrictive clause Consequently, more rows may be returned.
For more information, see
Oracle7 Server SQL Reference, Release 7.3, “Logical Operators.”
Trang 28Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 2Ć28
Order Evaluated Operator
Trang 29Rules of Precedence
You may combine AND and OR operators in the same logical expression The results
of all of the conditions are combined in the order determined by the precedence of theconnecting operators Where operators of equal precedence are used next to eachother, they are performed from left to right
Each AND is performed first then each OR is performed AND has a higher
precedence than OR
Rules of Precedence
Order Evaluated Operator
1 All comparison operators
(=, <>, >, >=, <, <=, IN, LIKE, IS NULL, BETWEEN)
Note: When using a negating expression, comparison operators still evaluate first.
Override precedence rules by placing part of an expression in parentheses; the OracleServer evaluates expressions in parentheses first
Whenever you are in doubt about which of two operations will be performed firstwhen an expression is evaluated, use parentheses to clarify your statements
Trang 30Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 2Ć30
Class Management Note:
The parentheses specify the order in which the expressions should beevaluated In the second example, the OR operator is evaluated before theAND operator
Question: What is another way to write the WHERE clause for example 2?Answer: WHERE salary >= 1000 AND dept_id IN (44, 42)
Trang 31Rules of Precedence continued
Example 1
Display the last name, salary, and department number for those employees in
department 44 who earn 1000 or more, as well as all employees in department 42
SQL> SELECT last_name, salary, dept_id
Display the last name, salary, and department number for those employees in
department 44 or 42 who earn 1000 or more
SQL> SELECT last_name, salary, dept_id
Trang 32-Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 2Ć32
Trang 33In this lesson, you have learned about sorting rows and restricting the rows returned
by the SELECT statement You have also learned how to implement comparisonoperators
Syntax
[ORDER BY {column,expr} [ASC|DESC]];
where: SELECT is a list of at least one column
DISTINCT suppresses duplicates
* selects all columns
column selects the named column
alias gives selected columns a different heading
FROM table specifies the table containing the columns.WHERE restricts the query to rows that meet a condition
condition is composed of column names, expressions,
constants, and comparison operators
ORDER BY specifies the order in which the retrieved rows
are displayed
ASC orders rows in ascending order
DESC orders the rows in descending order
Trang 34Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 2Ć34
Trang 35Practice Overview
This practice gives you a variety of exercises using the WHERE clause and theORDER BY clause
Practice Contents
D Selecting data and changing the order of rows displayed
D Using the WHERE clause to restrict rows, with a combination of logical andSQL operators
D Using column aliases
PaperĆBased Questions
For questions 1–3, circle either True or False
Class Management Note:
Duration: 30 minutes
Please tell students that they will have to use some of the commands
learned in lesson 1
Trang 36Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 2Ć36
Trang 373 Where last_name = ’Dancs’;
3. This SELECT statement will execute successfully
True / False
SQL> select *
2 from s_emp
3 where salary*12 = 9600;
4. There are four coding errors in this statement Can you identify them?
SQL> SELECT id, last_name,
2 salary x 12 ANNUAL SALARY
3 FROM s_emp
4 WHERE sal > 3000
5 AND start_date LIKE %84;
Trang 38Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 2Ć38
5. Use the S_CUSTOMER table and perform the following actions
a. Create a query to display the name, customer number, and credit rating for all companies represented by sales representative 11 Save your SQL statement to
a file named p2q5.
b. Run your query in the file p2q5.
c. Load p2q5 into the SQL buffer Name the column headings Company,
Company ID, and Rating Rerun your query Re-save your query as p2q5.
- ––––––––––– ––––––––
Womansport 204 GOOD Beisbol Si! 209 GOOD Big John’s Sports Emporium 213 GOOD Ojibway Retail 214 GOOD d. Retrieve p2q5 into the SQL buffer Order the query results in descending order by customer number Run your query 6. Show the structure of the S_EMP table a. Display the user name for employee 23 b. Display the first name, last name, and department number of the employees in departments 10 and 50 in alphabetical order of last name Merge the first name and last name together, and title the column Employees Employees DEPT_ID -
-Mark Quick-To-See 10
Audry Ropeburn 50
Carmen Velasquez 50
c. Display all employees whose last names contain an “s.”
d. Display the user names and start date of employees hired between May 14,
1990 and May 26, 1991 Order the query results by start date ascending order
Trang 39Practice 2 continued
If you have time, complete the following exercises
7. Use the S_EMP table to perform the following actions
a. Write a query to show the last name and salary of all employees who are notmaking between 1000 and 2500 per month
b. List the last name and salary of employees who earn more than 1350 who are
in department 31, 42, or 50 Label the last name column Employee Name, andlabel the salary column Monthly Salary
c. Display the last name and start date of every employee who was hired in1991
d. Display the full name of all employees with no manager
8. Show the structure of S_PRODUCT table
a. Alphabetically display all products having a name beginning with Pro
b. Display all product names and short descriptions for all descriptions
containing the word “bicycle.”
c. Display all short descriptions Compare the results from Exercise 8b Did yourresponse in Exercise 8b return all descriptions containing bicycle?
Trang 40Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 2Ć40