Você está na página 1de 40

2

Limiting Selected Rows

Schedule:

Timing

Topic

35 minutes 30 minutes 65 minutes

Lecture Practice Total

Class Management Note:

Demonstration l2betw.sql, l2in.sql, l2and.sql, l2or.sql, l2sal1.sql, l2sal2.sql Practice: None

22

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Objectives
While 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 D

Sort row output using the ORDER BY clause. Enter search criteria using the WHERE clause.

Limiting Selected Rows

23

If the ORDER BY clause is not used, the sort order is undefined, and the Oracle7 Server may not fetch rows in the same order for the same query twice. Use the ORDER BY clause to display the rows in a specific order.

24

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Ordering Rows with the ORDER BY Clause


The order of rows returned in a query result is undefined. The ORDER BY clause may 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 SELECT expr FROM table [ORDER BY {column,expr} [ASC|DESC]]; where: ORDER BY ASC DESC Example Query the employee table for employee last name, department number, and the hire date for all employees. Sort the results by employee last name. SQL> SELECT last_name, dept_id, start_date 2 FROM s_emp 3 ORDER BY last_name; specifies the order in which the retrieved rows are displayed. orders the rows in ascending order. This is the default order. orders the rows in descending order.

LAST_NAME DEPT_ID START_DAT ------------ ------- --------Biri 43 07-APR-90 Catchpole 44 09-FEB-92 Chang 44 30-NOV-90 Dancs 45 17-MAR-91 Dumas 35 09-OCT-91 Giljum 32 18-JAN-92 Havel 45 27-FEB-91 ...

Limiting Selected Rows

25

26

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Ordering Rows with the ORDER BY Clause


Default Ordering of Data

continued

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-92 before 01-JAN-95. D Character values are displayed in alphabetical order, for example A first and Z last. D In Oracle7, null values are displayed last for ascending sequences and first for descending 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. Example Query the employee table for employee last name, department number, and the hire date for all employees. Sort the results by the most recently hired employee. SQL> SELECT 2 FROM 3 ORDER BY last_name, dept_id, start_date s_emp start_date DESC;

LAST_NAME DEPT_ID ------------ ------... Urguhart 41 Chang 44 Patel 34 Menchu 42 ... 25 rows selected.

START_DAT --------18-JAN-91 30-NOV-90 17-OCT-90 14-MAY-90

Ordering with Column Aliases You can use a column alias in the ORDER BY clause. This feature was made available in Oracle7 release 7.0.16.

Limiting Selected Rows

27

28

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Ordering Rows with the ORDER BY Clause


Ordering by Position

continued

Another method for sorting query results is to sort by position. This is especially useful 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 of columns in the table. In the ORDER BY clause, specify the columns, and separate the column names using commas. If you want to reverse the order of a column, specify DESC after its name or position. You can order by columns that are not in the SELECT list. Example Display the last name, department number, and salary of all employees. Order the result by the department number, then in descending order by salary. SQL> SELECT last name, dept_id, salary 2 FROM s_emp 3 ORDER BY dept_id, salary DESC;

LAST_NAME DEPT_ID SALARY ------------ ------- ---------Quick-To-See 10 1450 Nagayama 31 1400 Magee 31 1400 Giljum 32 1490 Sedeghi 33 1515 Nguyen 34 1525 Patel 34 795 ...

Limiting Selected Rows

29

2 10

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Limiting Selected Rows with the WHERE Clause


You can restrict the rows returned from the query by using the WHERE clause. A WHERE clause contains a condition that must be met, and directly follows the FROM clause. Syntax SELECT FROM [WHERE [ORDER BY expr table condition(s)] expr]; restricts the query to rows that meet a condition. is composed of column names, expressions, constants, and comparison operators.

where: WHERE condition Comparison Operators

Comparison operators are divided into two categories: logical and SQL. They are used in the WHERE clause to compare one expression to another using the following format. Syntax ...WHERE expr operator value

Example WHERE conditions ...WHERE dept_id = 42

Class Management Note:

Remind students that the expr cannot be an alias.

Limiting Selected Rows

2 11

2 12

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Comparison 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. Example Write a query to show the first and last names, and title for the employee named Magee. SQL> SELECT 2 FROM 3 WHERE first_name, last_name, title s_emp last_name = MAGEE;

no rows selected All character strings are case sensitive. Therefore, change the last name to be initial capitals in order to acquire a match. SQL> SELECT 2 FROM 3 WHERE first_name, last_name, title s_emp 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 will cover single row functions such as UPPER and LOWER to override the case sensitivity.

Limiting Selected Rows

2 13

2 14

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Comparison Operators
Comparison Operators Logical operators test the following conditions: Operator = > >= < <= SQL Operators There are four SQL operators that operate with all datatypes: Operator BETWEEN...AND... IN(list) LIKE IS NULL Logical Operators Operator AND OR NOT Meaning Meaning Between two values (inclusive) Match any of a list of values Match a character pattern Is a null value Meaning Equal to Greater than Greater than or equal to Less than Less than or equal to

continued

If both component conditions return TRUE, then the result is TRUE. If either component condition returns TRUE, then the result is TRUE. Returns the opposite condition.

Limiting Selected Rows

2 15

2 16

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Negating Expressions
You may find that it is easier to find the rows that do not meet a condition, rather than those that do. Use the comparison and SQL operators with a negative expression. Negating Logical Operators Operator != ^= := <> NOT colname = NOT colname > Negating SQL Operators Operator NOT BETWEEN...AND... NOT IN (list) NOT LIKE IS NOT NULL Description Not between two specified values Not in specified list of values Not like comparison string Is not a null value Description Not equal to (VAX, UNIX, PC) Not equal to (IBM) Not equal to (all operating systems) Not equal to Not greater than

If you want to compare a known value to a null value, use either IS or IS NOT NULL comparison 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 value may not be either equal or unequal to any other value, even another null value. Note that 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 include.

Limiting Selected Rows

2 17

SQL> SELECT 2 FROM 3 WHERE 4

first_name, last_name, start_date s_emp start_date BETWEEN 09-may-91 AND 17-jun-91;

Class Management Note:

DEMO: l2betw.sql PURPOSE: The standard format for dates is DD-MON-YY, and the time and century are not visible. You need to use the TO_CHAR function to see these portions of the date value, which will be covered in a later lesson. DEMO: l2in.sql PURPOSE: Demonstrate the use of the IN operator.

2 18

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

SQL Operators
The BETWEEN Operator You can display rows based on a range of values using the BETWEEN operator. The range you specify contains a lower range and an upper range. Example Display the first name, last name, and start date of employees whose start date is between May 9, 1991 and June 17, 1991, inclusive. SQL> SELECT 2 FROM 3 WHERE 4 first_name, last_name, start_date s_emp start_date BETWEEN 09-may-91 AND 17-jun-91;

Values specified with the BETWEEN operator are inclusive. You must specify the lower limit first. The IN Operator To test for values in a specified list, use the IN operator. Example Display the department number, name, and region number of departments in regions 1 or 3. SQL> SELECT 2 FROM 3 WHERE id, name, region_id s_dept region_id IN (1,3);

If characters or dates are used in the list, they must be enclosed in single quotation marks ( ).

Limiting Selected Rows

2 19

SQL> SELECT 2 FROM 3 WHERE

last_name s_emp last_name LIKE M%;

2 20

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

SQL Operators

continued

The LIKE Operator You may not always know the exact value to search for. You can select rows that match 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.

Example Display all employee last names beginning with M. SQL> SELECT FROM WHERE last_name s_emp last_name LIKE M%;

LAST_NAME -----------Menchu Magee Maduro Markarian

Example Display all employee last names that do not contain an a within the name. SQL> SELECT 2 FROM 3 WHERE last_name s_emp last_name NOT LIKE %a%;

Limiting Selected Rows

2 21

2 22

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

SQL Operators

continued

The 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 in 1991. SQL> SELECT 2 FROM 3 WHERE last_name, start_date s_emp 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 2 FROM 3 WHERE last_name s_emp last_name LIKE _a%;

The ESCAPE Option When you need to have an exact match for the actual % and _ characters, use the ESCAPE option. This option specifies what the ESCAPE character is. Example Display the names of companies whose name contains X_Y. SQL> SELECT 2 FROM 3 WHERE name s_customer name LIKE %X\_Y% ESCAPE \;

Limiting Selected Rows

2 23

2 24

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

SQL Operators

continued

IS NULL Operator The IS NULL operator tests for values that are null. A null value means the value is unavailable, unassigned, unknown, or inapplicable. Therefore, you cannot test with = because a null value cannot be equal or unequal to any value. Example Display the customer number, name, and credit rating of all customers who do not have a sales representative. SQL> SELECT 2 FROM 3 WHERE id, name, credit_rating s_customer sales_rep_id = NULL;

no rows selected

SQL> SELECT 2 FROM 3 WHERE

id, name, credit_rating s_customer sales_rep_id = ;

no rows selected

SQL> SELECT 2 FROM 3 WHERE

id, name, credit_rating s_customer sales_rep_id IS NULL;

ID NAME CREDIT_RA ------- -------------------- --------207 Sweet Rock Sports GOOD Example Display all employee last names, titles, and commission percentages who make a commission. SQL> SELECT 2 FROM 3 WHERE last_name, title, commission_pct s_emp commission_pct IS NOT NULL;

Limiting Selected Rows

2 25

SQL> 2 3 4

SELECT FROM WHERE AND

last_name, salary, dept_id, title s_emp dept_id = 41 title = Stock Clerk;

Class Management Note:

DEMO: l2and.sql PURPOSE: Demonstrate the results of using the AND operator. DEMO: l2or.sql PURPOSE: Demonstrate the results using the OR operator. Compare the results. 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.

2 26

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Querying 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. Example 1 Display the last name, salary, department number, and title for all stock clerks in department 41. SQL> 2 3 4 SELECT FROM WHERE AND last_name, salary, dept_id, title s_emp dept_id = 41 title = Stock Clerk;

Example 2 Display the last name, salary, department number, and title for all employees who are either stock clerks or who are in department 41. SQL> 2 3 4 SELECT FROM WHERE OR last_name, salary, dept_id, title s_emp dept_id = 41 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.

Limiting Selected Rows

2 27

Order Evaluated 1 2 3

Operator All comparison operators. AND OR

2 28

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Rules 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 the connecting operators. Where operators of equal precedence are used next to each other, 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 1 2 3 Operator All comparison operators (=, <>, >, >=, <, <=, IN, LIKE, IS NULL, BETWEEN) AND OR

Note: When using a negating expression, comparison operators still evaluate first. Override precedence rules by placing part of an expression in parentheses; the Oracle Server evaluates expressions in parentheses first. Whenever you are in doubt about which of two operations will be performed first when an expression is evaluated, use parentheses to clarify your statements.

Limiting Selected Rows

2 29

Class Management Note:

DEMO: l2sal1.sql PURPOSE: This first script shows that the OR condition is performed after the AND condition. DEMO: l2sal2.sql PURPOSE: This script demonstrates that the parentheses override the AND condition being evaluated first. Consequently, the OR condition is executed first, then the AND condition. Therefore, fewer rows meet both sets of conditions. The parentheses specify the order in which the expressions should be evaluated. In the second example, the OR operator is evaluated before the AND operator. Question: What is another way to write the WHERE clause for example 2? Answer: WHERE salary >= 1000 AND dept_id IN (44, 42)

2 30

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Rules of Precedence
Example 1

continued

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> 2 3 4 5 SELECT FROM WHERE AND OR last_name, salary, dept_id s_emp salary >= 1000 dept_id = 44 dept_id = 42;

LAST_NAME SALARY DEPT_ID ------------ ------------ -------Menchu 1250 42 Catchpole 1300 44 Nozaki 1200 42 Patel 795 42

Example 2 Display the last name, salary, and department number for those employees in department 44 or 42 who earn 1000 or more. SQL> 2 3 4 5 SELECT FROM WHERE AND OR last_name, salary, dept_id s_emp salary >= 1000 (dept_id = 44 dept_id = 42);

LAST_NAME SALARY DEPT_ID ------------ ------------ -------Menchu 1250 42 Catchpole 1300 44 Nozaki 1200 42

Limiting Selected Rows

2 31

2 32

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Summary
In this lesson, you have learned about sorting rows and restricting the rows returned by the SELECT statement. You have also learned how to implement comparison operators. Syntax SELECT FROM [WHERE [ORDER BY [DISTINCT] {*,column [alias],....} table condition(s)] {column,expr} [ASC|DESC]]; is a list of at least one column. suppresses duplicates. selects all columns. selects the named column. gives selected columns a different heading. specifies the table containing the columns. restricts the query to rows that meet a condition. is composed of column names, expressions, constants, and comparison operators. specifies the order in which the retrieved rows are displayed. orders rows in ascending order. orders the rows in descending order.

where: SELECT DISTINCT * column alias FROM table WHERE condition ORDER BY ASC DESC

Limiting Selected Rows

2 33

2 34

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice Overview
This practice gives you a variety of exercises using the WHERE clause and the ORDER BY clause. Practice Contents
D D

Selecting data and changing the order of rows displayed. Using the WHERE clause to restrict rows, with a combination of logical and SQL operators. Using column aliases.

Paper Based Questions For questions 13, 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.

Limiting Selected Rows

2 35

2 36

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 2
1. 2.

You cannot order by a column that you have not selected. True / False This SELECT statement will execute successfully. True / False SQL> Select 2 From 3 Where last_name, title, salary Ann_sal s_emp last_name = Dancs;

3.

This SELECT statement will execute successfully. True / False SQL> select 2 from 3 where * s_emp salary*12 = 9600;

4.

There are four coding errors in this statement. Can you identify them? SQL> 2 3 4 5 SELECT FROM WHERE AND id, last_name, salary x 12 ANNUAL SALARY s_emp sal > 3000 start_date LIKE %84;

Limiting Selected Rows

2 37

Practice 2
5.

continued

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. c.

Run your query in the file p2q5. Load p2q5 into the SQL buffer. Name the column headings Company, Company ID, and Rating. Rerun your query. Re-save your query as p2q5. Company Company ID -------------------------- Womansport 204 Beisbol Si! 209 Big Johns Sports Emporium 213 Ojibway Retail 214 Rating GOOD GOOD GOOD GOOD

d. 6.

Retrieve p2q5 into the SQL buffer. Order the query results in descending order by customer number. Run your query.

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 ----------------------------------Mark Quick-To-See Audry Ropeburn Carmen Velasquez DEPT_ID --------10 50 50

c. d.

Display all employees whose last names contain an s. 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.

2 38

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 2
If you have time, complete the following exercises.
7.

continued

Use the S_EMP table to perform the following actions.


a. b.

Write a query to show the last name and salary of all employees who are not making between 1000 and 2500 per month. 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, and label the salary column Monthly Salary. Display the last name and start date of every employee who was hired in 1991. Display the full name of all employees with no manager. Alphabetically display all products having a name beginning with Pro. Display all product names and short descriptions for all descriptions containing the word bicycle. Display all short descriptions. Compare the results from Exercise 8b. Did your response in Exercise 8b return all descriptions containing bicycle?

c. d. 8.

Show the structure of S_PRODUCT table.


a. b. c.

Limiting Selected Rows

2 39

2 40

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Você também pode gostar