Sei sulla pagina 1di 307

Introduction to Oracle: SQL

and PL/SQL Using Procedure


Builder
Volume Four S Participant Guide

Edition 1.1
M03992
T1001E11
Authors Copyright EĂOracle Corporation, 1992, 1996. All rights reserved.

Neena Kochhar This documentation contains proprietary information of Oracle Corporation; it is


provided under a license agreement containing restrictions on use and discloĆ
Debby Kramer sure and is also protected by copyright law. Reverse engineering of the software
is prohibited. If this documentation is delivered to a U.S. Government Agency of
the Department of Defense, then it is delivered with Restricted Rights and the folĆ
lowing legend is applicable:
Technical Contributors Restricted Rights Legend
and Reviewers
Use, duplication or disclosure by the Government is subject to restrictions for
Christian Bauwens commercial computer software and shall be deemed to be Restricted Rights softĆ
ware under Federal law, and as set forth in subparagraph (c) (1) (ii) of DFARS
Debra Bowman 252.227Ć7013, Rights in Technical Data and Computer Software (October 1988).
Lenny Brunson
Jackie Collins This material or any portion of it may not be copied in any form or by any means
without the express prior written permission of the Worldwide Education Services
Ralf Durben group of Oracle Corporation. Any other copying is a violation of copyright law and
Brian Fry may result in civil and/or criminal penalties.
Anthony Holbrook If this documentation is delivered to a U.S. Government Agency not within the DeĆ
Karlene Jensen partment of Defense, then it is delivered with Restricted Rights," as defined in
Sarah Jones FAR 52.227Ć14, Rights in DataĆGeneral, including Alternate III (June 1987).
Glenn Maslen The information in this document is subject to change without notice. If you find
Sundar Nagarathnam any problems in the documentation, please report them in writing to Worldwide
Education Services, Oracle Corporation, 500 Oracle Parkway, Box 659806, RedĆ
Sandra Schrick wood Shores, CA 94065. Oracle Corporation does not warrant that this document
Ulrike Schwinn is error free.
Rosemarie Truman
SQL*Plus, PL/SQL, Procedure Builder, Developer/2000, Oracle7 Server, Oracle
Jenny Tsai Server, Discoverer/2000, and Designer/2000 are trademarks or registered tradeĆ
Laura Van Deusen marks of Oracle Corporation.

All other products or company names are used for identification purposes only,
and may be trademarks of their respective owners.

Publishers
Stephanie Jones
Kimberly Lee
Jennifer Robertson
Mark Turangan
A

Practice Solutions
AĆ2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Preface
There is often more than one way to achieve any result in SQL. Where possible, the
alternatives have been identified in these solutions. The performance benefits, if any,
are also mentioned. If you want to analyze any of the statements, refer to SQL*Trace.
This facility allows you to see how the SQL statement is being interpreted at the
database level.
For more information, see
Oracle7 Server SQL Reference, Release 7.3 and Oracle7 Server Administrators
Guide.

Practice Solutions AĆ3


Practice 1 Solutions
1. SQL commands are always held in a buffer.
" True
2. SQL*Plus commands assist with querying data.
" False
SQL*Plus commands allow you to format resulting data and control files.
Only SQL accesses the database.
3. Show the structure of the S_DEPT table. Select all information from the
S_DEPT table.

SQL> DESCRIBE s_dept


Name Null? Type
---------------------------- -------- ----
ID NOT NULL NUMBER(7)
NAME NOT NULL VARCHAR2(25)
REGION_ID NUMBER(7)

SQL> SELECT *
2 FROM s_dept;

ID NAME REGION_ID
--------- ------------------------- ---------
10 Finance 1
31 Sales 1
32 Sales 2
33 Sales 3
34 Sales 4
35 Sales 5
41 Operations 1
42 Operations 2
43 Operations 3
44 Operations 4
45 Operations 5
50 Administration 1

12 rows selected.

AĆ4 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 1 Solutions continued

4. Show the structure of the S_CUSTOMER table. Using this table, perform the
following actions:

SQL> DESCRIBE s_customer


Name Null? Type
-------------------------- -------- ----
ID NOT NULL NUMBER(7)
NAME NOT NULL VARCHAR2(50)
PHONE VARCHAR2(25)
ADDRESS VARCHAR2(400)
CITY VARCHAR2(30)
STATE VARCHAR2(20)
COUNTRY VARCHAR2(30)
ZIP_CODE VARCHAR2(75)
CREDIT_RATING VARCHAR2(9)
SALES_REP_ID NUMBER(7)
REGION_ID NUMBER(7)
COMMENTS VARCHAR2(255)

a. Retrieve all information from the S_CUSTOMER table.

SQL> SELECT *
2 FROM s_customer;

Continued

Practice Solutions AĆ5


Practice 1 Solutions continued

4.—continued
b. Display the name and phone number for each customer.

SQL> SELECT name, phone


2 FROM s_customer;

NAME PHONE
----------------------------------- --------------
Unisports 55-2066101
Simms Atheletics 81-20101
Delhi Sports 91-10351
Womansport 1-206-104-0103
Kam’s Sporting Goods 852-3692888
Sportique 33-2257201
Sweet Rock Sports 234-6036201
Muench Sports 49-527454
Beisbol Si! 809-352689
Futbol Sonora 52-404562
Kuhn’s Sports 42-111292
Hamada Sport 20-1209211
Big John’s Sports Emporium 1-415-555-6281
Ojibway Retail 1-716-555-7171
Sporta Russia 7-3892456

15 rows selected.

Continued

AĆ6 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 1 Solutions continued

4.—continued
c. Display the phone number and name for each customer, with phone number
appearing first.

SQL> SELECT phone, name


2 FROM s_customer;

PHONE NAME
-------------------- -------------------------
55-2066101 Unisports
81-20101 Simms Atheletics
91-10351 Delhi Sports
1-206-104-0103 Womansport
852-3692888 Kam’s Sporting Goods
33-2257201 Sportique
234-6036201 Sweet Rock Sports
49-527454 Muench Sports
809-352689 Beisbol Si!
52-404562 Futbol Sonora
42-111292 Kuhn’s Sports
20-1209211 Hamada Sport
1-415-555-6281 Big John’s Sports Emporium
1-716-555-7171 Ojibway Retail
7-3892456 Sporta Russia

15 rows selected.

Practice Solutions AĆ7


Practice 2 Solutions
1. You cannot order by a column that you have not selected.
" False
2. This SELECT statement will execute successfully.
" True

SQL> SELECT last_name, title, salary Ann_sal


2 FROM s_emp
3 WHERE last_name = ’Dancs’;

3. This SELECT statement will execute successfully.


" True

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;

" No SAL column in existence (WHERE clause).


" The ANNUAL SALARY alias cannot include spaces. Alias should read
ANNUAL_SALARY or be enclosed by quotation marks.
" The multiplication operator is *, not x as shown in line 2.
" All values when using the LIKE operator should be enclosed within single
quotation marks. The value should read ‘%84’ in line 5.

AĆ8 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 2 Solutions continued

5. Use the S_CUSTOMER table to 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.

SQL> SELECT name, id, credit_rating


2 FROM s_customer
3 WHERE sales_rep_id = 11
4
SQL> SAVE p2q5
Created file p2q5

b. Run your query in the file p2q5.

SQL> START p2q5


NAME ID CREDIT_RA
------------------------------ --------- ---------
Womansport 204 EXCELLENT
Beisbol Si! 209 EXCELLENT
Big John’s Sports Emporium 213 EXCELLENT
Ojibway Retail 214 POOR

Continued

Practice Solutions AĆ9


Practice 2 Solutions continued

5.—continued
c. Load p2q5 into the SQL buffer. Name the column headings Company,
Company ID, and Rating. Rerun your query. Resave your query as p2q5.
" Solution file: p2q5.sql

SQL> GET p2q5


1 SELECT name, id, credit_rating
2 FROM s_customer
3* WHERE sales_rep_id = 11
SQL> 1 SELECT name ”Company”, id ”Company ID”,
SQL> i credit_rating ”Rating”
SQL> RUN
1 SELECT name ”Company”, id ”Company ID”,
2 credit_rating ”Rating”
3 FROM s_customer
4* WHERE sales_rep_id = 11

Company Company ID Rating


------------------------------ ---------- ---------
Womansport 204 EXCELLENT
Beisbol Si! 209 EXCELLENT
Big John’s Sports Emporium 213 EXCELLENT
Ojibway Retail 214 POOR
SQL> SAVE p2q5 REPLACE
Wrote file p2q5

Continued

AĆ10 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 2 Solutions continued

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

SQL> GET p2q5


1 SELECT name ”Company”, id ”Company ID”,
2 credit_rating ”Rating”
3 FROM s_customer
4* WHERE sales_rep_id = 11
SQL> i ORDER BY 2 DESC
SQL> /
Company Company ID Rating
------------------------------ ---------- ---------
Ojibway Retail 214 POOR
Big John’s Sports Emporium 213 EXCELLENT
Beisbol Si! 209 EXCELLENT
Womansport 204 EXCELLENT

6. Show the structure of the S_EMP table.

SQL> DESCRIBE s_emp


Name Null? Type
-------------------------- -------- ----
ID NOT NULL NUMBER(7)
LAST_NAME NOT NULL VARCHAR2(25)
FIRST_NAME VARCHAR2(25)
USERID NOT NULL VARCHAR2(8)
START_DATE DATE
COMMENTS VARCHAR2(255)
MANAGER_ID NUMBER(7)
TITLE VARCHAR2(25)
DEPT_ID NUMBER(7)
SALARY NUMBER(11,2)
COMMISSION_PCT NUMBER(4,2)

Practice Solutions AĆ11


Practice 2 Solutions continued

6.—continued
a. Display the user name for employee 23.

SQL> SELECT userid


2 FROM s_emp
3 WHERE id = 23;

USERID
--------
rpatel

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.

SQL> SELECT first_name||’ ’||last_name


2 ”Employees”, dept_id
3 FROM s_emp
4 WHERE dept_id IN (10,50)
5 ORDER BY last_name;

Employees DEPT_ID
------------------------------------ ---------
Mark Quick-To-See 10
Audry Ropeburn 50
Carmen Velasquez 50

Continued

AĆ12 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 2 Solutions continued

6.—continued
c. Display all employees whose last names contain an “s”.
" This solution is not quite complete because names that contain a capital
S do not appear in this list. In a later lesson, you will see how to change
your query into a case-insensitive query.

SQL> SELECT first_name, last_name


2 FROM s_emp
3 WHERE last_name like ’%s%’;

FIRST_NAME LAST_NAME
------------------------- ------------------------
Carmen Velasquez
Andre Dumas
Bela Dancs

d. Display the user names and start date of employees hired between May 5,
1990 and May 26, 1991. Order the query results by start date ascending order.

SQL> SELECT userid, start_date


2 FROM s_emp
3 WHERE start_date BETWEEN ’05-may-90’
4 AND ’26-may-91’
5 ORDER BY start_date;

Continued

Practice Solutions AĆ13


Practice 2 Solutions continued

6d.—continued

USERID START_DAT
-------- ---------
rmenchu 14-MAY-90
cmagee 14-MAY-90
rpatel 17-OCT-90
echang 30-NOV-90
murguhar 18-JAN-91
anozaki 09-FEB-91
ysedeghi 18-FEB-91
mhavel 27-FEB-91
bdancs 17-MAR-91
sschwart 09-MAY-91
amarkari 26-MAY-91

11 rows selected.

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 not
making between 1000 and 2500 per month.

SQL> SELECT last_name, salary


2 FROM s_emp
3 WHERE salary NOT BETWEEN 1000 AND 2500;

LAST_NAME SALARY
------------------------- ---------
Smith 940
Patel 795
Newman 750
Markarian 850
Chang 800
Patel 795
Dancs 860

7 rows selected.

Continued

AĆ14 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 2 Solutions continued

7.—continued
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, and
label the salary column Monthly Salary.

SQL> SELECT last_name ”Employee Name”,


2 salary ”Monthly Salary”
3 FROM s_emp
4 WHERE salary > 1350
5 AND dept_id IN (31, 42, 50);

Employee Name Monthly Salary


------------------------- --------------
Velasquez 2500
Nagayama 1400
Ropeburn 1550
Magee 1400

c. Display the last name and start date of every employee who was hired in
1991.

SQL> SELECT last_name, start_date


2 FROM s_emp
3 WHERE start_date LIKE ’%91’;

Continued

Practice Solutions AĆ15


Practice 2 Solutions continued

7c.—continued

LAST_NAME START_DAT
------------------------- ---------
Nagayama 17-JUN-91
Urguhart 18-JAN-91
Havel 27-FEB-91
Sedeghi 18-FEB-91
Dumas 09-OCT-91
Nozaki 09-FEB-91
Patel 06-AUG-91
Newman 21-JUL-91
Markarian 26-MAY-91
Dancs 17-MAR-91
Schwartz 09-MAY-91

11 rows selected.

d. Display the full name of all employees with no manager.

SQL> SELECT first_name, last_name


2 FROM s_emp
3 WHERE manager_id IS NULL;

FIRST_NAME LAST_NAME
------------------------- -------------------------
Carmen Velasquez

AĆ16 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 2 Solutions continued

8. Show the structure of the S_PRODUCT table.

SQL> DESCRIBE s_product


Name Null? Type
------------------------- -------- ----
ID NOT NULL NUMBER(7)
NAME NOT NULL VARCHAR2(50)
SHORT_DESC VARCHAR2(255)
LONGTEXT_ID NUMBER(7)
IMAGE_ID NUMBER(7)
SUGGESTED_WHLSL_PRICE NUMBER(11,2)
WHLSL_UNITS VARCHAR2(25)

a. Alphabetically display all products having a name beginning with Pro.

SQL> SELECT name


2 FROM s_product
3 WHERE name LIKE ’Pro%’;

NAME
-------------------------------------------------
-
Pro Curling Bar
Pro Ski Boot
Pro Ski Pole
Prostar 10 Pound Weight
Prostar 100 Pound Weight
Prostar 20 Pound Weight
Prostar 50 Pound Weight
Prostar 80 Pound Weight

8 rows selected.

Continued

Practice Solutions AĆ17


Practice 2 Solutions continued

8.—continued
b. Display all product names and short descriptions for all descriptions
containing the word bicycle.
" Results have been formatted.

SQL> SELECT name, short_desc


2 FROM s_product
3 WHERE short_desc LIKE ’%bicycle%’

NAME SHORT_DESC
------------------------- --------------------
Grand Prix Bicycle Road bicycle
Himalaya Bicycle Mountain bicycle
Grand Prix Bicycle Tires Road bicycle tires
Himalaya Tires Mountain bicycle tires

c. Display all short descriptions. Compare the results from Exercise 10b. Did
your response in Exercise 10b return all descriptions containing “bicycle”?
" No, not all words containing “bicycle” were returned because the
WHERE clause is case-sensitive. In a later lesson, you will see how to
remove the case-sensitivity.

SQL> SELECT short_desc


2 FROM s_product
3 ORDER BY 1;

Continued

AĆ18 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 2 Solutions continued

8c.—continued

SHORT_DESC
---------------------------------------------
Advanced ski boot
Advanced ski pole
Baseball
Batting helmet
Beginner’s ski boot
Beginner’s ski pole
Bicycle helmet
Catcher’s glove
Curling bar
Eighty pound weight
Elbow pads, pair
Fifty pound weight
Infielder’s glove
Intermediate ski boot
Intermediate ski pole
Junior soccer ball
Knee pads, pair
Mountain bicycle
Mountain bicycle tires
One hundred pound weight
Outfielder’s glove
Road bicycle
Road bicycle tires
Straight bar
Ten pound weight
Thirty inch bat
Thirty-six inch bat
Thirty-two inch bat
Tire pump
Twenty pound weight
Water bottle
World cup net
World cup soccer ball

33 rows selected.

Practice Solutions AĆ19


Practice 3 Solutions
1. Single row functions work on many rows to produce a single result.
" False
Single row functions work for each row selected by the query and return one
result per row.
2. You can use all of the arithmetic operators on date values.
" False
Additional and subtraction are the only operators that can be used.
3. What is the name of the pseudo column that holds the current date?
" SYSDATE

AĆ20 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 3 Solutions continued

4. Display the employee number, last name, and salary increased by 15% and
expressed as a whole number.

SQL> SELECT id, last_name, ROUND(salary * 1.15)


2 FROM s_emp;

ID LAST_NAME ROUND(SALARY*1.15)
------ ------------ ------------------
1 Velasquez 2875
2 Ngao 1668
3 Nagayama 1610
4 Quick-To-See 1668
5 Ropeburn 1783
6 Urguhart 1380
7 Menchu 1438
8 Biri 1265
9 Catchpole 1495
10 Havel 1503
11 Magee 1610
12 Giljum 1714
13 Sedeghi 1742
14 Nguyen 1754
15 Dumas 1668
16 Maduro 1610
17 Smith 1081
18 Nozaki 1380
19 Patel 914
20 Newman 863
21 Markarian 978
22 Chang 920
23 Patel 914
24 Dancs 989
25 Schwartz 1265

25 rows selected.

Practice Solutions AĆ21


Practice 3 Solutions continued

5. Display the employee last name and title in parentheses for all employees. The
report should look like the output below.

SQL> SELECT last_name||’(’||INITCAP(title)||’)’


2 EMPLOYEE
3 FROM s_emp
4 ORDER BY last_name;

EMPLOYEE
----------------------------------------------------
Biri(Warehouse Manager)
Catchpole(Warehouse Manager)
Chang(Stock Clerk)
Dancs(Stock Clerk)
Dumas(Sales Representative)
Giljum(Sales Representative)
Havel(Warehouse Manager)
Maduro(Stock Clerk)
Magee(Sales Representative)
Markarian(Stock Clerk)
Menchu(Warehouse Manager)
Nagayama(Vp, Sales)
Newman(Stock Clerk)
Ngao(Vp, Operations)
Nguyen(Sales Representative)
Nozaki(Stock Clerk)
Patel(Stock Clerk)
Patel(Stock Clerk)
Quick-To-See(Vp, Finance)
Ropeburn(Vp, Administration)
Schwartz(Stock Clerk)
Sedeghi(Sales Representative)
Smith(Stock Clerk)
Urguhart(Warehouse Manager)
Velasquez(President)

25 rows selected.

AĆ22 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 3 Solutions continued

6. Display each employee’s last name, hire date, and salary review date, which is the
first Monday after six months of service. Format the dates to appear in the format
similar to Eighth of May 1992.
" Results have been formatted.

SQL> SELECT last_name, start_date,


2 TO_CHAR(NEXT_DAY(ADD_MONTHS(start_date,6),
3 ’MONDAY’),
4 ’fmDdspth ”of” Month YYYY’) REVIEW
5 FROM s_emp;

Continued

Practice Solutions AĆ23


Practice 3 Solutions continued

6.—continued

LAST_NAME START_DAT REVIEW


------------ --------- ------------------------------
Velasquez 03-MAR-90 Tenth of September 1990
Ngao 08-MAR-90 Tenth of September 1990
Nagayama 17-JUN-91 Twenty-Third of December 1991
Quick-To-See 07-APR-90 Eighth of October 1990
Ropeburn 04-MAR-90 Tenth of September 1990
Urguhart 18-JAN-91 Twenty-Second of July 1991
Menchu 14-MAY-90 Nineteenth of November 1990
Biri 07-APR-90 Eighth of October 1990
Catchpole 09-FEB-92 Tenth of August 1992
Havel 27-FEB-91 Second of September 1991
Magee 14-MAY-90 Nineteenth of November 1990
Giljum 18-JAN-92 Twentieth of July 1992
Sedeghi 18-FEB-91 Nineteenth of August 1991
Nguyen 22-JAN-92 Twenty-Seventh of July 1992
Dumas 09-OCT-91 Thirteenth of April 1992
Maduro 07-FEB-92 Tenth of August 1992
Smith 08-MAR-90 Tenth of September 1990
Nozaki 09-FEB-91 Twelfth of August 1991
Patel 06-AUG-91 Tenth of February 1992
Newman 21-JUL-91 Twenty-Seventh of January 1992
Markarian 26-MAY-91 Second of December 1991
Chang 30-NOV-90 Third of June 1991
Patel 17-OCT-90 Twenty-Second of April 1991
Dancs 17-MAR-91 Twenty-Third of September 1991
Schwartz 09-MAY-91 Eleventh of November 1991

25 rows selected.

AĆ24 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 3 Solutions continued

7. Display the product name for products that have “ski” in the name.

SQL> SELECT name


2 FROM s_product
3 WHERE LOWER(name) LIKE ’%ski%’;

NAME
--------------------
Ace Ski Boot
Pro Ski Boot
Bunny Ski Pole
Ace Ski Pole
Pro Ski Pole

8. For each employee, calculate the number of months between today and the date
the employee was hired. Order your result by the number of months employed.
Round the number of months up to the closest whole number.

SQL> SELECT last_name,


2 ROUND(MONTHS_BETWEEN(SYSDATE, start_date))
3 MONTHS_WORKED
4 FROM s_emp
5 ORDER BY MONTHS_BETWEEN(SYSDATE, start_date);

Continued

Practice Solutions AĆ25


Practice 3 Solutions continued

8.—continued

LAST_NAME MONTHS_WORKED
------------ -------------
Catchpole 46
Maduro 46
Nguyen 47
Giljum 47
Dumas 50
Patel 52
Newman 53
Nagayama 54
Markarian 55
Schwartz 55
Dancs 57
Havel 58
Sedeghi 58
Nozaki 58
Urguhart 59
Chang 61
Patel 62
Menchu 67
Magee 67
Quick-To-See 68
Biri 68
Ngao 69
Smith 69
Ropeburn 69
Velasquez 69

25 rows selected.

Note: Your MONTHS_WORKED may differ from the solution because your
SYSDATE may return a different value.

AĆ26 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 3 Solutions continued

9. Display the last name for all employees and the day of the week they started.
Order the results by the day of the week starting with Monday.
" Results have been formatted.

SQL> SELECT last_name, start_date,


2 TO_CHAR(start_date, ’DAY’) DAY
3 FROM s_emp
4 ORDER BY TO_CHAR(start_date-1, ’d’);

LAST_NAME START_DAT DAY


------------ --------- ----------
Nagayama 17-JUN-91 MONDAY
Menchu 14-MAY-90 MONDAY
Sedeghi 18-FEB-91 MONDAY
Magee 14-MAY-90 MONDAY
Patel 06-AUG-91 TUESDAY
Havel 27-FEB-91 WEDNESDAY
Patel 17-OCT-90 WEDNESDAY
Nguyen 22-JAN-92 WEDNESDAY
Dumas 09-OCT-91 WEDNESDAY
Ngao 08-MAR-90 THURSDAY
Smith 08-MAR-90 THURSDAY
Schwartz 09-MAY-91 THURSDAY
Urguhart 18-JAN-91 FRIDAY
Chang 30-NOV-90 FRIDAY
Maduro 07-FEB-92 FRIDAY
Velasquez 03-MAR-90 SATURDAY
Quick-To-See 07-APR-90 SATURDAY
Biri 07-APR-90 SATURDAY
Nozaki 09-FEB-91 SATURDAY
Giljum 18-JAN-92 SATURDAY
Ropeburn 04-MAR-90 SUNDAY
Newman 21-JUL-91 SUNDAY
Dancs 17-MAR-91 SUNDAY
Markarian 26-MAY-91 SUNDAY
Catchpole 09-FEB-92 SUNDAY

25 rows selected.

Practice Solutions AĆ27


Practice 3 Solutions continued

10. Write a query that produces the following for each employee:
<employee name> earns <salary> monthly but wants<3 times salary>.
For example: ALLEN earns $1,100 monthly but wants $3,300.

SQL> SELECT UPPER(last_name)|| ’ earns ’ ||


2 TO_CHAR(salary, ’fm$99,999’)
3 || ’ monthly but wants ’||
4 TO_CHAR(salary*3, ’fm$99,999’)
5 ||’.’ ”Dream Salaries”
6 FROM s_emp;

Dream Salaries
---------------------------------------------------
VELASQUEZ earns $2,500 monthly but wants $7,500.
NGAO earns $1,450 monthly but wants $4,350.
NAGAYAMA earns $1400 monthly but wants $4,200.
QUICK-TO-SEE earns $,1450 monthly but wants $4,350.
ROPEBURN earns $1,550 monthly but wants $4,650.
URGUHART earns $1,200 monthly but wants $3,600.
MENCHU earns $1,250 monthly but wants $3,750.
BIRI earns $1,100 monthly but wants $3,300.
CATCHPOLE earns $1,300 monthly but wants $3,900.
HAVEL earns $1,307 monthly but wants $3,921.
MAGEE earns $1,400 monthly but wants $4,200.
GILJUM earns $1,490 monthly but wants $4,470.
SEDEGHI earns $1,515 monthly but wants $4,545.
NGUYEN earns $1,525 monthly but wants $4,575.
DUMAS earns $1,450 monthly but wants $4,350.
MADURO earns $1,400 monthly but wants $4,200.
NOZAKI earns $1,200 monthly but wants $3,600.
MARKARIAN earns $850 monthly but wants $2,550.
PATEL earns $795 monthly but wants $2,385.
SMITH earns $1,000 monthly but wants $3,000.
PATEL earns $795 monthly but wants $2,385.
NEWMAN earns $750 monthly but wants $2,250.
CHANG earns $800 monthly but wants $2,400.
DANCS earns $860 monthly but wants $2,580.
SCHWARTZ earns $1,100 monthly but wants $3,300.

AĆ28 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 4 Solutions
Use the S_EMP, S_DEPT, S_CUSTOMER, S_REGION, S_ORD, S_ITEM, and
S_PRODUCT tables to complete the following exercises.
1. Write a report containing each employee’s last name, department number, and
name of their department.

SQL> SELECT s_emp.last_name, s_emp.dept_id,


2 s_dept.name
3 FROM s_emp, s_dept
4 WHERE s_emp.dept_id = s_dept.id;

Continued

Practice Solutions AĆ29


Practice 4 Solutions continued

1.—continued

LAST_NAME DEPT_ID NAME


------------ ------- --------------------
Velasquez 50 Administration
Ngao 41 Operations
Nagayama 31 Sales
Quick-To-See 10 Finance
Ropeburn 50 Administration
Urguhart 41 Operations
Menchu 42 Operations
Biri 43 Operations
Catchpole 44 Operations
Havel 45 Operations
Magee 31 Sales
Giljum 32 Sales
Sedeghi 33 Sales
Nguyen 34 Sales
Dumas 35 Sales
Maduro 41 Operations
Smith 41 Operations
Nozaki 42 Operations
Patel 42 Operations
Newman 43 Operations
Markarian 43 Operations
Chang 44 Operations
Patel 34 Sales
Dancs 45 Operations
Schwartz 45 Operations

25 rows selected.

AĆ30 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 4 Solutions continued

2. Write a query to display the last name, department name, and region name of all
employees who earn a commission.
" Results have been formatted.

SQL> SELECT e.last_name, d.name, r.name


2 FROM s_emp e, s_dept d, s_region r
3 WHERE e.dept_id = d.id
4 AND r.id = d.region_id
5 AND e.commission_pct IS NOT NULL;

LAST_NAME NAME NAME


------------ -------------- --------------------
Magee Sales North America
Giljum Sales South America
Sedeghi Sales Africa / Middle East
Nguyen Sales Asia
Dumas Sales Europe

3. Display the employee name and department name for Smith.

SQL> SELECT s_emp.last_name, s_dept.name


2 FROM s_emp, s_dept
3 WHERE s_emp.dept_id = s_dept.id
4 AND s_emp.last_name = ’Smith’;

LAST_NAME NAME
------------ ----------------------
Smith Operations

Practice Solutions AĆ31


Practice 4 Solutions continued

4. Display the product name, product number, and quantity ordered of all items in
order number 101. Label the quantity column ORDERED.

SQL> SELECT s_product.name,


2 s_product.id,
3 s_item.quantity ”ORDERED”
4 FROM s_product, s_item
5 WHERE s_product.id = s_item.product_id
6 AND s_item.ord_id = 101;

NAME ID ORDERED
--------------------------------- ----- -------
Grand Prix Bicycle Tires 30421 15
Pro Curling Bar 40422 30
Prostar 10 Pound Weight 41010 20
Prostar 100 Pound Weight 41100 35
Major League Baseball 50169 40
Griffey Glove 50417 27
Cabrera Bat 50530 50

7 rows selected.

5. Display the customer number and the last name of their sales representative.
Order the list by last name.

SQL> SELECT s_customer.id, s_emp.last_name


2 FROM s_emp, s_customer
3 WHERE s_emp.id = s_customer.sales_rep_id
4 ORDER BY s_emp.last_name;

Continued

AĆ32 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 4 Solutions continued

5.—continued

ID LAST_NAME
----- ---------------
205 Dumas
206 Dumas
208 Dumas
211 Dumas
215 Dumas
201 Giljum
210 Giljum
204 Magee
214 Magee
209 Magee
213 Magee
202 Nguyen
203 Nguyen
212 Sedeghi

14 rows selected.

6. Display the customer number, customer name, and order number of all customers
and their orders. Display the customer number and name, even if they have not
placed an order.

SQL> SELECT s_customer.id ”Customer ID”,


2 s_customer.name ”Customer Name”,
3 s_ord.id ”Order ID”
4 FROM s_customer, s_ord
5 WHERE s_customer.id =
6 s_ord.customer_id (+);

Continued

Practice Solutions AĆ33


Practice 4 Solutions continued

6.—continued

Customer ID Customer Name Order ID


----------- ------------------------------ ----------
201 Unisports 97
202 Simms Atheletics 98
203 Delhi Sports 99
204 Womansport 100
204 Womansport 111
205 Kam’s Sporting Goods 101
206 Sportique 102
207 Sweet Rock Sports
208 Muench Sports 103
208 Muench Sports 104
209 Beisbol Si! 105
210 Futbol Sonora 106
210 Futbol Sonora 112
211 Kuhn’s Sports 107
212 Hamada Sport 108
213 Big John’s Sports Emporium 109
214 Ojibway Retail 110
215 Sporta Russia

18 rows selected.

7. Display all employees by last name name and employee number along with their
manager’s last name and manager number.

SQL> SELECT w.last_name EMP_NAME, w.id EMP_ID,


2 m.last_name MGR_NAME, m.id MGR_ID
3 FROM s_emp w, s_emp m
4 WHERE w.manager_id = m.id;

Continued

AĆ34 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 4 Solutions continued

7.—continued

EMP_NAME EMP_ID MGR_NAME MGR_ID


------------ ---------- ------------ ----------
Ngao 2 Velasquez 1
Nagayama 3 Velasquez 1
Quick-To-See 4 Velasquez 1
Ropeburn 5 Velasquez 1
Urguhart 6 Ngao 2
Menchu 7 Ngao 2
Biri 8 Ngao 2
Catchpole 9 Ngao 2
Havel 10 Ngao 2
Magee 11 Nagayama 3
Giljum 12 Nagayama 3
Sedeghi 13 Nagayama 3
Nguyen 14 Nagayama 3
Dumas 15 Nagayama 3
Maduro 16 Urguhart 6
Smith 17 Urguhart 6
Nozaki 18 Menchu 7
Patel 19 Menchu 7
Newman 20 Biri 8
Markarian 21 Biri 8
Chang 22 Catchpole 9
Patel 23 Catchpole 9
Dancs 24 Havel 10
Schwartz 25 Havel 10

24 rows selected.

Practice Solutions AĆ35


Practice 4 Solutions continued

8. Modify the solution to exercise 7 to also display Velasquez, who has no manager.

SQL> SELECT w.last_name ”Employee Name”,


w.id ”Employee ID”,
2 m.last_name ”Manager Name”,
m.id ”Manager ID”
3 FROM s_emp w, s_emp m
4 WHERE w.manager_id = m.id (+);

Employee Name Employee ID Manager Name Manager ID


--------------- ----------- --------------- ----------
Velasquez 1
Ngao 2 Velasquez 1
Nagayama 3 Velasquez 1
Quick-To-See 4 Velasquez 1
Ropeburn 5 Velasquez 1
Urguhart 6 Ngao 2
Menchu 7 Ngao 2
Biri 8 Ngao 2
Catchpole 9 Ngao 2
Havel 10 Ngao 2
Magee 11 Nagayama 3
Giljum 12 Nagayama 3
Sedeghi 13 Nagayama 3
Nguyen 14 Nagayama 3
Dumas 15 Nagayama 3
Maduro 16 Urguhart 6
Nozaki 18 Menchu 7
Markarian 21 Biri 8
Patel 23 Catchpole 9
Smith 17 Urguhart 6
Patel 19 Menchu 7
Newman 20 Biri 8
Chang 22 Catchpole 9
Dancs 24 Havel 10
Schwartz 25 Havel 10

25 rows selected.

AĆ36 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 4 Solutions continued

9. Display all customers and the product number and quantities they ordered for
those customers whose order totaled more than 100,000.

SQL> SELECT c.name CUSTOMER, p.id PRODUCT_ID,


2 i.quantity
3 FROM s_customer c, s_product p, s_item i,
4 s_ord o
5 WHERE c.id = o.customer_id
6 AND o.id = i.ord_id
7 AND i.product_id = p.id
8 AND o.total > 100000;

Continued

Practice Solutions AĆ37


Practice 4 Solutions continued

9.—continued

CUSTOMER PRODUCT_ID QUANTITY


------------------------------ ---------- ----------
Womansport 10011 500
Womansport 10013 400
Womansport 10021 500
Womansport 30326 600
Womansport 41010 250
Womansport 30433 450
Womansport 10023 400
Kuhn’s Sports 20106 50
Kuhn’s Sports 20201 130
Kuhn’s Sports 30421 55
Kuhn’s Sports 30321 75
Kuhn’s Sports 20108 22
Hamada Sport 20510 9
Hamada Sport 41080 50
Hamada Sport 41100 42
Hamada Sport 32861 57
Hamada Sport 20512 18
Hamada Sport 32779 60
Hamada Sport 30321 85
Big John’s Sports Emporium 10011 150
Big John’s Sports Emporium 30426 500
Big John’s Sports Emporium 50418 43
Big John’s Sports Emporium 32861 50
Big John’s Sports Emporium 30326 1500
Big John’s Sports Emporium 10012 600
Big John’s Sports Emporium 10022 300

26 rows selected.

AĆ38 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 5 Solutions
1. Determine the validity of the following statements. Circle either True or False.
a. Group functions work across many rows to produce one result.
" True
b. Group functions include nulls in calculations.
" False
Group functions ignore null values. If you want to include null values,
use the NVL function.
c. Use the HAVING clause to exclude rows from a group calculation.
" False
The WHERE clause restricts rows prior to inclusion in a group
calculation.
d. Use the HAVING clause to exclude groups of rows from the display.
" True
2. Display the highest and lowest order totals in the S_ORD. Label the columns
Highest and Lowest, respectively.

SQL> SELECT MAX (total) ”Highest”,


2 MIN (total) ”Lowest”
3 FROM s_ord;

Highest Lowest
---------- ----------
1020935 377

3. Write a query to display the minimum and maximum salary for each job type
ordered alphabetically.

SQL> SELECT title JOB, MAX(salary) MAXIMUM,


2 MIN(salary) MINIMUM
3 FROM s_emp
4 GROUP BY title;

Continued

Practice Solutions AĆ39


Practice 5 Solutions continued

3.—continued

JOB MAXIMUM MINIMUM


------------------------- ---------- ----------
President 2500 2500
Sales Representative 1525 1400
Stock Clerk 1400 750
VP, Administration 1550 1550
VP, Finance 1450 1450
VP, Operations 1450 1450
VP, Sales 1400 1400
Warehouse Manager 1307 1100

8 rows selected.

4. Determine the number of managers without listing them.

SQL> SELECT COUNT(DISTINCT(manager_id))


2 ”Number of Managers”
3 FROM s_emp;

Number of Managers
------------------
8

5. Display the number of line items in each order under each order number, labeled
Number of Items.

SQL> SELECT ord_id, COUNT(*) ”NUMBER OF ITEMS”


2 FROM s_item
3 GROUP BY ord_id;

Continued

AĆ40 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 5 Solutions continued

5.—continued

ORD_ID NUMBER OF ITEMS


---------- ---------------
97 2
98 1
99 4
100 7
101 7
102 2
103 2
104 4
105 3
106 6
107 5
108 7
109 7
110 2
111 2
112 1

16 rows selected.

6. Display the manager number and the salary of the lowest paid employee for that
manager. Exclude any groups where the minimum salary is less than 1000. Sort
the output by salary.

SQL> SELECT manager_id,


2 MIN(salary) ”LOWEST PAID EMPLOYEE”
3 FROM s_emp
4 GROUP BY manager_id
5 HAVING MIN(salary) >= 1000
6 ORDER BY 2;

Continued

Practice Solutions AĆ41


Practice 5 Solutions continued

6.—continued

MANAGER_ID LOWEST PAID EMPLOYEE


---------- --------------------
2 1100
1 1400
3 1400
2500

7. What is the difference between the highest and lowest salaries?

SQL> SELECT MAX(salary) - MIN (salary) DIFFERENCE


2 FROM s_emp;

DIFFERENCE
----------
1750

AĆ42 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 5 Solutions continued

If you have time, complete the following exercises.


8. Display the product number and number of times it was ordered, labeled Times
Ordered. Only show those products that have been ordered at least three times.
Order the data by the number of products ordered.

SQL> SELECT product_id,


2 COUNT(ord_id) ”TIMES ORDERED”
3 FROM s_item
4 GROUP BY product_id
5 HAVING COUNT(ord_id) >= 3
6 ORDER BY COUNT(ord_id);

PRODUCT_ID TIMES ORDERED


---------- --------------
20106 3
20108 3
20201 3
20510 3
50273 3
30421 3
20512 3
30321 4

8 rows selected.

9. Retrieve the region number, region name, and the number of departments within
each region.

SQL> SELECT r.id, r.name, COUNT(d.id) ”# OF DEPT”


2 FROM s_dept d, s_region r
3 WHERE d.region_id = r.id
4 GROUP BY r.id, r.name;

Continued

Practice Solutions AĆ43


Practice 5 Solutions continued

9.—continued

ID NAME # OF DEPT
----- --------------------------- ----------------
1 North America 4
2 South America 2
3 Africa / Middle East 2
4 Asia 2
5 Europe 2

10. Display the order number and total item count for each order of 100 or more
items. For example, if order number 99 contains quantity 30 of one item, and
quantity 75 of another item, then the total item count for that order is 105.

SQL> SELECT ord_id,


2 SUM(quantity) ”TOTAL ITEM COUNT”
3 FROM s_item
4 GROUP BY ord_id
5 HAVING SUM(quantity) >= 100;

ORD_ID TOTAL ITEM COUNT


---------- -----------------
97 1050
99 165
100 3100
101 217
102 145
106 392
107 332
108 321
109 3143

9 rows selected.

AĆ44 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 5 Solutions continued

11. Display the customer name and the number of orders for each customer.

SQL> SELECT c.name, COUNT(o.id) ”NUMBER OF ORDERS”


2 FROM s_customer c, s_ord o
3 WHERE c.id = o.customer_id
4 GROUP BY c.name;

NAME NUMBER OF ORDERS


-------------------------------- -----------------
Beisbol Si! 1
Big John’s Sports Emporium 1
Delhi Sports 1
Futbol Sonora 2
Hamada Sport 1
Kam’s Sporting Goods 1
Kuhn’s Sports 1
Muench Sports 2
Simms Athletics 1
Ojibway Retail 1
Sportique 1
Unisports 1
Womansport 2

13 rows selected.

Practice Solutions AĆ45


Practice 6 Solutions
1. Answer the following questions
a. Which query runs first with a subquery?
" Inner query runs first.
b. How many times does the first query run?
" The first query executes once.
c. You cannot use the equals (=) operator if the inner query returns more than
one value.
" True
i. If the answer is True, why and what operator should be used?
" The equals operator expects one value in return. Use the IN operator.
ii. If the answer is False, why?
2. Display the first name, last name, and start date for all employees in the same
department as Magee.

SQL> SELECT first_name, last_name, start_date


2 FROM s_emp
3 WHERE dept_id =
4 (SELECT dept_id
5 FROM s_emp
6 WHERE last_name = ’Magee’);

FIRST_NAME LAST_NAME START_DAT


-------------------- -------------------- ---------
Midori Nagayama 17-JUN-91
Colin Magee 14-MAY-90

AĆ46 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 6 Solutions continued

3. Display the employee number, first name, last name, and user name for all
employees with salaries above the average salary.

SQL> SELECT id, first_name, last_name, userid


2 FROM s_emp
3 WHERE salary >
4 (SELECT AVG(salary)
5 FROM s_emp);

ID FIRST_NAME LAST_NAME USERID


------- --------------- --------------- --------
1 Carmen Velasquez cvelasqu
2 LaDoris Ngao lngao
3 Midori Nagayama mnagayam
4 Mark Quick-To-See mquickto
5 Audry Ropeburn aropebur
9 Antoinette Catchpole acatchpo
10 Marta Havel mhavel
11 Colin Magee cmagee
12 Henry Giljum hgiljum
13 Yasmin Sedeghi ysedeghi
14 Mai Nguyen mnguyen
15 Andre Dumas adumas
16 Elena Maduro emaduro

13 rows selected.

Practice Solutions AĆ47


Practice 6 Solutions continued

4. Display last name, department number, and title for all employees assigned to
region 1 or region 2.

SQL> SELECT last_name, dept_id, title


2 FROM s_emp
3 WHERE dept_id IN
4 (SELECT id
5 FROM s_dept
6 WHERE region_id IN (1,2));

LAST_NAME DEPT_ID TITLE


-------------------- --------- -------------------
Velasquez 50 President
Ngao 41 VP, Operations
Nagayama 31 VP, Sales
Quick-To-See 10 VP, Finance
Ropeburn 50 VP, Administration
Urguhart 41 Warehouse Manager
Menchu 42 Warehouse Manager
Magee 31 Sales Representative
Giljum 32 Sales Representative
Maduro 41 Stock Clerk
Smith 41 Stock Clerk
Nozaki 42 Stock Clerk
Patel 42 Stock Clerk

13 rows selected.

AĆ48 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 6 Solutions continued

5. Display the last name and salary for all employees that report to LaDoris Ngao.

SQL> SELECT last_name, salary


2 FROM s_emp
3 WHERE manager_id =
4 (SELECT id
5 FROM s_emp
6 WHERE last_name = ’Ngao’);

LAST_NAME SALARY
------------------------- ---------
Urguhart 1200
Menchu 1250
Biri 1100
Catchpole 1300
Havel 1307

Practice Solutions AĆ49


Practice 6 Solutions continued

6. Display the employee number, first name, and last name for all employees with a
salary above the average salary and that work with any employee with a last name
that contains a “t”.

SQL> SELECT id, first_name, last_name


2 FROM s_emp
3 WHERE salary >
4 (SELECT AVG(salary)
5 FROM s_emp)
6 AND dept_id IN
7 (SELECT dept_id
8 FROM s_emp
9 WHERE UPPER(last_name) LIKE ’%T%’);

ID FIRST_NAME LAST_NAME
------- -------------------- -------------------
4 Mark Quick-To-See
14 Mai Nguyen
2 LaDoris Ngao
16 Elena Maduro
9 Antoinette Catchpole
10 Marta Havel

6 rows selected.

AĆ50 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 6 Solutions continued

7. Display the customer number, customer name, customer rating, and sales
representative’s last name for all customers who are located in the North America
region or have Nguyen as their sales representative.

SQL> SELECT c.id, c.name, c.credit_rating,


2 e.last_name
3 FROM s_customer c, s_emp e
4 WHERE c.sales_rep_id = e.id
5 AND (c.region_id = (select id from
6 s_region
7 where name = ‘North America’)
8 OR c.sales_rep_id = (select id from s_emp
9 where last_name =
10 ‘Nguyen’));

ID NAME CREDIT_RA LAST_NAME


––– –––––––––––––––––––––––––––– ––––––––– –––––––––
202 Simms Athletics POOR Nguyen
203 Delhi Sports GOOD Nguyen
204 Womansport EXCELLENT Magee
209 Beisbol Si! EXCELLENT Magee
213 Big John’s Sports Emporium EXCELLENT Magee
214 Ojibway Retail POOR Magee

6 rows selected.

Practice Solutions AĆ51


Practice 6 Solutions continued

8. Display the name and short description for any product that did not appear on an
order in the month of September, 1992.
" Results have been formatted.

SQL> SELECT name, short_desc DESCRIPTION


2 FROM s_product
3 WHERE id NOT IN
4 (SELECT s_item.product_id
5 FROM s_item, s_ord
6 WHERE s_item.ord_id = s_ord.id
7 AND s_ord.date_ordered BETWEEN
8 ’01-SEP-92’ AND ’30-SEP-92’);

NAME DESCRIPTION
------------------------ -------------------------
Pro Ski Boot Advanced ski boot
Bunny Ski Pole Beginner’s ski pole
Pro Ski Pole Advanced ski pole
Pro Curling Bar Curling bar
Prostar 10 Pound Weight Ten pound weight
Prostar 20 Pound Weight Twenty pound weight
Prostar 50 Pound Weight Fifty pound weight
Griffey Glove Outfielder’s glove
Cabrera Bat Thirty inch bat

9 rows selected.

AĆ52 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 6 Solutions continued

9. Display the customer name and credit rating for all customers of sales
representative Andre Dumas.

SQL> SELECT name, credit_rating


2 FROM s_customer
3 WHERE sales_rep_id =
4 (SELECT id
5 FROM s_emp
6 WHERE last_name = ’Dumas’);

NAME CREDIT_RA
------------------------ ---------
Kam’s Sporting Goods EXCELLENT
Sportique EXCELLENT
Muench Sports GOOD
Kuhn’s Sports EXCELLENT
Sporta Russia POOR

Practice Solutions AĆ53


Practice 6 Solutions continued

10. Display each sales representative’s last name in region 1 and region 2, their
customers’ names and each customer’s total sales orders.

SQL> SELECT e.last_name, c.name, sum(o.total) “Order


2 Total”
3 FROM s_emp e, s_customer c, s_ord o
4 WHERE e.id = c.sales_rep_id
5 AND c.id = o.customer_id
6 AND e.dept_id in (select id from s_dept
7 where region_id in (1,2))
8 GROUP BY e.last_name, c.name;

LAST_NAME NAME ORDER TOTAL


–––––––––––––– –––––––––––––––––––––––––– ––––––––––––
Giljum Futbol Sonora 16184
Giljum Unisports 84000
Magee Beisbol Si! 2722.24
Magee Big John’s Sports Emporium 1020935
Magee Ojibway Retail 1539.13
Magee Womansport 603870

6 rows selected.

AĆ54 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 7 Solutions
Determine whether the following statements are true.
1. A single ampersand substitution variable prompts only once.
" True
However, if the variable is defined, then the single ampersand substitution
variable will not prompt at all. In fact, it will pick up the value in the
predefined variable.
2. The ACCEPT command is a SQL command.
" False
The ACCEPT command is a SQL*Plus command. It is issued at the SQL
prompt.

Practice Solutions AĆ55


Practice 7 Solutions continued

The following questions use the S_EMP, S_CUSTOMER, and S_PRODUCT tables.
3. Write a script file to display the user ID, first and last names concatenated
together, and start dates of employees within a specified range. Prompt the user
for the two ranges using the ACCEPT command. Use the format “MM/DD/YY”.
Save the script file as p7q3.sql.

SET ECHO OFF


SET VERIFY OFF
ACCEPT low_date DATE FORMAT ’MM/DD/YY’ -
PROMPT ”Enter the low date range (’MM/DD/YY’): ”
ACCEPT high_date DATE FORMAT ’MM/DD/YY’ -
PROMPT ”Enter the high date range (’MM/DD/YY’): ”
COLUMN employee FORMAT A30
SELECT userid, first_name||’ ’||last_name employee,
start_date
FROM s_emp
WHERE start_date BETWEEN
TO_DATE(’&low_date’,’MM/DD/YY’)
AND TO_DATE(’&high_date’,’MM/DD/YY’)
/
UNDEFINE low_date
UNDEFINE high_date
COLUMN employee CLEAR
SET VERIFY ON
SET ECHO ON

SQL> START p7q3


SET ECHO OFF
Enter the low date range (’MM/DD/YY’): 09/01/91
Enter the high date range (’MM/DD/YY’): 09/01/92

USERID EMPLOYEE START_DAT


-------- ------------------------------ ---------
acatchpo Antoinette Catchpole 09-FEB-92
hgiljum Henry Giljum 18-JAN-92
mnguyen Mai Nguyen 22-JAN-92
adumas Andre Dumas 09-OCT-91
emaduro Elena Maduro 07-FEB-92

AĆ56 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 7 Solutions continued

4. Write a script to search for customer names and numbers. The search condition
should allow for case-insensitive name searches. Save the script file as p7q4.sql.
Your result should look like the output below.

SET ECHO OFF


ACCEPT p_customer PROMPT ”Please enter the customer’s name: ”
COLUMN name HEADING ”CUSTOMER NAME” FORMAT A40
SELECT id, name
FROM s_customer
WHERE UPPER(name) LIKE UPPER(’%&p_customer%’)
/
UNDEFINE p_customer
COLUMN name CLEAR
SET ECHO ON

" Notice that the variable is between single quotation marks. Without the
quotation marks, the operator would have to input the quotation marks at the
prompt.

SQL> START p7q4


SET ECHO OFF
Please enter the customer’s name: sport

ID CUSTOMER NAME
------ ----------------------------------------
201 Unisports
203 Delhi Sports
204 Womansport
205 Kam’s Sporting Goods
206 Sportique
207 Sweet Rock Sports
208 Muench Sports
211 Kuhn’s Sports
212 Hamada Sport
213 Big John’s Sports Emporium
215 Sporta Russia

11 rows selected.

Practice Solutions AĆ57


Practice 7 Solutions continued

5. Write a report containing the sales representative name, customer name, and each
customer’s total sales order. Prompt the user for a region number. Save the script
as p7q5.sql.

SET ECHO OFF


SET VERIFY OFF
ACCEPT p_region NUMBER PROMPT ’Please enter a region number: ’
COLUMN employee FORMAT A25
COLUMN customer FORMAT A30
COLUMN sales FORMAT $9,999,999
SELECT a.first_name||’ ’||a.last_name EMPLOYEE,
b.name CUSTOMER, SUM(c.total) SALES
FROM s_emp a, s_customer b, s_ord c
WHERE a.id = b.sales_rep_id
AND b.id = c.customer_id
AND a.dept_id IN
(SELECT id
FROM s_dept
WHERE region_id IN (&p_region))
GROUP BY a.first_name||’ ’||a.last_name, b.name
/
COLUMN sales CLEAR
COLUMN customer CLEAR
COLUMN employee CLEAR
SET VERIFY ON
SET ECHO ON

SQL> START p7q5


Please enter a region number: 1

EMPLOYEE CUSTOMER SALES


---------------------- --------------------------- -----------
Colin Magee Beisbol Si! $2,722
Colin Magee Big John’s Sports Emporium $1,020,935
Colin Magee Ojibway Retail $1,539
Colin Magee Womansport $603,870

Note: SQL*Plus allows you to suppress duplicate values by using the BREAK
command. More about the BREAK command is covered in Advanced SQL
and SQL*Plus course.

AĆ58 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 9 Solutions
1. Are the following examples syntactically correct? If not, why?
a. Correct/Incorrect
" Incorrect.
A comma is required after the NAME definition in line 3 for a table
constraint.

SQL> CREATE TABLE T_3000


2 (id NUMBER(7),
3 name VARCHAR2(25)
4 CONSTRAINT table_id_pk PRIMARY KEY(id));

b. Correct/Incorrect
" Incorrect.
Remove the comma in line 3 to include the NOT NULL column
constraint.
Add “(id)” after “PRIMARY KEY” in line 9 because this is a table
constraint.
Change table name in line 1 because 1995_orders is an illegal table
name. A table name must begin with a letter.

SQL> CREATE TABLE 1995_orders


2 (id NUMBER(7),
3 customer_id NUMBER(7),
4 CONSTRAINT ord_cust_id_nn NOT NULL,
5 total NUMBER(11,2),
6 filled CHAR(1)
7 CONSTRAINT ord_filled_ck CHECK
8 (filled IN (’Y’,’N’)),
9 CONSTRAINT ord_id_pk PRIMARY KEY);

Practice Solutions AĆ59


Practice 9 Solutions continued

2. Create the DEPARTMENT table based on the table instance chart given below.
Enter the syntax in a script named p9q2.sql, then execute the script to create the
table. Confirm that the table is created. You will add data to the table in another
lesson.
Table name: DEPARTMENT

Column Name ID NAME


Key Type PK
Nulls/ Unique NN, U
FK Table
FK Column
Datatype NUMBER CHAR
Length 7 25

" Script p9q2.sql contents.

SET ECHO OFF


CREATE TABLE department
(id NUMBER(7)
CONSTRAINT department_id_pk PRIMARY KEY,
name VARCHAR2(25))
/
SET ECHO ON

SQL> START p9q2


Table created.

SQL> DESCRIBE department

Name Null? Type


-------------------------- -------- ----
ID NOT NULL NUMBER(7)
NAME VARCHAR2(25)

AĆ60 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 9 Solutions continued

3. Create the EMPLOYEE table based on the table instance chart given below. Enter
the syntax in a script p9q3.sql, then execute the script to create the table. Confirm
that the table is created. You will add data to the table in another lesson.
Table name: EMPLOYEE

Column ID LAST_NAME FIRST_NAME DEPT_ID


Name
Key Type PK FK
Nulls/ Unique NN, U NN NN
FK Table DEPARTMENT
FK Column ID
Datatype NUMBER CHAR CHAR NUMBER
Length 7 25 25 7

Continued

Practice Solutions AĆ61


Practice 9 Solutions continued

3.—continued
" Script p9q3.sql contents.
SET ECHO OFF
CREATE TABLE employee
(id NUMBER(7)
CONSTRAINT employee_id_pk PRIMARY KEY,
last_name VARCHAR2(25)
CONSTRAINT employee_last_name_nn NOT NULL,
first_name VARCHAR2(25),
dept_id NUMBER (7)
CONSTRAINT employee_dept_id_nn NOT NULL
CONSTRAINT employee_dept_id_fk
REFERENCES department(id))
/
SET ECHO ON

SQL> START p9q3


Table created.

SQL> DESCRIBE employee

Name Null? Type


––––––––––––––––––––––– ––––––––– –––––––––––
ID NOT NULL NUMBER(7)
LAST_NAME NOT NULL VARCHAR2(25)
FIRST_NAME VARCHAR2(25)
DEPT_ID NOT NULL NUMBER(7)

AĆ62 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 10 Solutions

1. Select all the views from the data dictionary pertaining to Table. You can adjust
the column formats by using the SQL*Plus COLUMN command.

SQL> COLUMN TABLE_NAME FORMAT A22


SQL> COLUMN COMMENTS FORMAT A50 WORD_WRAPPED
SQL> SELECT *
2 FROM DICTIONARY
3 WHERE LOWER(COMMENTS) LIKE ’%table%’;

TABLE_NAME COMMENTS
----------------- --------------------------------
ALL_CATALOG All tables, views, synonyms,
sequences accessible to the user
ALL_COL_COMMENTS Comments on columns of
accessible tables and views
ALL_CONSTRAINTS Constraint definitions on
accessible tables
ALL_INDEXES Descriptions of indexes on
tables accessible to the user
ALL_IND_COLUMNS COLUMNs comprising INDEXes on
accessible TABLES
ALL_TABLES Description of tables accessible
to the user
ALL_TAB_COLUMNS Columns of all tables, views and
clusters
ALL_TAB_COMMENTS Comments on tables and views
accessible to the user
ALL_TRIGGER_COLS Column usage in user’s triggers
or in triggers on user’s tables
USER_AUDIT_OBJECT Audit trail records for
statements concerning objects,
specifically: table, cluster,
view, index, sequence, [public]
database link, [public] synonym,
procedure, trigger, rollback
segment, tablespace, role, user

Practice Solutions AĆ63


Practice 10 Solutions continued

1.—continued

TABLE_NAME COMMENTS
----------------- --------------------------------
USER_CATALOG Tables, Views, Synonyms and
Sequences owned by the user
USER_CLU_COLUMNS Mapping of table columns to
cluster columns
USER_COL_COMMENTS Comments on columns of user’s
tables and views
USER_CONSTRAINTS Constraint definitions on user’s
own tables
USER_FREE_SPACE Free extents in tablespaces
accessible to the user
USER_IND_COLUMNS COLUMNs comprising user’s
INDEXes or on user’s TABLES
USER_OBJ_AUDIT_OP Auditing options for user’s own
TS tables and views
USER_TABLES Description of the user’s own
tables
USER_TABLESPACES Description of accessible
tablespaces
USER_TAB_COLUMNS Columns of user’s tables, views
and clusters
USER_TAB_COMMENTS Comments on the tables and views
owned by the user
USER_TS_QUOTAS Tablespace quotas for the user
AUDIT_ACTIONS Description table for audit
trail action type codes. Maps
action type numbers to action
type names
DICTIONARY Description of data dictionary
tables and views
DICT_COLUMNS Description of columns in data
dictionary tables and views
ROLE_TAB_PRIVS Table privileges granted to
roles
TABS Synonym for USER_TABLES
27 rows selected.

AĆ64 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 10 Solutions continued

2. If a query is very lengthy, what SQL*Plus command can you set before you
execute the query to show only one page at a time?
" Issue the SQL*Plus command SET PAUSE ON.
3. Query the USER_OBJECTS data dictionary to see information about the tables
you created in Practice 9, DEPARTMENT and EMPLOYEE tables.

SQL> SELECT *
2 FROM user_objects
3 WHERE object_type = ’TABLE’
4 AND object_name
5 IN (’EMPLOYEE’,’DEPARTMENT’);

OBJECT_NAM OBJECT_ID OBJECT_TYPE CREATED


---------- ---------- ------------- ---------
LAST_DDL_ TIMESTAMP STATUS
--------- -------------------- -------
DEPARTMENT 94460 TABLE 10-FEB-96
10-FEB-96 1996-02-10:10:52:29 VALID

EMPLOYEE 94462 TABLE 10-FEB-96


10-FEB-96 1996-02-10:10:52:30 VALID

Practice Solutions AĆ65


Practice 10 Solutions continued

4. Create a script to execute a generic query to confirm the constraints for the tables
you have created. You can use a substitution parameter for the table name. Save
the query as p10q4.sql. Execute the script to confirm the constraints for the tables
you created in Practice 9, DEPARTMENT and EMPLOYEE tables.
" Script p10q4.sql contents.

SET ECHO OFF


REM SQL*Plus commands
ACCEPT table PROMPT ’Table to view constraints: ’
COLUMN constraint_name FORMAT A25
COLUMN search_condition FORMAT A25
COLUMN r_constraint_name FORMAT A20

REM SELECT statement to query the constraints


SELECT constraint_name, constraint_type,
search_condition, r_constraint_name
FROM user_constraints
WHERE table_name = UPPER(’&table’)
/
CLEAR COLUMN
SET ECHO ON

SQL> START p10q4


Table to view constraints: department
CONSTRAINT_NAME C
------------------------- -
SEARCH_CONDITION R_CONSTRAINT_NAME
------------------------- --------------------
DEPARTMENT_ID_PK P

AĆ66 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 10 Solutions continued

4.—continued

SQL> START p10q4


Table to view constraints: employee
CONSTRAINT_NAME C
------------------------- -
SEARCH_CONDITION R_CONSTRAINT_NAME
------------------------- --------------------
EMPLOYEE_LAST_NAME_NN C
LAST_NAME IS NOT NULL

EMPLOYEE_ID_PK P

EMPLOYEE_DEPT_ID_FK R
DEPARTMENT_ID_PK
EMPLOYEE_DEPT_ID_NN C
DEPT_ID IS NOT NULL

Practice Solutions AĆ67


Practice 11 Solutions
1. Insert data into the DEPARTMENT and EMPLOYEE tables.
a. Describe the DEPARTMENT and EMPLOYEE tables to identify the column
names.

SQL> DESCRIBE department


Name Null? Type
-------------------------- -------- ----
ID NOT NULL NUMBER(7)
NAME VARCHAR2(25)

SQL> DESCRIBE employee


Name Null? Type
-------------------------- -------- ----
ID NOT NULL NUMBER(7)
LAST_NAME NOT NULL VARCHAR2(25)
FIRST_NAME VARCHAR2(25)
DEPT_ID NOT NULL NUMBER(7)

b. View the constraints on each table to identify the primary key and any other
constraints. Execute the script p10q4.sql, which is a generic query to confirm
constraints.

SQL> START p10q4


Table to view constraints: department
CONSTRAINT_NAME C
------------------------- -
SEARCH_CONDITION R_CONSTRAINT_NAME
------------------------- --------------------
DEPARTMENT_ID_PK P

AĆ68 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 11 Solutions continued

1b.—continued

SQL> START p10q4


Table to view constraints: employee
CONSTRAINT_NAME C
------------------------- -
SEARCH_CONDITION R_CONSTRAINT_NAME
------------------------- --------------------
EMPLOYEE_LAST_NAME_NN C
LAST_NAME IS NOT NULL

EMPLOYEE_ID_PK P

EMPLOYEE_DEPT_ID_FK R
DEPARTMENT_ID_PK

c. Add a row of data to the DEPARTMENT table. The department number is 10


and the department name is Finance. Do not list the columns in the INSERT
clause.

SQL> INSERT INTO department


2 VALUES (10, ’Finance’);

1 row created.

Practice Solutions AĆ69


Practice 11 Solutions continued

1.—continued
d. Add two rows of data to the EMPLOYEE table. Write a script named
p11q1d.sql that prompts you for each column value. The first employee is
Donna Smith in department number 10, and her employee number is 200. The
second employee is Albert Jones in department number 54, and his employee
number is 201. What was the result and why?

SET ECHO OFF


INSERT INTO employee (first_name,
last_name, dept_id, id)
VALUES (’&first_name’, ’&last_name’,
&department_number, &employee_number)
/
SET ECHO ON

SQL> START p11q1d


SQL> SET ECHO OFF
Enter value for first_name: Donna
Enter value for last_name: Smith
Enter value for department_number: 10
Enter value for employee_number: 200

1 row created.

AĆ70 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 11 Solutions continued

1d.—continued

SQL> START p11q1d


SQL> SET ECHO OFF
Enter value for first_name: Albert
Enter value for last_name: Jones
Enter value for department_number: 54
Enter value for employee_number: 201
INSERT INTO employee (first_name,
*
ERROR at line 1:
ORA-02291: integrity constraint
(PREP40.EMPLOYEE_DEPT_ID_FK) violated - parent
key not found

" Integrity constraint error occurred because department number 54 does


not exist.
e. Insert into the DEPARTMENT table department number 10 and department
name of Marketing. What was the result and why?

SQL> INSERT INTO department


2 VALUES (10, ’Marketing’);
INSERT INTO department
*
ERROR at line 1:
ORA-00001: unique constraint
(PREP40.DEPARTMENT_ID_PK) violated

" Unique constraint error occurred because a department number 10


already exists.

Practice Solutions AĆ71


Practice 11 Solutions continued

1.—continued
f. Confirm your additions to the tables.

SQL> SELECT *
2 FROM department;

ID NAME
---------- -------------------------
10 Finance

SQL> SELECT *
2 FROM employee;

ID LAST_NAME FIRST_NAME DEPT_ID


---- ---------- ---------- --------
200 Smith Donna 10

AĆ72 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 11 Solutions continued

1.—continued

g. Write a script named p11q1g.sql to prompt the user to add the following rows
to the DEPARTMENT table: Marketing as number 37; Sales as number 54;
and Personnel as number 75.

SET ECHO OFF


INSERT INTO department (name, id)
VALUES (’&department_name’,&id)
/
SET ECHO ON

SQL> START p11q1g


SQL> SET ECHO OFF
Enter value for department_name: Marketing
Enter value for id: 37

1 row created.

SQL> START p11q1g


SQL> SET ECHO OFF
Enter value for department_name: Sales
Enter value for id: 54

1 row created.

SQL> START p11q1g


SQL> SET ECHO OFF
Enter value for department_name: Personnel
Enter value for id: 75

1 row created.

Practice Solutions AĆ73


Practice 11 Solutions continued

1.—continued
h. Execute the p11q1d.sql script to add the following rows to the EMPLOYEE
table: Albert Jones in department number 54, and employee number 201;
Harry Chin in department 75 and employee number 202; Rey Guiliani in
department 37 and employee number 203.

SQL> START p11q1d


SQL> SET ECHO OFF
Enter value for first_name: Albert
Enter value for last_name: Jones
Enter value for department_number: 54
Enter value for employee_number: 201

1 row created.

SQL> START p11q1d


SQL> SET ECHO OFF
Enter value for first_name: Harry
Enter value for last_name: Chin
Enter value for department_number: 75
Enter value for employee_number: 202

1 row created.

SQL> START p11q1d


SQL> SET ECHO OFF
Enter value for first_name: Rey
Enter value for last_name: Guiliani
Enter value for department_number: 37
Enter value for employee_number: 203

1 row created.

AĆ74 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 11 Solutions continued

1.—continued
i. Confirm your additions to the tables.

SQL> SELECT *
2 FROM department;

ID NAME
---- -------------------------
10 Finance
37 Marketing
54 Sales
75 Personnel

SQL> SELECT *
2 FROM employee;

ID LAST_NAME FIRST_NAME DEPT_ID


---- ---------- ---------- --------
200 Smith Donna 10
201 Jones Albert 54
202 Chin Harry 75
203 Guiliani Rey 37

j. Make the data additions permanent.

SQL> COMMIT;
Commit complete.

Practice Solutions AĆ75


Practice 11 Solutions continued

2. Update and delete data in the DEPARTMENT and EMPLOYEE tables.


a. Change the name of the Personnel department to Human Resources.

SQL> UPDATE department


2 SET name = ’Human Resources’
3 WHERE id = 75;
1 row updated.

b. Change the last name of employee 202 to Korsgaard.

SQL> UPDATE employee


2 SET last_name = ’Korsgaard’
3 WHERE id = 202;
1 row updated.

c. Verify your changes to the tables.

SQL> SELECT *
2 FROM department
3 WHERE name = ’Human Resources’;

ID NAME
---- -------------------------
75 Human Resources

SQL> SELECT *
2 FROM employee
3 WHERE id = 202;

ID LAST_NAME FIRST_NAME DEPT_ID


---- ---------- ---------- --------
202 Korsgaard Harry 75

AĆ76 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 11 Solutions continued

2.—continued
d. Attempt to delete department 54. What was the result and why?

SQL> DELETE FROM department


2 WHERE id = 54;
DELETE FROM department
*
ERROR at line 1:
ORA-02292: integrity constraint
(PREP40.EMPLOYEE_DEPT_ID_FK) violated - child
record found

" Integrity constraint violation because there is foreign key reference to


department number 54 in the EMPLOYEE table.
e. Delete Albert Jones from the EMPLOYEE table.

SQL> SELECT *
2 FROM employee
3 WHERE last_name = ’Jones’;

ID LAST_NAME FIRST_NAME DEPT_ID


---- ---------- ---------- --------
201 Jones Albert 54

SQL> DELETE FROM employee


2 WHERE id = 201;
1 row deleted.

Practice Solutions AĆ77


Practice 11 Solutions continued

2.—continued

f. Attempt to delete department 54 from the DEPARTMENT table again. What


was the result and why?

SQL> DELETE FROM department


2 WHERE id = 54;
1 row deleted.

" The deletion is successful now because the foreign key reference to
department number 54 was removed when the record for Albert Jones
was deleted.
g. Verify the changes to your tables.

SQL> SELECT *
2 FROM department;

ID NAME
---- -------------------------
10 Finance
37 Marketing
75 Human Resources

SQL> SELECT *
2 FROM employee;

ID LAST_NAME FIRST_NAME DEPT_ID


---- ---------- ---------- --------
200 Smith Donna 10
202 Korsgaard Harry 75
203 Guiliani Rey 37

AĆ78 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 11 Solutions continued

2.—continued
h. Commit all pending changes.

SQL> COMMIT;
Commit complete.

3. Control data transactions to the DEPARTMENT and EMPLOYEE tables.


a. Execute the p11q1g.sql script to reinstate the Sales department as department
number 54.

SQL> start p11q1g


SQL> SET ECHO OFF
Enter value for department_name: Sales
Enter value for id: 54

1 row created.

b. Verify your addition.

SQL> SELECT *
2 FROM department
3 WHERE id = 54;

ID NAME
---- -------------------------
54 Sales

c. Mark a transaction processing savepoint.

SQL> SAVEPOINT sales;

Practice Solutions AĆ79


Practice 11 Solutions continued

3.—continued
d. Empty the entire EMPLOYEE table.

SQL> DELETE FROM employee;


3 rows deleted.

e. Verify that the EMPLOYEE table is empty.

SQL> SELECT *
2 FROM employee;
no rows selected

f. Discard the most recent DELETE operation without discarding the most
recent INSERT operation.

SQL> ROLLBACK TO sales;


Rollback complete.

g. Verify that the new row in the DEPARTMENT table is still intact. Verify that
the EMPLOYEE table has all three rows.

SQL> SELECT *
2 FROM department;

ID NAME
---- -------------------------
10 Finance
37 Marketing
54 Sales
75 Human Resources

AĆ80 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 11 Solutions continued

3g.—continued

SQL> SELECT *
2 FROM employee;

ID LAST_NAME FIRST_NAME DEPT_ID


---- ---------- ---------- --------
200 Smith Donna 10
202 Korsgaard Harry 75
203 Guiliani Rey 37

h. Make the data addition permanent.

SQL> COMMIT;
Commit complete.

Practice Solutions AĆ81


Practice 12 Solutions
1. Create a WORKER table, which copies the data from the EMPLOYEE table.
Describe the table to confirm its structure.

SQL> CREATE TABLE worker


2 AS (SELECT *
3 FROM employee);
Table created.

SQL> DESCRIBE worker


Name Null? Type
-------------------------- -------- ----
ID NUMBER(7)
LAST_NAME NOT NULL VARCHAR2(25)
FIRST_NAME VARCHAR2(25)
DEPT_ID NOT NULL NUMBER(7)

2. View the constraints for this new table. Save this command to a script named
p12q2.sql. Note the types and names of the constraints.

SQL> SELECT constraint_name, constraint_type,


2 search_condition, r_constraint_name
3 FROM user_constraints
4 WHERE table_name = ’WORKER’;

CONSTRAINT_NAME C SEARCH_CONDITION R_CONSTRAI


--------------- - --------------------- ----------
SYS_C00108545 C LAST_NAME IS NOT NULL
SYS_C00108546 C DEPT_ID IS NOT NULL
SQL> SAVE p12q2
Created file p12q2

" Your constraint names may be different from those listed here because they
are system generated.

AĆ82 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 12 Solutions continued

3. Compare these constraints to those in the EMPLOYEE table. Note the types and
names of the constraints.

SQL> SELECT constraint_name, constraint_type,


2 search_condition, r_constraint_name
3 FROM user_constraints
4 WHERE table_name = ’EMPLOYEE’;

CONSTRAINT_NAME C SEARCH_CONDITION R_CONSTRAI


--------------- - --------------------- ----------
EMP_LAST_NN C LAST_NAME IS NOT NULL
EMP_DEPT_ID_NN C DEPT_ID IS NOT NULL
EMP_ID_PK P
EMP_DEPT_ID_FK R DEPT_ID_PK

4. Add a table level PRIMARY KEY constraint to the WORKER table using the ID
column. The constraint should be immediately enabled.

SQL> ALTER TABLE worker


2 ADD CONSTRAINT worker_id_pk PRIMARY KEY(id);
Table altered.

5. Add a foreign key reference from the DEPARTMENT table to the


DEPTARTMENT_ID column in the WORKER table. Confirm that the
constraints were added by re-executing p12q2.sql.

SQL> ALTER TABLE worker


2 ADD CONSTRAINT worker_dept_id_fk
3 FOREIGN KEY(dept_id)
4 REFERENCES department(id);
Table altered.

Practice Solutions AĆ83


Practice 12 Solutions continued

5.—continued

SQL> START p12q2

CONSTRAINT_NAME C SEARCH_CONDITION R_CONSTRAI


--------------- - --------------------- ----------
SYS_C00108545 C LAST_NAME IS NOT NULL
SYS_C00108546 C DEPT_ID IS NOT NULL
WORKER_ID_PK P
WORKER_DEPT_ID_FK R DEPT_ID_PK

6. Display the object names and types from the USER_OBJECTS data dictionary
view. You may want to format the columns for readability. Notice that the new
table and a new index were created.

SQL> COLUMN object_name FORMAT A30


SQL> SELECT object_name, object_type
2 FROM user_objects
3 ORDER BY object_name;

OBJECT_NAME OBJECT_TYPE
------------------------------ -------------
DEPARTMENT TABLE
DEPT_ID_PK INDEX
EMPLOYEE TABLE
EMP_ID_PK INDEX
S_CUSTOMER TABLE
S_CUSTOMER_ID SEQUENCE
S_CUSTOMER_ID_PK INDEX
S_DEPT TABLE
S_DEPT_ID SEQUENCE

AĆ84 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 12 Solutions continued

6.—continued

S_DEPT_ID_PK INDEX
S_DEPT_NAME_REGION_ID_UK INDEX
S_EMP TABLE
S_EMP_ID SEQUENCE
S_EMP_ID_PK INDEX
S_EMP_USERID_UK INDEX
S_IMAGE TABLE
S_IMAGE_ID SEQUENCE
S_IMAGE_ID_PK INDEX
S_INVENTORY TABLE
S_INVENTORY_PRODID_WARID_PK INDEX
S_ITEM TABLE
S_ITEM_ORDID_ITEMID_PK INDEX
S_ITEM_ORDID_PRODID_UK INDEX
S_LONGTEXT TABLE
S_LONGTEXT_ID SEQUENCE
S_LONGTEXT_ID_PK INDEX
S_ORD TABLE
S_ORD_ID SEQUENCE
S_ORD_ID_PK INDEX
S_PRODUCT TABLE
S_PRODUCT_ID SEQUENCE
S_PRODUCT_ID_PK INDEX
S_PRODUCT_NAME_UK INDEX
S_REGION TABLE
S_REGION_ID SEQUENCE
S_REGION_ID_PK INDEX
S_REGION_NAME_UK INDEX
S_TITLE TABLE
S_TITLE_TITLE_PK INDEX
S_WAREHOUSE TABLE
S_WAREHOUSE_ID SEQUENCE
S_WAREHOUSE_ID_PK INDEX
WORKER TABLE
WORKER_ID_PK INDEX

44 rows selected.

Practice Solutions AĆ85


Practice 12 Solutions continued

7. Drop the EMPLOYEE table, while leaving the WORKER table in the database.

SQL> DROP TABLE employee;


Table dropped.

8. Modify the WORKER table. Add a TITLE column of VARCHAR2 datatype,


length 30.

SQL> ALTER TABLE worker


2 ADD (title VARCHAR2(30));
Table altered.

SQL> DESCRIBE worker


Name Null? Type
-------------------------- -------- ----
ID NOT NULL NUMBER(7)
LAST_NAME NOT NULL VARCHAR2(25)
FIRST_NAME VARCHAR2(25)
DEPT_ID NOT NULL NUMBER(7)
TITLE VARCHAR2(30)

AĆ86 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 12 Solutions continued

9. Add a comment to the WORKER and DEPARTMENT table definitions


describing the tables. Confirm your additions in the data dictionary.

TABLE_NAME COMMENTS
--------------- ------------------------------
DEPARTMENT Departmental Listing
WORKER Employee Information

SQL> COMMENT ON TABLE department


2 IS ’Departmental Listings’;
Comment created.

SQL> COMMENT ON TABLE worker


2 IS ’Employee Information’;
Comment created.

SQL> SELECT table_name, comments


2 FROM user_tab_comments
3 WHERE table_name IN
4 (’WORKER’,’DEPARTMENT’);

TABLE_NAME COMMENTS
--------------- ------------------------------
DEPARTMENT Departmental Listing
WORKER Employee Information

Practice Solutions AĆ87


Practice 13 Solutions
1. Create a sequence to be used with the DEPARTMENT table’s primary key
column. The sequence should start at 76 and have a maximum value of 80. Be
sure that it increments by one. Name the sequence DEPT_ID_SEQ.

SQL> CREATE SEQUENCE dept_id_seq


2 START WITH 76
3 MAXVALUE 80
4 NOCACHE
5 NOCYCLE;
Sequence created.

2. Create another sequence. This sequence will be used with the WORKER table’s
primary key column. Start this sequence at 204, and set the maximum value to be
9999999. Be sure that it increments by one. Allow the sequence to cache 5
numbers. Name the sequence WORKER_ID_SEQ.

SQL> CREATE SEQUENCE worker_id_seq


2 START WITH 204
3 MAXVALUE 9999999
4 CACHE 5
5 NOCYCLE;
Sequence created.

AĆ88 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 13 Solutions continued

3. Write a script to display the following information about your sequences:


sequence name, cache size, maximum value, increment size, and last number
generated. Name the script p13q3.sql.

SET ECHO OFF


COLUMN sequence_name FORMAT A15
SELECT sequence_name, cache_size, max_value,
increment_by, last_number
FROM user_sequences
WHERE sequence_name
IN (’DEPT_ID_SEQ’,’WORKER_ID_SEQ’)
/
SET ECHO ON

SQL> START p13q3


SET ECHO OFF
SEQUENCE_NAME CACHE_SIZE MAX_VALUE INCREMENT_BY LAST_NUMBER
--------------- ---------- ---------- ------------ -----------
DEPT_ID_SEQ 0 80 1 76
WORKER_ID_SEQ 5 9999999 1 204

4. Write an interactive script to insert a row into the DEPARTMENT table. Name
your script p13q4.sql. Be sure to use the sequence you created for the ID column.
Create a customized prompt to enter the department name. Execute your script.
Add two departments named Education and Administration. Confirm your
additions.

SET ECHO OFF


ACCEPT name PROMPT ’Enter the department name: ’
INSERT INTO department (id, name)
VALUES (dept_id_seq.NEXTVAL, ’&name’)
/
SET ECHO ON

Practice Solutions AĆ89


Practice 13 Solutions continued

4.—continued

SQL> START p13q4


Enter the department name: Education

1 row created.

SQL> START p13q4


Enter the department name: Administration

1 row created.

SQL> SELECT *
2 FROM department;

ID NAME
––– -------------------------
10 Finance
37 Marketing
76 Education
75 Human Resources
54 Sales
77 Administration

AĆ90 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 13 Solutions continued

5. Write a script to insert two rows into the WORKER table. Name your script
p13q5.sql. Use the sequence you create for the ID column. Execute your script.
Add Tomas Lira as the President in the last department you just added to the
table. The other employee is Anna Seigher who is the Vice President in the
Finance department.

SET ECHO OFF


INSERT INTO worker (first_name,
last_name, dept_id, title, id)
VALUES (’&first_name’, ’&last_name’,
&department_number, ’&title’,
worker_id_seq.NEXTVAL)
/
SET ECHO ON

SQL> START p13q5


SQL> SET ECHO OFF
Enter value for first_name: Tomas
Enter value for last_name: Lira
Enter value for department_number: 77
Enter value for title: President

1 row created.

SQL> START p13q5


SQL> SET ECHO OFF
Enter value for first_name: Anna
Enter value for last_name: Seigler
Enter value for department_number: 10
Enter value for title: Vice President

1 row created.

Practice Solutions AĆ91


Practice 13 Solutions continued

6. Confirm your additions to the DEPARTMENT table and WORKER table. Note
the highest primary key values for each table.

SQL> SELECT *
2 FROM department;

ID NAME
---- -------------------------
10 Finance
37 Marketing
76 Education
75 Human Resources
54 Sales
77 Administration

SQL> SELECT *
2 FROM worker;

ID LAST_NAME FIRST_NAME DEPT_ID TITLE


---- ---------- ---------- -------- ---------------
200 Smith Donna 10
204 Lira Tomas 77 President
202 Korsgaard Harry 75
203 Guiliani Rey 37
205 Seigler Anna 10 Vice President

AĆ92 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 13 Solutions continued

7. Display information about your sequences by executing the p13q3.sql script.


Notice that the WORKER_ID_SEQ last number does not match the highest
primary key value in Exercise 6. Why?
" The CACHE value for WORKER_ID_SEQ is 5.

SQL> START p13q3


SET ECHO OFF
SEQUENCE_NAME CACHE_SIZE MAX_VALUE INCREMENT_BY LAST_NUMBER
--------------- ---------- ---------- ------------ -----------
DEPT_ID_SEQ 0 80 1 78
WORKER_ID_SEQ 5 9999999 1 209

8. Execute p13q4.sql to insert four additional departments named Accounting,


Warehouse, Operations, and Research. What happened and why?

SQL> START p13q4


SQL> SET ECHO OFF
Enter the department name: Accounting

1 row created.

SQL> START p13q4


SQL> SET ECHO OFF
Enter the department name: Warehouse

1 row created.

SQL> START p13q4


SQL> SET ECHO OFF
Enter the department name: Operations

1 row created.

Practice Solutions AĆ93


Practice 13 Solutions continued

8.—continued

SQL> START p13q4


SQL> SET ECHO OFF
Enter the department name: Research
VALUES (’Research’,dept_id_seq.NEXTVAL)
*
ERROR at line 2:
ORA-08004: sequence DEPT_ID_SEQ.NEXTVAL exceeds
MAXVALUE and cannot be instantiated

" Reached maxvalue for DEPT_ID_SEQ.


9. Modify your department sequence to allow no maximum value. Verify the change
to the sequence by executing the p13q3.sql script.

SQL> ALTER SEQUENCE dept_id_seq NOMAXVALUE;


Sequence altered.

SQL> START p13q3


SET ECHO OFF
SEQUENCE_NAME CACHE_SIZE MAX_VALUE INCREMENT_BY LAST_NUMBER
--------------- ---------- ---------- ------------ -----------
DEPT_ID_SEQ 0 1.0000E+27 1 80
WORKER_ID_SEQ 5 9999999 1 209

AĆ94 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 13 Solutions continued

10. Add the Research department by using your script named p13q4.sql. Make this
addition permanent.

SQL> START p13q4


SQL> SET ECHO OFF
Enter the department name: Research

1 row created.

SQL> COMMIT;
Commit complete.

11. Display the contents of the DEPARTMENT table and WORKER table.

SQL> SELECT *
2 FROM department;

ID NAME
---- -------------------------
10 Finance
37 Marketing
76 Education
75 Human Resources
54 Sales
77 Administration
78 Accounting
79 Warehouse
80 Operations
81 Research

10 rows selected.

Practice Solutions AĆ95


Practice 13 Solutions continued

11.—continued

SQL> SELECT *
2 FROM worker;

ID LAST_NAME FIRST_NAME DEPT_ID TITLE


---- ---------- ---------- -------- ---------------
200 Smith Donna 10
204 Lira Tomas 77 President
202 Korsgaard Harry 75
203 Guiliani Rey 37
205 Seigler Anna 10 Vice President

AĆ96 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 14 Solutions
1. Create a view called EMP_VU based on the employee number, last name, and
department number from the WORKER table. Change the heading for the last
name to EMPLOYEE.

SQL> CREATE VIEW EMP_VU AS


2 SELECT id, last_name employee,
3 dept_id
5 FROM worker;
View created.

a. Display the content of the EMP_VU view.

SQL> SELECT *
2 FROM emp_vu;

ID EMPLOYEE DEPARTMENT_ID
--------- ------------------------- -------------
200 Smith 10
202 Korsgaard 75
203 Guiliani 37
204 Lira 77
205 Seigler 10

Practice Solutions AĆ97


Practice 14 Solutions continued

1.—continued

b. Write a script to display the definition of a view. Pass the name of the view to
the script. Save the script as p14q1.sql. Execute the script to view the
definition of the EMP_VU view.

SET ECHO OFF


SET VERIFY OFF
SET LONG 200
COLUMN view_name FORMAT A15
COLUMN text FORMAT A50
SELECT *
FROM user_views
WHERE view_name = UPPER(’&view’)
/
COLUMN text CLEAR
COLUMN view_name CLEAR
SET LONG 80
SET ECHO ON

SQL> START p14q1


SQL> SET ECHO OFF
Enter value for view: emp_vu

VIEW_NAME TEXT_LENGTH TEXT


--------------- ----------- ------------------------------
EMP_VU 60 SELECT id, last_name employee,
dept_id
FROM worker

c. Change the department number for Smith to 37 in the EMP_VU view.

SQL> UPDATE emp_vu


2 SET dept_id = 37
3 WHERE employee = ’Smith’;
1 row updated.

AĆ98 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 14 Solutions continued

1.—continued
d. Confirm that Smith is now assigned to department 37.

SQL> SELECT *
2 FROM emp_vu;

ID EMPLOYEE DEPARTMENT_ID
--------- ------------------------- -------------
200 Smith 37
202 Korsgaard 75
203 Guiliani 37
204 Lira 77
205 Seigler 10

2. Create a view called MNS_VU that contains the employee number, full name, and
department name for all employees in the Marketing and Sales departments in the
WORKER and DEPARTMENT tables. Save the command in a script named
p14q2.sql.

SQL> CREATE OR REPLACE VIEW mns_vu AS


2 SELECT w.id, w.first_name||’ ’||w.last_name
3 full_name, d.name
4 FROM worker w, department d
5 WHERE w.dept_id = d.id
6 AND d.id IN (37, 54);
View created.

Practice Solutions AĆ99


Practice 14 Solutions continued

2.—continued

a. Display the structure and contents of the MNP_VU view.

SQL> DESCRIBE mns_vu


Name Null? Type
----------------------------- -------- ----
ID NOT NULL NUMBER(7)
FULL_NAME VARCHAR2(51)
NAME VARCHAR2(25)

SQL> SELECT *
2 FROM mns_vu;

ID FULL_NAME NAME
--------- ------------------------ -------------
200 Donna Smith Marketing
203 Rey Guiliani Marketing

b. Display the definition of the MNS_VU view by executing the p14q1.sql


script.

SQL> START p14q1


SQL> SET ECHO OFF
Enter value for view: mns_vu

VIEW_NAME TEXT_LENGTH TEXT


-------------- ----------- ------------------------------
MNS_VU 140 SELECT w.id, w.first_name||’ ’
||w.last_name full_name, d.nam
e
FROM worker w, dept d
WHERE w.dept_id = d.id
AND d.id IN (37, 54)

AĆ100 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 14 Solutions continued

2.—continued

c. Display the department name and number of employees in each department.

SQL> SELECT name, COUNT(*)


2 FROM mns_vu
3 GROUP BY name;

NAME COUNT(*)
------------------------- ---------
Marketing 2

3. Modify EMP_VU view to contain only those employees in department 37. Add a
check constraint so that the department number cannot be modified.

SQL> CREATE OR REPLACE VIEW EMP_VU AS


2 SELECT id, last_name employee,
3 dept_id
4 FROM worker
5 WHERE dept_id = 37
6 WITH CHECK OPTION CONSTRAINT emp_dept_id_37;
View created.

a. Display the contents of the EMP_VU view.

SQL> SELECT *
2 FROM emp_vu;

ID EMPLOYEE DEPT_ID
--------- ------------------------- -------------
200 Smith 37
203 Guiliani 37

Practice Solutions AĆ101


Practice 14 Solutions continued

3.—continued
b. Change the department number for Smith back to 54 through the EMP_VU
view. Was your operation successful? Why or why not?

SQL> UPDATE emp_vu


2 SET dept_id = 54
3 WHERE employee = ’Smith’;
WHERE employee = ’Smith’
*
ERROR at line 3:
ORA-01402: view WITH CHECK OPTION where-clause
violation

" The operation was unsuccessful because the CHECK OPTION


constraint does not allow the department number to be changed in the
view.
4. Modify the MNS_VU so that the rows can only be seen between 1:00 P.M. and
4:00 P.M. You can edit the script named p14q2.sql. Execute the script. Display the
contents of the view.

CREATE OR REPLACE VIEW MNS_VU


AS SELECT w.id, w.first_name||’ ’||w.last_name
full_name, d.name
FROM worker w, department d
WHERE w.dept_id = d.id
AND d.id IN (37, 54)
AND TO_CHAR(SYSDATE,’hh24mi’)
BETWEEN ’1300’ and ’1600’;

SQL> START p14q2


View created.

AĆ102 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 14 Solutions continued

4.—continued

" If your server’s time is between the time range specified, you will see
the following result. Otherwise, the SELECT statement yields no rows.

SQL> SELECT *
2 FROM mns_vu;

ID FULL_NAME NAME
--------- ------------------------ ---------------
200 Donna Smith Marketing
203 Rey Guiliani Marketing

5. Remove all views from the data dictionary. Confirm that no views exist in the
data dictionary.

SQL> SELECT view_name


2 FROM user_views;

VIEW_NAME
------------------------------
EMP_VU
MNS_VU

SQL> DROP VIEW emp_vu;


View dropped.

SQL> DROP VIEW mns_vu;


View dropped.

Practice Solutions AĆ103


Practice 14 Solutions continued

5.—continued

SQL> SELECT view_name


2 FROM user_views;
no rows selected

AĆ104 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 15 Solutions
1. Would an indexes specified be used with the following queries and why?
a. Non-unique index on LAST_NAME.
" Yes because the LAST_NAME column is used in the WHERE clause.

SQL> SELECT *
2 FROM s_emp
3 WHERE last_name = ’Biri’;

b. Unique index on ID and non-unique index on CUSTOMER_ID.


" No because the WHERE clause does not specify a column that has an
index on it.

SQL> SELECT id, customer_id, total


2 FROM s_ord
3 WHERE date_ordered = ’31-AUG-92’;

c. Unique index on S_DEPT.ID and non-unique index on S_EMP.DEPT_ID.


" Yes because both columns are in the WHERE clause.

SQL> SELECT e.last_name, d.name


2 FROM s_emp e, s_dept d
3 WHERE e.dept_id = d.id;

Practice Solutions AĆ105


Practice 15 Solutions continued

2. Create a non-unique index on the foreign key column in the WORKER table.

SQL> CREATE INDEX worker_dept_id_idx


2 ON worker(dept_id);
Index created.

3. Since users will frequently query on the employee last name, create a non-unique
index on that column in the WORKER table.

SQL> CREATE INDEX worker_last_name_idx


2 ON worker(last_name);
Index created.

4. Display the indexes and uniqueness that exist in the data dictionary for the
WORKER and DEPARTMENT tables. Save the command into a script named
p15q4.sql.

SET ECHO OFF


COLUMN index_name FORMAT A20
COLUMN table_name FORMAT A15
SELECT index_name, table_name, uniqueness
FROM user_indexes
WHERE table_name
IN (’WORKER’,’DEPARTMENT’)
/
COLUMN index_name CLEAR
COLUMN table_name CLEAR
SET ECHO ON

AĆ106 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 15 Solutions continued

4.—continued

SQL> START p15q4


SET ECHO OFF

INDEX_NAME TABLE_NAME UNIQUENES


-------------------- --------------- ---------
DEPT_ID_PK DEPARTMENT UNIQUE
WORKER_DEPT_ID_IDX WORKER NONUNIQUE
WORKER_ID_PK WORKER UNIQUE
WORKER_LAST_NAME_IDX WORKER NONUNIQUE

5. Remove the primary key constraint on the WORKER table.

SQL> ALTER TABLE worker


2 DROP CONSTRAINT worker_id_pk;
Table altered.

6. Re-display the indexes and uniqueness that exist in the data dictionary for the
WORKER and DEPARTMENT tables by executing the p15q4.sql script. What
changes do you observe and why?
" The WORKER_ID_PK index is no longer in the list because when the
primary key constraint on the WORKER table was dropped, the index was
no longer required and therefore automatically removed.

SQL> START p15q4


SET ECHO OFF

INDEX_NAME TABLE_NAME UNIQUENES


-------------------- --------------- ---------
DEPT_ID_PK DEPARTMENT UNIQUE
WORKER_DEPT_ID_IDX WORKER NONUNIQUE
WORKER_LAST_NAME_IDX WORKER NONUNIQUE

Practice Solutions AĆ107


Practice 15 Solutions continued

7. Re-create the primary key constraint on the WORKER table. Confirm the
constraint in the data dictionary by executing pl2q2.sql. Confirm the unique index
in the data dictionary by executing pl5q4.

SQL> ALTER TABLE worker


2 ADD CONSTRAINT worker_id_pk PRIMARY KEY(id);
Table altered.

SQL> START pl2q2


CONSTRAINT_NAME C
------------------- -
SYS_C00108623 C
SYS_C00108624 C
WORKER_ID_PK P
WORKER_DEPT_ID_FK R

SQL> START p15q4


SET ECHO OFF

INDEX_NAME TABLE_NAME UNIQUENES


-------------------- --------------- ---------
DEPT_ID_PK DEPARTMENT UNIQUE
WORKER_DEPT_ID_IDX WORKER NONUNIQUE
WORKER_ID_PK WORKER UNIQUE
WORKER_LAST_NAME_IDX WORKER NONUNIQUE

8. Remove the index on the employee last name from the WORKER table.

SQL> DROP INDEX worker_last_name_idx;


Index dropped.

AĆ108 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 16 Solutions
1. What privilege should a user be given to log in to the Oracle7 Server? Is this
privilege a system or object privilege?
" The CREATE SESSION system privilege.
2. What privilege should a user be given to create tables?
" The CREATE TABLE privilege.
3. If you create a table, who can pass along privileges to other users on your table?
" You can, or anyone you have given those privileges to by using the WITH
GRANT OPTION.
4. You are the DBA. You are creating many users who require the same system
privileges. What would you use to make your job easier?
" Create a role containing the system privileges and allocate the role to the
users.
5. What command do you use to change your password?
" The ALTER USER command.
6. Grant other users query access to your S_REGION table. Have them grant you
query access to their S_REGION table.
" Team 2 executes the GRANT command.

SQL> GRANT select


2 ON s_region
3 TO user1;
Grant succeeded.

" Team 1 executes the GRANT command.

SQL> GRANT select


2 ON s_region
3 TO user2;
Grant succeeded.

" Where user1 is the name of team 1 and user2 is the name of team 2.

Practice Solutions AĆ109


Practice 16 Solutions continued

7. Query all the rows in your S_REGION table.

SQL> SELECT *
2 FROM s_region;

ID NAME
------- ---------------
1 North America
2 South America
3 Africa / Middle East
4 Asia
5 Europe

8. Add a new row to your S_REGION table. Team 1 should add Central America as
region number 6. Team 2 should add Micronesia as region number 7. Make the
changes permanent.
" Team 1 executes this INSERT command.

SQL> INSERT INTO s_region (id, name)


2 VALUES (6, ’Central America’);
1 row created.
SQL> COMMIT;
Commit completed.

" Team 2 executes this INSERT command.

SQL> INSERT INTO s_region (id, name)


2 VALUES (7, ’Micronesia’);
1 row created.
SQL> COMMIT;
Commit completed.

AĆ110 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 16 Solutions continued

9. Query the other team’s S_REGION table.


" Team 1 executes the query.

SQL> SELECT *
2 FROM user2.s_region;

ID NAME
------- ---------------
1 North America
2 South America
3 Africa / Middle East
4 Asia
5 Europe
7 Micronesia

6 rows selected.

" Team 2 executes the query.

SQL> SELECT *
2 FROM user1.s_region;

ID NAME
------- ---------------
1 North America
2 South America
3 Africa / Middle East
4 Asia
5 Europe
6 Centeral America

6 rows selected.

Practice Solutions AĆ111


Practice 16 Solutions continued

10. Create a synonym for the other team’s S_REGION table.


" Team 1 creates a synonym named team2.

SQL> CREATE SYNONYM team2


2 FOR user2.s_region;
Synonynm created.

" Team 2 creates a synonym named team1.

SQL> CREATE SYNONYM team1


2 FOR user1.s_region;
Synonynm created.

11. Display the other team’s S_REGION table contents by using your synonym.
" Team 1 executes the query.

SQL> SELECT *
2 FROM team2;

ID NAME
------- ---------------
1 North America
2 South America
3 Africa / Middle East
4 Asia
5 Europe
7 Micronesia

6 rows selected.

AĆ112 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 16 Solutions continued

11.—continued
" Team 2 executes the query.

SQL> SELECT *
2 FROM team1;

ID NAME
------- ---------------
1 North America
2 South America
3 Africa / Middle East
4 Asia
5 Europe
6 Central America

6 rows selected.

12. Confirm the privileges in effect for your team’s tables.


" Team 1 executes the query.

SQL> SELECT *
2 FROM user_tab_privs_made;

GRANTEE TABLE_NAME GRANTOR PRIVILEGE GRA


-------- ------------ -------- --------- ---
user2 S_REGION user1 SELECT NO

Practice Solutions AĆ113


Practice 16 Solutions continued

12.—continued
" Team 2 executes the query.

SQL> SELECT *
2 FROM user_tab_privs_made;

GRANTEE TABLE_NAME GRANTOR PRIVILEGE GRA


-------- ------------ -------- --------- ---
user1 S_REGION user2 SELECT NO

13. Revoke the SELECT privilege from the other team.


" Team 1 revokes the privilege.

SQL> REVOKE select


2 ON s_region
3 FROM user2;
Revoke succeeded.

" Team 2 revokes the privilege.

SQL> REVOKE select


2 ON s_region
3 FROM user1;
Revoke succeeded.

AĆ114 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 16 Solutions continued

14. Attempt to SELECT from the other team’s S_REGION table.


" Team 1 executes the query.

SQL> SELECT *
2 FROM team2;
Error at line 1:
ORA-00942: table or view does not exist

" Team 2 executes the query.

SQL> SELECT *
2 FROM team1;
Error at line 1:
ORA-00942: table or view does not exist

15. Drop the synonym you created.


" Team 1 drops the synonym.

SQL> DROP SYNONYM team2;


Synonym dropped.

" Team 2 drops the synonym.

SQL> DROP SYNONYM team1;


Synonym dropped.

Practice Solutions AĆ115


Practice 17 Solutions
1. Create the tables based on the entity relationship diagram on the previous page
and the table instance charts below. Choose the appropriate datatypes and be sure
to add the integrity constraints.
a. Table name: MEMBER

Column MEMBER_ LAST_ FIRST_ ADDRESS CITY PHONE JOIN_DATE


Name ID NAME NAME

Key PK
Type
Null/ NN, U NN NN
Unique
Default System date
Value
Datatype number char char char char char date
Length 10 25 25 100 30 15

SQL> CREATE TABLE MEMBER


2 (member_id NUMBER (10)
3 CONSTRAINT member_id_pk PRIMARY KEY,
4 last_name VARCHAR2(25)
5 CONSTRAINT member_last_nn NOT NULL,
6 first_name VARCHAR2(25),
7 address VARCHAR2(100),
8 city VARCHAR2(30),
9 phone VARCHAR2(15),
10 join_date DATE DEFAULT SYSDATE
11 CONSTRAINT join_date_nn NOT NULL);
Table created.

AĆ116 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 17 Solutions continued

1.—continued
b. Table name: TITLE

Column TITLE_ RELEASE_


Name ID TITLE DESCRIPTION RATING CATEGORY DATE

Key PK
Type
Null/ NN, U NN NN
Unique
Check G, PG, DRAMA,
R, COMEDY,
NC17, ACTION,
NR CHILD, SCIFI,
DOCUMENTA
RY
Default DRAMA
Value
Datatype number char char char char date
Length 10 60 400 4 20

Practice Solutions AĆ117


Practice 17 Solutions continued

1b.—continued

SQL> CREATE TABLE title


2 (title_id NUMBER(10)
3 CONSTRAINT title_id_pk PRIMARY KEY,
4 title VARCHAR2(60)
5 CONSTRAINT title_nn NOT NULL,
6 description VARCHAR2(400)
7 CONSTRAINT title_desc_nn NOT NULL,
8 rating VARCHAR2(4)
9 CONSTRAINT title_rating_ck CHECK
10 (rating IN (’G’,’PG’,’R’,’NC17’,’NR’)),
11 category VARCHAR2(20) DEFAULT ’DRAMA’
12 CONSTRAINT title_categ_ck CHECK
13 (category IN (’DRAMA’, ’COMEDY’, ’ACTION’,
14 ’CHILD’, ’SCIFI’, ’DOCUMENTARY’)),
15 release_date DATE);
Table created.

AĆ118 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 17 Solutions continued

1.—continued
c. Table name: TITLE_COPY

Column COPY_ID TITLE_ID STATUS


Name
Key Type PK PK, FK
Null/ NN, U NN, U NN
Unique
Check AVAILABLE, DESTROYED,
RENTED, RESERVED
FK Ref title
Table
FK Ref Col title_id
Datatype number number char
Length 10 10 15

SQL> CREATE TABLE title_copy


2 (copy_id NUMBER(10),
3 title_id NUMBER(10)
4 CONSTRAINT copy_title_id_fk REFERENCES
5 title(title_id),
6 status VARCHAR2(15)
7 CONSTRAINT copy_status_nn NOT NULL
8 CONSTRAINT copy_status_ck CHECK
9 (status IN (’AVAILABLE’, ’DESTROYED’,
10 ’RENTED’, ’RESERVED’)),
11 CONSTRAINT copy_title_id_pk
12 PRIMARY KEY(copy_id, title_id));
Table created.

Practice Solutions AĆ119


Practice 17 Solutions continued

1.—continued

d. Table name: RENTAL

Column BOOK_ MEMBER_ COPY_ID ACT_RET_ EXP_RET_ TITLE_ID


Name DATE ID DATE DATE

Key Type PK FK PK, FK PK, FK


Null/ NN,U NN NN,U NN,U
Unique
Default System 2 days
Value date after book
date
FK Ref member title_copy title_copy
Table
FK Ref member_id copy_id title_id
Col
Datatype date number number date date number
Length 10 10 10

SQL> CREATE TABLE rental


2 (book_date DATE DEFAULT SYSDATE,
3 member_id NUMBER(10)
4 CONSTRAINT rental_mbr_id_fk
5 REFERENCES member(member_id),
6 copy_id NUMBER(10),
7 act_ret_date DATE,
8 exp_ret_date DATE DEFAULT SYSDATE + 2,
9 CONSTRAINT rental_copy_title_id_fk
10 FOREIGN KEY (copy_id, title_id)
11 REFERENCES title_copy(copy_id, title_id),
12 title_id NUMBER(10),
13 CONSTRAINT rental_id_pk PRIMARY KEY
14 (book_date, copy_id, title_id));
Table created.

AĆ120 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 17 Solutions continued

1.—continued
e. Table name: RESERVATION

Column Name RES_DATE MEMBER_ID TITLE_ID

Key Type PK PK, FK PK, FK


Null/ NN,U NN,U NN,U
Unique
FK Ref Table member title
FK Ref Col member_id title_id
Datatype date number number
Length 10 10

SQL> CREATE TABLE reservation


2 (res_date DATE,
3 member_id NUMBER(10)
4 CONSTRAINT res_member_id_fk
5 REFERENCES member (member_id),
6 title_id NUMBER(10)
7 CONSTRAINT res_title_id_fk
8 REFERENCES title (title_id),
9 CONSTRAINT res_id_pk PRIMARY KEY
10 (res_date, member_id, title_id));
Table created.

Practice Solutions AĆ121


Practice 17 Solutions continued

2. Verify that the tables and constraints were created properly by checking the data
dictionary.

SQL> SELECT object_name


2 FROM user_objects
3 WHERE object_name IN (’MEMBER’,’TITLE’,
4 ’TITLE_COPY’,’RENTAL’,’RESERVATION’);

OBJECT_NAME
-------------------
RESERVATION
RENTAL
TITLE_COPY
TITLE
MEMBER

SQL> SELECT constraint_name, constraint_type,


2 table_name, search_condition,
3 r_constraint_name
4 FROM user_constraints
5 WHERE table_name IN (’MEMBER’,’TITLE’,
6 ’TITLE_COPY’,’RENTAL’,’RESERVATION’);

AĆ122 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 17 Solutions continued

2.—continued

CONSTRAINT_NAME C TABLE_NAME SEARCH_CONDITION


R_CONSTRAINT_NAME
-------------------- - --------------- ---------------------–
-----------------–––
MEMBER_LAST_NN C MEMBER LAST_NAME IS NOT NULL
JOIN_DATE_NN C MEMBER JOIN_DATE IS NOT NULL
MEMBER_ID_PK P MEMBER
RENTAL_ID_PK P RENTAL
RENTAL_MBR_ID_FK R RENTAL
MEMBER_ID_PK
RENTAL_COPY_TITLE_ID R RENTAL
COPY_TITLE_ID_PK_FK
RES_MEMBER_ID_FK R RESERVATION
MEMBER_ID_PK
RES_TITLE_ID_FK R RESERVATION
TITLE_ID_PK
RES_ID_PK P RESERVATION
TITLE_NN C TITLE TITLE IS NOT NULL
TITLE_DESC_NN C TITLE DESCRIPTION IS NOT NU
LL
TITLE_ID_PK P TITLE
TITLE_RATING_NN C TITLE RATING IS NOT NULL
TITLE_RATING_CK C TITLE rating IN (’G’,’PG’,
’R’,’NC17’,’NR’)
TITLE_CATEG_NN C TITLE RATING IS NOT NULL
TITLE_CATEG_CK C TITLE category IN (’DRAMA’,
’COMEDY’,’ACTION’,
’CHILD’,’SCIFI’,
’DOCUMENTARY’)
COPY_STATUS_NN C TITLE_COPY STATUS IS NOT NULL
COPY_STATUS_CK C TITLE_COPY status IN (’AVAILABLE’,
’DESTROYED’,’RENTED’,
’RESERVED’)
COPY_TITLE_ID_PK P TITLE_COPY
COPY_TITLE_ID_FK R TITLE_COPY

16 rows selected.

Practice Solutions AĆ123


Practice 17 Solutions continued

3. Create sequences to uniquely identify each row in the MEMBER table and the
TITLE table.
a. Member number for the MEMBER table, start with 101, do not allow caching
of the values.

SQL> CREATE SEQUENCE member_id_seq


2 START WITH 101
3 NOCACHE;
Sequence created.

b. Title number for the TITLE table, start with 92, no caching.

SQL> CREATE SEQUENCE title_id_seq


2 START WITH 92
3 NOCACHE;
Sequence created.

c. Verify the existence of the sequences in the data dictionary.

SQL> SELECT sequence_name, increment_by,


2 last_number
3 FROM user_sequences
4 WHERE sequence_name IN (’MEMBER_ID_SEQ’,
5 ’TITLE_ID_SEQ’);

SEQUENCE_NAME INCREMENT_BY LAST_NUMBER


--------------- ------------ -----------
MEMBER_ID_SEQ 1 101
TITLE_ID_SEQ 1 92

AĆ124 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 17 Solutions continued

4. Add data to the tables. Create a script for each set of data to add.
a. Add movie titles to the TITLE table. Write a script to enter the movie
information. Save the script as p17q4a.sql. Use the sequence to uniquely
identify each title. Remember that single quotation marks in a character field
must be specially handled. Verify your additions.

Title Description Rating Category Release date


Willie and All of Willie’s friends made a G CHILD 05-OCT-95
Christmas Christmas list for Santa, but
Too Willie has yet to add his own
wish list.
Alien Again Yet another installment of R SCIFI 19-MAY-95
science fiction history. Can
the heroine save the planet
from the alien life form?
The Glob A meteor crashes near a NR SCIFI 12-AUG-95
small American town and
unleashes carnivorous goo in
this classic.
My Day Off With a little luck and a lot of PG COMEDY 12-JUL-95
ingenuity, a teenager skips
school for a day in New
York.
Miracles on A six-year-old has doubts PG DRAMA 12-SEP-95
Ice about Santa Claus. But she
discovers that miracles really
do exist.
Soda Gang After discovering a cache of NR ACTION 01-JUN-95
drugs, a young couple find
themselves pitted against a
vicious gang.

Practice Solutions AĆ125


Practice 17 Solutions continued

4a.—continued

SET ECHO OFF


INSERT INTO title (title_id, title, description,
rating, category, release_date)
VALUES (title_id_seq.nextval,
’Willie and Christmas Too’,
’All of Willie’’s friends made a Christmas list
for Santa, but Willie has yet to add his own
wish list.’,
’G’,’CHILD’,’05-OCT-95’)
/
INSERT INTO title (title_id, title, description,
rating, category, release_date)
VALUES (title_id_seq.nextval, ’Alien Again’,
’Yet another installment of science fiction
history. Can the heroine save the planet from the
alien life form?’,
’R’, ’SCIFI’, ’19-MAY-95’)
/
INSERT INTO title (title_id, title, description,
rating, category, release_date)
VALUES (title_id_seq.nextval, ’The Glob’, ’A meteor
crashes near a small American town and unleashes
carnivorous goo in this classic.’,
’NR’, ’SCIFI’, ’12-AUG-95’)
/
INSERT INTO title (title_id, title, description,
rating, category, release_date)
VALUES (title_id_seq.nextval, ’My Day Off’,
’With a little luck and a lot of ingenuity, a
teenager skips school for a day in New York.’,
’PG’, ’COMEDY’, ’12-JUL-95’)
/

AĆ126 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 17 Solutions continued

4a.—continued

INSERT INTO title (title_id, title, description,


rating, category, release_date)
VALUES (title_id_seq.nextval, ’Miracles on Ice’,
’A six-year-old has doubts about Santa Claus.
But she discovers that miracles really do exist.’,
’PG’, ’DRAMA’, ’12-SEP-95’)
/
INSERT INTO title (title_id, title, description,
rating, category, release_date)
VALUES (title_id_seq.nextval, ’Soda Gang’,
’After discovering a cache of drugs, a young couple
find themselves pitted against a vicious gang.’,
’NR’, ’ACTION’, ’01-JUN-95’)
/
COMMIT
/
SET ECHO ON

SQL> START p17q4a


SET ECHO OFF
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
Commit complete.

Practice Solutions AĆ127


Practice 17 Solutions continued

4a.—continued

SQL> SELECT *
2 FROM title
3 ORDER BY title_id;

TITLE_ID TITLE
---------- -------------------------
DESCRIPTION
-------------------------------------------------
RATI CATEGORY RELEASE_D
---- -------------------- ---------
92 Willie and Christmas Too
All of Willie’s friends made a Christmas list for
Santa, but Willie has yet to create his own
wish list.
G CHILD 05-OCT-95

93 Alien Again
Another installment of science fiction history.
Can the heroine save the planet from the alien
life form?
R SCIFI 19-MAY-95

94 The Glob
A meteor crashes near a small American town and
unleashes carnivorous goo in this classic.
NR SCIFI 12-AUG-95

95 My Day Off
With a little luck and a lot of ingenuity, a
teenager skips school for a day in New York.
PG COMEDY 12-JUL-95

AĆ128 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 17 Solutions continued

4a.—continued

TITLE_ID TITLE
---------- -------------------------
DESCRIPTION
-------------------------------------------------
RATI CATEGORY RELEASE_D
---- -------------------- ---------

96 Miracles on Ice
A six-year-old has doubts about Santa Claus. But
she discovers that miracles really do exist.
PG DRAMA 12-SEP-95

97 Soda Gang
After discovering a cached of drugs, a young
couple find themselves pitted against a vicious
gang.
NR ACTION 01-JUN-95

6 rows selected.

Practice Solutions AĆ129


Practice 17 Solutions continued

4.—continued
b. Add data to the MEMBER table. Write a script named p17q4b.sql to prompt
users for the information. Execute the script. Be sure to use the sequence to
add the member numbers.

First
name Last name Address City Phone Join date
Carmen Velasquez 283 King Seattle 206-899-6666 08-MAR-90
Street
LaDoris Ngao 5 Bratislava 586-355-8882 08-MAR-90
Modrany
Midori Nagayama 68 Via Sao Paolo 254-852-5764 17-JUN-91
Centrale
Mark Quick-To-See 6921 King Lagos 63-559-7777 07-APR-90
Way
Audry Ropeburn 86 Chu Hong 41-559-87 18-JAN-91
Street Kong
Molly Urguhart 3035 Quebec 418-542-9988 18-JAN-91
Laurier
Blvd

" Script p17q4b.sql contents.

SET ECHO OFF


INSERT INTO member (member_id, first_name, last_name,
address, city, phone, join_date)
VALUES (member_id_seq.NEXTVAL, ’&first_name’,
’&last_name’, ’&address’,
’&city’,’&phone’,’&join_date’)
/
COMMIT
/
SET ECHO ON

AĆ130 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 17 Solutions continued

4b.—continued

SQL> START p17q4b


SET ECHO OFF
Enter value for first_name: Carmen
Enter value for last_name: Velasquez
Enter value for address: 283 King Street
Enter value for city: Seattle
Enter value for phone: 206-899-6666
Enter value for join_date: 08-MAR-90
1 row created.
Commit complete.

SQL> START p17q4b


SET ECHO OFF
Enter value for first_name: LaDoris
Enter value for last_name: Ngao
Enter value for address: 5 Modrany
Enter value for city: Bratislava
Enter value for phone: 586-355-8882
Enter value for join_date: 08-MAR-90
1 row created.
Commit complete.

SQL> START p17q4b


SET ECHO OFF
Enter value for first_name: Midori
Enter value for last_name: Nagayama
Enter value for address: 68 Via Centrale
Enter value for city: Sao Paolo
Enter value for phone: 254-852-5764
Enter value for join_date: 17-JUN-91
1 row created.
Commit complete.

Practice Solutions AĆ131


Practice 17 Solutions continued

4b.—continued

SQL> START p17q4b


SET ECHO OFF
Enter value for first_name: Mark
Enter value for last_name: Quick-To-See
Enter value for address: 6921 King Way
Enter value for city: Lagos
Enter value for phone: 63-559-7777
Enter value for join_date: 07-APR-90
1 row created.
Commit complete.

SQL> START p17q4b


SET ECHO OFF
Enter value for first_name: Audry
Enter value for last_name: Ropeburn
Enter value for address: 86 Chu Street
Enter value for city: Hong Kong
Enter value for phone: 41-559-87
Enter value for join_date: 18-JAN-91
1 row created.
Commit complete.

SQL> START p17q4b


SET ECHO OFF
Enter value for first_name: Molly
Enter value for last_name: Urguhart
Enter value for address: 3035 Laurier Blvd
Enter value for city: Quebec
Enter value for phone: 418-542-9988
Enter value for join_date: 18-JAN-91
1 row created.
Commit complete.

AĆ132 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 17 Solutions continued

4b.—continued
" Verify the additions.

SQL> SELECT *
2 FROM member
3 ORDER BY member_id;

MEMBER_ID LAST_NAME FIRST_NAME


---------- ---------- ----------
ADDRESS CITY
------------------------------ ----------
PHONE JOIN_DATE
--------------- ---------
101 Velasquez Carmen
283 King Street Seattle
206-899-6666 03-MAR-90

102 Ngao LaDoris


5 Modrany Bratislava
586-355-8882 08-MAR-90

103 Nagayama Midori


68 Via Centrale Sao Paolo
254-852-5764 17-JUN-91

104 Quick-To-S Mark


ee
6921 King Way Lagos
63-559-777 07-APR-90

Practice Solutions AĆ133


Practice 17 Solutions continued

4b.—continued

MEMBER_ID LAST_NAME FIRST_NAME


---------- ---------- ----------
ADDRESS CITY
------------------------------ ----------
PHONE JOIN_DATE
--------------- ---------

105 Ropeburn Audry


86 Chu Street Hong Kong
41-559-87 04-MAR-90

106 Urguhart Molly


3035 Laurier Blvd. Quebec
418-542-9988 18-JAN-91

6 rows selected.

AĆ134 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 17 Solutions continued

4.—continued
c. Add the following movie copies in the TITLE_COPY table:

Title Copy number Status


Willie and Christmas Too 1 Available
Alien Again 1 Available
2 Rented
The Glob 1 Available
My Day Off 1 Available
2 Available
3 Rented
Miracles on Ice 1 Available
Soda Gang 1 Available

Practice Solutions AĆ135


Practice 17 Solutions continued

4c.—continued
" Script p17q4c.sql contents.

SET ECHO OFF


INSERT INTO title_copy (copy_id, title_id, status)
VALUES (1, 92, ’AVAILABLE’)
/
INSERT INTO title_copy (copy_id, title_id, status)
VALUES (1, 93, ’AVAILABLE’)
/
INSERT INTO title_copy (copy_id, title_id, status)
VALUES (2, 93, ’RENTED’)
/
INSERT INTO title_copy (copy_id, title_id, status)
VALUES (1, 94, ’AVAILABLE’)
/
INSERT INTO title_copy (copy_id, title_id, status)
VALUES (1, 95, ’AVAILABLE’)
/
INSERT INTO title_copy (copy_id, title_id, status)
VALUES (2, 95, ’AVAILABLE’)
/
INSERT INTO title_copy (copy_id, title_id, status)
VALUES (3, 95, ’RENTED’)
/
INSERT INTO title_copy (copy_id, title_id, status)
VALUES (1, 96, ’AVAILABLE’)
/
INSERT INTO title_copy (copy_id, title_id, status)
VALUES (1, 97, ’AVAILABLE’)
/
COMMIT
/
SET ECHO ON

AĆ136 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 17 Solutions continued

4c.—continued

SQL> START p17q4c


SET ECHO OFF
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
Commit complete.

" Verify the additions.

SQL> SELECT *
2 FROM title_copy
3 ORDER BY title_id, copy_id;

COPY_ID TITLE_ID STATUS


---------- ---------- ---------------
1 92 AVAILABLE
1 93 AVAILABLE
2 93 RENTED
1 94 AVAILABLE
1 95 AVAILABLE
2 95 AVAILABLE
3 95 RENTED
1 96 AVAILABLE
1 97 AVAILABLE

9 rows selected.

Practice Solutions AĆ137


Practice 17 Solutions continued

4.—continued
d. Add the following rentals to the RENTAL table:

Title Copy Customer Date rented Date return Date


number expected returned
Willie and 1 101 3 days ago 1 day ago 2 days ago
Christmas Too
Alien Again 2 101 1 day ago 1 day from
now
My Day Off 3 102 2 days ago Today
Soda Gang 1 106 4 days ago 2 days ago 2 days ago

SQL> INSERT INTO rental (title_id, copy_id


2 member_id, book_date, exp_ret_date,
3 act_ret_date)
4 VALUES (92, 1, 101, SYSDATE-3,
5 SYSDATE-1, SYSDATE-2);
1 row created.

SQL> INSERT INTO rental (title_id, copy_id


2 member_id, book_date, exp_ret_date,
3 act_ret_date)
4 VALUES (93, 2, 101, SYSDATE-1,
5 SYSDATE+1, null);
1 row created.

SQL> INSERT INTO rental (title_id, copy_id


2 member_id, book_date, exp_ret_date,
3 act_ret_date)
4 VALUES (95, 3, 102, SYSDATE-2,
5 SYSDATE, null);
1 row created.

AĆ138 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 17 Solutions continued

4d.—continued

SQL> INSERT INTO rental (title_id, copy_id


2 member_id, book_date, exp_ret_date,
3 act_ret_date)
4 VALUES (97, 1, 106, SYSDATE-4,
5 SYSDATE-2, SYSDATE-2);
1 row created.

SQL> COMMIT;
Commit complete

" Verify your additions.

SQL> SELECT *
2 FROM rental
3 ORDER BY title_id;

BOOK_DATE MEMBER_ID COPY_ID ACT_RET_D


--------- ---------- ---------- ---------
EXP_RET_D TITLE_ID
--------- ----------
07-FEB-96 101 1 08-FEB-96
09-FEB-96 92

09-FEB-96 101 2
11-FEB-96 93

08-FEB-96 102 3
10-FEB-96 95

06-FEB-96 106 1 08-FEB-96


08-FEB-96 97

Practice Solutions AĆ139


Practice 17 Solutions continued

5. Create a view named TITLE_AVAIL to show the movie titles and the availability
of each copy and its expected return date if rented. Query all rows from the view.

SQL> CREATE VIEW title_avail AS


2 SELECT t.title, c.copy_id, c.status,
3 r.exp_ret_date
4 FROM title t, title_copy c, rental r
5 WHERE t.title_id = c.title_id
6 AND c.copy_id = r.copy_id(+)
7 AND c.title_id = r.title_id(+);
View created.

SQL> SELECT *
2 FROM title_avail
3 ORDER BY title, copy_id;

TITLE COPY_ID STATUS EXP_RET_D


--------------- -------- ---------- ---------
Alien Again 1 AVAILABLE
Alien Again 2 RENTED 11-FEB-96
Miracles on Ice 1 AVAILABLE
My Day Off 1 AVAILABLE
My Day Off 2 AVAILABLE
My Day Off 3 RENTED 10-FEB-96
Soda Gang 1 AVAILABLE 08-FEB-96
The Glob 1 AVAILABLE
Willie and 1 AVAILABLE 09-FEB-96
Christmas Too

9 rows selected.

AĆ140 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 17 Solutions continued

6. Make changes to data in the tables.


a. Add a new title. The movie is “Interstellar Wars”, which is rated PG, and
classified as a SCIFI movie. The release date is 07-JUL-77. The description is
“Futuristic interstellar action movie. Can the rebels save the humans from the
evil Empire?” Be sure to add a title copy record for two copies.

SQL> INSERT INTO title (title_id, title,


2 description, rating, category, release_date)
3 VALUES (title_id_seq.nextval,
4 ’Interstellar Wars’,
5 ’Futuristic interstellar action movie. Can the
6 rebels save the humans from the evil Empire?’,
7 ’PG’, ’SCIFI’, ’07-JUL-77’);
1 row created.

" Obtain the title number for use in the TITLE_COPY table.

SQL> SELECT title_id, title


2 FROM title
3 WHERE title = ’Interstellar Wars’;

TITLE_ID TITLE
---------- ---------------------
98 Interstellar Wars

" Insert a record for the copies into the TITLE_COPY table.

SQL> INSERT INTO title_copy (copy_id, title_id,


2 status)
3 VALUES (1, 98, ’AVAILABLE’);
1 row created.

Practice Solutions AĆ141


Practice 17 Solutions continued

6a.—continued

SQL> INSERT INTO title_copy (copy_id, title_id,


2 status)
3 VALUES (2, 98, ’AVAILABLE’);
1 row created.

b. Enter two reservations. One reservation is for Carmen Velasquez who wants
to rent “Interstellar Wars.” The other is for Mark Quick-To-See who wants to
rent “Soda Gang”.

SQL> SELECT member_id, first_name, last_name


2 FROM member
3 WHERE last_name
4 IN (’Velasquez’,’Quick-To-See’);

MEMBER_ID FIRST_NAME LAST_NAME


---------- ---------- ------------
101 Carmen Velasquez
104 Mark Quick-To-See

SQL> SELECT title_id, title


2 FROM title
3 WHERE title
4 IN (’Interstellar Wars’,’Soda Gang’);

TITLE_ID TITLE
---------- ---------------
97 Soda Gang
98 Interstellar
Wars

AĆ142 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 17 Solutions continued

6b.—continued

SQL> INSERT INTO reservation


2 (res_date, member_id, title_id)
3 VALUES (sysdate, 101, 98);
1 row created.

SQL> INSERT INTO reservation


2 (res_date, member_id, title_id)
2 VALUES (sysdate, 104, 97);
1 row created.

SQL> COMMIT;
Commit complete.

" Verify additions.

SQL> SELECT *
2 FROM reservation;

RES_DATE MEMBER_ID TITLE_ID


--------- ---------- ----------
10-FEB-96 101 98
10-FEB-96 104 97

Practice Solutions AĆ143


Practice 17 Solutions continued

6.—continued
c. Customer Carmen Velasquez rents the movie “Interstellar Wars”, copy 1.
Remove her reservation for the movie. Record the information about the
rental. Allow the default value for the expected return date to be used. Verify
the rental was recorded by using the view you created.
" Add the rental information.

SQL> INSERT INTO rental (title_id, copy_id,


2 member_id)
3 VALUES (98, 1, 101);
1 row created.

" Update the title copy information to show that the film is rented.

SQL> UPDATE title_copy


2 SET status = ’RENTED’
3 WHERE title_id = 98
4 AND copy_id = 1;
1 row updated.

" Remove the reservation.

SQL> DELETE FROM reservation


2 WHERE member_id = 101;
1 row deleted.

AĆ144 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 17 Solutions continued

6c.—continued
" Confirm the rental information from the TITLE_AVAIL view.

SQL> SELECT *
2 FROM title_avail;

TITLE COPY_ID STATUS EXP_RET_D


--------------- -------- ---------- ---------
Willie and 1 AVAILABLE 09-FEB-96
Christmas Too

Alien Again 1 AVAILABLE


The Glob 1 AVAILABLE
My Day Off 1 AVAILABLE
Miracles on Ice 1 AVAILABLE
Soda Gang 1 AVAILABLE 08-FEB-96
Interstellar 1 RENTED 12-FEB-96
Wars

Alien Again 2 RENTED 11-FEB-96


My Day Off 2 AVAILABLE
Interstellar 2 AVAILABLE
Wars

My Day Off 3 RENTED 10-FEB-96

11 rows selected.

Practice Solutions AĆ145


Practice 17 Solutions continued

7. Make a modification to one of the tables.


a. Add a PRICE column to the TITLE table to record the purchase price of the
video. The column should have a total length of eight digits and two decimal
places. Verify your modification.

SQL> ALTER TABLE title


2 ADD (price NUMBER(8,2));
Table altered.

SQL> DESCRIBE title


Name Null? Type
-------------------------- -------- ----
TITLE_ID NOT NULL NUMBER(10)
TITLE NOT NULL VARCHAR2(60)
DESCRIPTION NOT NULL VARCHAR2(400)
RATING VARCHAR2(4)
CATEGORY VARCHAR2(20)
RELEASE_DATE DATE
PRICE NUMBER(8,2)

AĆ146 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 17 Solutions continued

7.—continued
b. Create a script named p17q7b.sql to update each video with a price according
to the following list:

Title Price
Willie and Christmas Too 25
Alien Again 35
The Glob 35
My Day Off 35
Miracle on Ice 98
Soda Gang 35
Interstellar Wars 29

" Script p17q7b.sql contents.

SET ECHO OFF


UPDATE title
SET price = &price
WHERE title_id = &title_id
/
SET ECHO ON

SQL> START p17q7b


SET ECHO OFF
Enter value for price: 25
Enter value for title_id: 92

1 row updated.

Practice Solutions AĆ147


Practice 17 Solutions continued

7b.—continued

SQL> START p17q7b


SET ECHO OFF
Enter value for price: 35
Enter value for title_id: 93

1 row updated.

SQL> START p17q7b


SET ECHO OFF
Enter value for price: 35
Enter value for title_id: 94

1 row updated.

SQL> START p17q7b


SET ECHO OFF
Enter value for price: 35
Enter value for title_id: 95

1 row updated.

SQL> START p17q7b


SET ECHO OFF
Enter value for price: 98
Enter value for title_id: 96

1 row updated.

AĆ148 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 17 Solutions continued

7b.—continued

SQL> START p17q7b


SET ECHO OFF
Enter value for price: 35
Enter value for title_id: 97

1 row updated.

SQL> START p17q7b


SET ECHO OFF
Enter value for price: 29
Enter value for title_id: 98

1 row updated.

SQL> COMMIT;
Commit complete.

" Verify the changes.

SQL> SELECT title_id, title, price


2 FROM title
3 ORDER BY title_id;

Practice Solutions AĆ149


Practice 17 Solutions continued

7b.—continued

TITLE_ID TITLE PRICE


---------- --------------- ----------
92 Willie and 25
Christmas Too

93 Alien Again 35
94 The Glob 35
95 My Day Off 35
96 Miracles on Ice 98
97 Soda Gang 35
98 Interstellar 29
Wars

7 rows selected.

c. Ensure that in the future all titles will contain a price value. Verify the
constraint.

SQL> ALTER TABLE title


2 MODIFY (price CONSTRAINT
3 member_price_nn NOT NULL);
Table altered.

SQL> SELECT constraint_name, constraint_type,


2 search_condition, r_constraint_name
3 FROM user_constraints
4 WHERE table_name = ’TITLE’;

AĆ150 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 17 Solutions continued

7c.—continued

CONSTRAINT_NAME C SEARCH_CONDITION
--------------- - --------------------
R_CONSTRAINT_NA
---------------
TITLE_NN C TITLE IS NOT NULL

TITLE_DESC_NN C DESCRIPTION IS NOT


NULL

TITLE_ID_PK P

TITLE_RATING_CK C rating IN (’G’,’PG’,


’R’,’NC17’,’NR’)

TITLE_CATEG_CK C category IN (’DRAMA’


,’COMEDY’,’ACTION’,
’CHILD’,’SCIFI’,
’DOCUMENTARY’)

MEMBER_PRICE_NN C PRICE IS NOT NULL

6 rows selected.

Practice Solutions AĆ151


Practice 17 Solutions continued

8. Create a report titled Customer History Report. This report will contain each
customer’s history of renting videos. Be sure to include the customer name,
movie rented, dates of the rentals, and duration of rentals. Count up the total
number of rentals for all customers for the reporting period. Save the script in a
file named p17q8.sql.

SET ECHO OFF


SET PAGESIZE 30
SET LINESIZE 52
TTITLE ’Customer History Report’
COLUMN member FORMAT A17
COLUMN title FORMAT A15 WORD_WRAPPED
COLUMN book_date FORMAT A9
COLUMN duration FORMAT 9999999
BREAK ON member skip 1 ON REPORT
COMPUTE COUNT LABEL ’Total Rentals’ OF -
title ON REPORT
SELECT m.first_name||’ ’||m.last_name MEMBER,
t.title, r.book_date,
r.act_ret_date - book_date DURATION
FROM member m, title t, rental r
WHERE r.member_id = m.member_id
AND r.title_id = t.title_id
ORDER BY m.last_name
/
CLEAR COMPUTE
CLEAR BREAK
COLUMN duration CLEAR
COLUMN book_date CLEAR
COLUMN title CLEAR
COLUMN member CLEAR
SET PAGESIZE 25
SET LINESIZE 80
SET ECHO ON

AĆ152 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 17 Solutions continued

8.—continued

Sat Feb 10 page 1


Customer History Report

MEMBER TITLE BOOK_DATE DURATION


----------------- --------------- --------- --------
LaDoris Ngao My Day Off 08-FEB-96

Molly Urguhart Soda Gang 06-FEB-96 2

Carmen Velasquez Willie and 07-FEB-96 1


Christmas Too

Interstellar 10-FEB-96
Wars

Alien Again 09-FEB-96

***************** ---------------
Total Rentals 5

Practice Solutions AĆ153


Practice 19 Solutions

1. Load and execute a loop counter.


a. Launch Procedure Builder. Your instructor will give you the login
information.
b. From the menu, load the LABS\p19loop.pls file.
c. Execute the procedure from the Interpreter pane. Pass a numeric value into the
procedure as demonstrated below.

Reminder: The Cue Cards can help you get started.

PL/SQL> count_loops(4);

" Solution file: SOLN\ p19q1.pls

PROCEDURE count_loops
(v_count IN NUMBER)
IS
BEGIN
FOR i in 1..v_count LOOP
TEXT_IO.PUT_LINE (’Times through loop:
’||TO_CHAR(i));
END LOOP;
END;

2. Create, compile, and execute a procedure.


a. Create a procedure named MY_MESSAGE as demonstrated below.

" Solution file: SOLN\ p19q2.pls

PROCEDURE my_message IS
BEGIN
TEXT_IO.PUT_LINE (’Hello World’);
END;

b. Compile the procedure using the Program Unit Editor.


c. Execute the procedure from the Interpreter pane.

PL/SQL> my_message;

AĆ154 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 20 Solutions
1. A procedure can act as a function.
True / False
" True
2. A procedure can be used in a SQL statement.
True / False
" False
3. The IN OUT argument mode is the default mode.
True / False
" False
4. Functions are executed as part of an expression.
True / False
True
"

5. Name the four parts of the subprogram syntax.

a. Header

b. Declarative

c. Executable

d. Exception handling

Practice Solutions AĆ155


Practice 20 Solutions continued

6. Create a procedure called MY_PROCEDURE to output the phrase “My


Procedure Works” at the Interpreter prompt.
" Solution file: SOLN\ p20q6.pls
a. Replace the skeleton text with text from LABS\p20proc.pls.
" Click the Subprograms node in the Navigator. Click the Create button.
In the dialog box, enter the name my_procedure. Click the
Procedure radio button. Click OK.

" In the Program Unit Editor window, select all the skeleton text. From
the menu, select Edit/Import. Choose the LABS\p20proc.pls file. Click
OK.

PROCEDURE my_procedure IS
TEXT_IO.PUTLINE (My Procedure Works)
END;

AĆ156 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 20 Solutions continued

6.—continued
b. Compile the code. Make appropriate corrections so code successfully
compiles.
" Corrections:
" Correct function name: TEXT_IO.PUT_LINE
" Add BEGIN after IS.
" Add quotation marks around text string: ’My Procedure Works’
" Add a semicolon after the output statement.
c. Execute the procedure at the Interpreter prompt.

PL/SQL> my_procedure;
My Procedure Works

Practice Solutions AĆ157


Practice 21 Solutions
1. Evaluate each of the following declarations. Determine which of them are not
legal and explain why.

DECLARE
v_id NUMBER (4);

a. Legal

DECLARE
v_x, v_y, v_z VARCHAR2(10);

b. Illegal because only one identifier per declaration is allowed.

DECLARE
v_birthdate DATE NOT NULL;

c. Illegal because the NOT NULL variable must be initialized.

DECLARE
v_in_stock BOOLEAN := 1;

d. Illegal because 1 is not a ‘Boolean expression.

DECLARE
emp_record emp_record_type;

e. Illegal because EMP_RECORD_TYPE must be declared.

DECLARE
TYPE name_table_type IS TABLE OF VARCHAR2(20)
INDEX BY BINARY_INTEGER;
dept_name_table name_table_type;

f. Legal

AĆ158 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 21 Solutions continued

2. Suppose you embed a sub-block within a block, as depicted below. You declare
two variables, V_CUSTOMER and V_CREDIT_RATING, within the main block.
You also declare two variables,V_CUSTOMER and V_NAME in the sub-block.
Determine the values for each variable in each case listed below.
a. The value of V_CUSTOMER in the sub-block is
" “201” and the datatype is NUMBER.
b. The value of V_NAME in the sub-block is
" “Unisports”.
c. The value of V_CREDIT_RATING in the sub-block is
" “EXCELLENT”.
d. The value of V_CUSTOMER in the main block is
" “Womansport” and the datatype is VARCHAR2.
e. The value of V_NAME in the main block is
" V_NAME is not visible in the main block and you would see an error.
f. The value of V_CREDIT_RATING within the main block is
" “EXCELLENT”.

Scope Example
DECLARE
v_customer VARCHAR2(50) := ’Womansport’;
v_credit_rating VARCHAR2(10) := ’EXCELLENT’;
BEGIN
SUB-BLOCK
DECLARE
v_customer NUMBER (7) := 201;
v_name VARCHAR2(25):= ’Unisports’;

BEGIN
v_customer v_name v_credit_rating

END;

v_customer v_name v_credit_rating

END;

Practice Solutions AĆ159


Practice 21 Solutions continued

3. Create and execute a procedure named MULTIPLIER that accepts two numbers
through variables. The first number should be divided by the second number and
have the second number added to the result. The result should be written to a
PL/SQL variable and printed to the screen.
" Solution file: SOLN\p21q3.pls

PROCEDURE multiplier
(v_num1 IN NUMBER,
v_num2 IN NUMBER)
IS
v_result NUMBER(9,2);
BEGIN
v_result := (v_num1/v_num2) + v_num2;
TEXT_IO.PUT_LINE(TO_CHAR(v_result));
END multiplier;

" Test the procedure.

PL/SQL> multiplier(2,4);
4.5

AĆ160 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 21 Solutions continued

4. Build a function named ANN_COMP that computes the total compensation for
one year. The annual salary and the annual bonus percentage will be passed to the
function, and the bonus will need to be converted from a whole number to a
decimal (for example, 15 to .15). If the salary is null, set it to zero before
computing the total compensation. Likewise, if the bonus is null, set it to zero
before computing the total compensation. Execute the function. Reminder: Use
the NVL function to handle null values.
" Solution file: SOLN\p21q4.pls

FUNCTION ann_comp
(v_salary IN NUMBER,
v_bonus IN NUMBER)
RETURN NUMBER
IS
v_total NUMBER(9,2);
BEGIN
v_total := NVL(v_salary, 0) *
(1 + NVL(v_bonus, 0) / 100);
RETURN (v_total);
END ann_comp;

" Create a variable to hold the result. Execute the function. Print the output
variable value.

PL/SQL> .CREATE NUMBER g_comp PRECISION 10 SCALE 2


PL/SQL> :g_comp := ann_comp (50000,10);
PL/SQL> TEXT_IO.PUT_LINE (TO_CHAR(:g_comp));
55000

Practice Solutions AĆ161


Practice 21 Solutions continued

5. Rewrite the MULTIPLIER procedure in Exercise 3 as a function named MULTI.


Execute the function.
" Solution file: SOLN\p21q5.pls

FUNCTION multi
(v_num1 IN NUMBER,
v_num2 IN NUMBER)
RETURN NUMBER
IS
v_result NUMBER(9,2);
BEGIN
v_result := (v_num1/v_num2) + v_num2;
RETURN (v_result);
END multi;

" Create a variable to hold the result. Execute the function. Print the output
variable value.

PL/SQL> .CREATE NUMBER g_multi PRECISION 9 SCALE 2


PL/SQL> :g_multi := multi(2,4);
PL/SQL> TEXT_IO.PUT_LINE (TO_CHAR(:g_multi));
4.5

AĆ162 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 22 Solutions
If you are not already connected to the database, be sure to do so now.
1. Create a procedure to insert a new department into the S_DEPT table.
a. Use the S_DEPT_ID sequence generator for the department number.
b. Create a parameter for the department name.
c. Leave the region number null for now.
" Solution file: SOLN\p22q1.pls

PROCEDURE new_dept
(v_dept_name IN VARCHAR2)
IS
BEGIN
INSERT INTO s_dept(id, name, region_id)
VALUES (s_dept_id.NEXTVAL, v_dept_name, NULL);
COMMIT;
END new_dept;

d. Execute the procedure.

PL/SQL> new_dept (’Health’);

e. Display the new department that you created.

PL/SQL> SELECT *
+> FROM s_dept
+> WHERE name = ’Health’;
ID NAME REGION_ID
-------- ------------------------- ---------
51 Health

1 row selected.

Practice Solutions AĆ163


Practice 22 Solutions continued

2. Create a procedure to update the region number for an existing department.


a. Create a parameter for the department number.
b. Create a parameter for the region name.
c. Set the region number to the value that corresponds to the specified region
name.
" Solution file: SOLN\p22q2.pls

PROCEDURE update_dept
(v_dept_id NUMBER,
v_region_name VARCHAR2)
IS
v_region_id s_region.id%TYPE;
BEGIN
SELECT id
INTO v_region_id
FROM s_region
WHERE UPPER(name) = UPPER(v_region_name);
UPDATE s_dept
SET region_id = v_region_id
WHERE id = v_dept_id;
COMMIT;
END update_dept;

d. Test the procedure. What happens if you enter a region name that does not
exist?

PL/SQL> update_dept (51, ’Europe’);

" If the operator enters an invalid region name, the NO_DATA_FOUND


exception is raised.

AĆ164 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 22 Solutions continued

2.—continued
e. Display the department number, region number, and region name for the
updated department.

PL/SQL> SELECT d.id, d.region_id, r.name


+> FROM s_dept d, s_region r
+> WHERE d.region_id = r.id
+> AND d.id = 51;
ID REGION_ID NAME
-------- --------- -------------------------
51 5 Europe

1 row selected.

3. Create a procedure to delete the department created in Exercise 1.


a. Create a parameter for the department number.
b. Print to the screen the number of rows affected.
" Solution file: SOLN\p22q3.pls

PROCEDURE delete_dept
(v_dept_id IN NUMBER)
IS
v_result NUMBER(2);
BEGIN
DELETE FROM s_dept
WHERE id = v_dept_id;
v_result := SQL%ROWCOUNT;
TEXT_IO.PUT_LINE (TO_CHAR(v_result)||
’ row(s) deleted.’);
COMMIT;
END delete_dept;

Practice Solutions AĆ165


Practice 22 Solutions continued

3.—continued
c. Test the procedure. What happens if you enter a department number that does
not exist?

PL/SQL> delete_dept (51);

" If the operator enters a department number that does not exist, the
procedure completes successfully because this does not constitute an
exception.
What happens if you enter a department that has employees?
" The Oracle7 Server sends an error message that an integrity constraint
has been violated.
d. Confirm that the department has been deleted.

PL/SQL> SELECT *
+> FROM s_dept
+> WHERE id = 51;
No rows selected.

e. Test the procedure.

PL/SQL> delete_dept (51);

AĆ166 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 22 Solutions continued

4. Create a procedure named NEW_EMP to insert a new employee into the S_EMP
table.
a. Create parameters for first name, last name, and job title.
b. Use the S_EMP_ID sequence generator for the employee number.
c. Compute the user ID by concatenating the first letter of the first name with the
first seven letters of the last name, and converting all letters to lowercase.
d. Set the start date to the current date.
e. To determine the manager number, the department number, and the salary,
first find the lowest-paid existing employee having the specified job title.
Then, set these three values according to that existing employee. (If several
people are tied for lowest-paid, choose any one of them.)
f. Leave the comments and the commission percent empty.
" Solution file: SOLN\p22q4.pls
Code has been formatted to fit page.

Practice Solutions AĆ167


Practice 22 Solutions continued

4.—continued

PROCEDURE NEW_EMP
(v_first_name IN s_emp.first_name%TYPE,
v_last_name IN s_emp.last_name%TYPE,
v_title IN s_emp.title%TYPE)
IS
v_userid s_emp.userid%TYPE;
v_start_date s_emp.start_date%TYPE := SYSDATE;
v_manager_id s_emp.manager_id%TYPE;
v_dept_id s_emp.dept_id%TYPE;
v_salary s_emp.salary%TYPE;
v_existing_id s_emp.id%TYPE;
BEGIN
v_userid := LOWER (SUBSTR (v_first_name,1,1)||
SUBSTR (v_last_name,1,7));
SELECT MIN(id)
INTO v_existing_id
FROM s_emp
WHERE title = v_title
AND salary =
(SELECT MIN(salary)
FROM s_emp
WHERE title = v_title);
SELECT manager_id, dept_id, salary
INTO v_manager_id, v_dept_id, v_salary
FROM s_emp
WHERE id = v_existing_id;
INSERT INTO s_emp (id, last_name,
first_name, userid, start_date, comments,
manager_id, title, dept_id,
salary, commission_pct)
VALUES (s_emp_id.NEXTVAL, v_last_name,
v_first_name, v_userid, v_start_date, NULL,
v_manager_id, v_title, v_dept_id,
v_salary, NULL);
COMMIT;
END new_emp;

AĆ168 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 22 Solutions continued

4.—continued
" Execute the procedure.

PL/SQL> new_emp (’Jayne’,’Bowman’,


2> ’Sales Representative’);

g. Verify the record has been added by viewing the employee’s number, userid,
and salary.

PL/SQL> SELECT id, userid, salary


2> FROM s_emp
3> WHERE last_name = ’Bowman’;
ID USERID SALARY
------ -------- ------------
26 jbowman 1400.00

Practice Solutions AĆ169


Practice 23 Solutions
If you are not already connected to the database, be sure to do so now.
1. Create a procedure named SET_COMM to conditionally set the commission
percentage for a given employee based upon total sales.
a. Prepare this exercise by disabling the constraint on the COMMISSION_PCT
column in the S_EMP table. You modify the commission percentage to values
that are not in the constraint.

PL/SQL> ALTER TABLE s_emp


+> DROP CONSTRAINT s_emp_commission_pct_ck;

b. Create a parameter to accept the employee number from the user.


c. Find the sum of the totals for all orders placed by that employee.
d. If the sum is less than 100,000, set the commission percentage for the
employee to 10.
e. If the sum is between 100,000 and 1,000,000 inclusive, set the commission
percentage for the employee to 15.
f. If the sum exceeds 1,000,000, set the commission percentage for the
employee to 20.
g. If no orders appear in the S_ORD table for the given employee, set the
commission percentage to 0.
h. Commit the change.
i. Test the block and view the changes. Results should appear for some example
employees as follows.

Employee Number Total Sales Resulting Commission


1 0 0
11 1,629,066.37 20
12 100,184.00 15
14 16,358.00 10

AĆ170 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 23 Solutions continued

1.—continued
" Solution file: SOLN\p23q1.pls
" In the Navigator, create a new procedure. Name it SET_COMM.

PROCEDURE set_comm
(v_id IN NUMBER)
IS
v_sum_total NUMBER(11,2);
v_comm s_emp.commission_pct%TYPE;
BEGIN
SELECT SUM(total)
INTO v_sum_total
FROM s_ord
WHERE sales_rep_id = v_id;
IF v_sum_total < 100000 THEN
v_comm := 10;
ELSIF v_sum_total <= 1000000 THEN
v_comm := 15;
ELSIF v_sum_total > 1000000 THEN
v_comm := 20;
ELSE
v_comm := 0;
END IF;
UPDATE s_emp
SET commission_pct = v_comm
WHERE id = v_id;
COMMIT;
END set_comm;

Practice Solutions AĆ171


Practice 23 Solutions continued

1.—continued
Test the procedure.

PL/SQL> set_comm (1);


PL/SQL> set_comm (11);
PL/SQL> set_comm (12);
PL/SQL> set_comm (14);
PL/SQL> SELECT id, commission_pct
+> FROM s_emp
+> WHERE id IN (1, 11, 12, 14);
ID COMMISSION_PCT
-------- -------------
1 0.00
11 20.00
12 15.00
14 10.00

4 row selected.

2. Write a procedure named CUST_UPDATE that loops through the region numbers
(1 through 5) to update the credit rating of all customers. Do not issue a commit.
a. If the region number is even, then set the credit rating to Excellent (even if the
customer’s credit rating is already Excellent), otherwise set the credit rating to
Good.
b. Once the rows are updated, find out how many rows were updated. Print the
following statements to the screen based on the number of rows updated.
i. If less than three rows updated, statement should read “Fewer than 3
customer records updated for region number X”, where X represents the
region number.
ii. Otherwise, it should read “Y rows updated for region number X”, where Y
is the number of rows updated, and X is the region number.

AĆ172 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 23 Solutions continued

2.—continued
" Solution: SOLN\p23q2.pls
" In the Navigator, create a new procedure. Name it CUST_UPDATE.

PROCEDURE cust_update IS
v_output VARCHAR2(100);
v_updated NUMBER(2);
v_rating VARCHAR2(25);
c_few CONSTANT VARCHAR2(100)
:= ’Fewer than 3 customer records updated for
region number ’;
BEGIN
FOR i IN 1..5 LOOP
IF MOD(i,2) = 0 THEN
v_rating := ’EXCELLENT’;
ELSE
v_rating := ’GOOD’;
END IF;
UPDATE s_customer
SET credit_rating = v_rating
WHERE region_id = i;
v_updated := SQL%ROWCOUNT;
IF v_updated < 3 THEN
v_output := c_few || TO_CHAR(i);
ELSE
v_output := TO_CHAR (v_updated) ||
’ rows updated for region number
’||TO_CHAR(i);
END IF;
TEXT_IO.PUT_LINE (v_output);
END LOOP;
END cust_update;

" Execute the procedure by entering cust_update; at the Interpreter


prompt. Observe the resulting statements.

Practice Solutions AĆ173


Practice 23 Solutions continued

2.—continued
c. Rollback the changes. Set a breakpoint on the conditional test for the number
of rows updated. Execute the procedure. Check the Stack node to verify the
values of the variables as you Step Into the statements in the loop.
Reminder: You can use the Quick Tour, “Debugging a Program Unit” section
for assistance.
" Issue a ROLLBACK statement to undo changes. In the Navigator, click
the CUST_UPDATE program unit. In the Interpreter source pane,
double-click the line with the statement IF v_updated < 3 THEN
to set the breakpoint.
" Execute the procedure again. When the breakpoint is reached,
investigate the values in the Stack node of the Navigator as you step
into the code.
3. Create a procedure named EMP_MESSAGE that selects the employee last name,
start date, and salary based on an employee number provided at execution. Print a
message to the screen based on any combination of one of the following criteria.
Test employee numbers 2, 5, 16, 17, and 18. Hint: A nested IF is required.

Criteria Message
Salary greater than 1200 Salary more than 1200
Last name contains “r” Name contains “R”
Start date is in March March start date
None of the above **None**

" Solution file: SOLN\p23q3.pls


" In the Navigator, create a new procedure. Name it EMP_MESSAGE.

AĆ174 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 23 Solutions continued

3.—continued

PROCEDURE emp_message
(v_emp_id IN NUMBER) IS
v_last_name s_emp.last_name%TYPE;
v_start_date s_emp.start_date%TYPE;
v_salary s_emp.salary%TYPE;
v_output VARCHAR2(100);
c_name CONSTANT VARCHAR2(30) := ’Name contains ”R”’;
c_date CONSTANT VARCHAR2(30) := ’March start date’;
c_sal CONSTANT VARCHAR2(30) := ’Salary more than 1200’;
BEGIN
SELECT last_name, start_date, salary
INTO v_last_name, v_start_date, v_salary
FROM s_emp
WHERE id = v_emp_id;
IF v_salary > 1200 THEN
v_output := c_sal;
IF LOWER(v_last_name) LIKE ’%r%’ THEN
v_output := v_output || ’ - ’ || c_name;
IF TO_CHAR(v_start_date, ’MON’) LIKE ’MAR’ THEN
IF v_output IS NULL THEN
v_output := c_date;
ELSE
v_output := v_output || ’ - ’ || c_date;
END IF;
END IF;
ELSIF TO_CHAR(v_start_date, ’MON’) LIKE ’MAR’ THEN
v_output := v_output || ’ - ’ || c_date;
END IF;
ELSIF LOWER(v_last_name) LIKE ’%r%’ THEN
v_output := c_name;
IF TO_CHAR(v_start_date, ’MON’) LIKE ’MAR’ THEN
v_output := v_output || ’ - ’ || c_date;
END IF;
ELSIF TO_CHAR(v_start_date, ’MON’) LIKE ’MAR’ THEN
v_output := c_date;
ELSE
v_output := ’**None**’;
END IF;
TEXT_IO.PUT_LINE (v_output);
END emp_message;

Practice Solutions AĆ175


Practice 23 Solutions continued

3.—continued
" Test the procedure.

PL/SQL> emp_message (2);


Salary more than 1200 - March start date

PL/SQL> emp_message (5);


Salary more than 1200 - Name contains ”R” - March
start date

PL/SQL> emp_message (16);


Salary more than 1200 - Name contains ”R”

PL/SQL> emp_message (17);


March start date

PL/SQL> emp_message (18);


**None**

AĆ176 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 24 Solutions
1. Create a procedure named TOP_DOGS1 that determines the top employees with
respect to salaries.
a. Prepare for this exercise by creating a new table for storing employees and
their salaries.

PL/SQL> CREATE TABLE top_dogs


+> (name VARCHAR2(25),
+> salary NUMBER(11,2));

b. Add a parameter to accept the user input n for the top number of employees.
c. Write a cursor FOR loop to get the last names and salaries of the top n people,
with respect to salary, from the S_EMP table.
d. Store the names and salaries in the TOP_DOGS table.
e. Assume for the moment that no two employees have the same salary.
f. Test the exercise under a variety of special cases, such as n = 0, n is greater
than the number of employees in the S_EMP table.
g. Empty the TOP_DOGS table after each test.

Practice Solutions AĆ177


Practice 24 Solutions continued

1.—continued
" Solution file: SOLN\p24q1.pls
" From the Tools menu, select Stored Program Unit Editor... Set the Owner to
your username, and click the New button. Create a new procedure. Name it
TOP_DOGS1.

PROCEDURE top_dogs1
(v_n IN NUMBER)
IS
CURSOR emp_cursor IS
SELECT last_name, salary
FROM s_emp
WHERE salary IS NOT NULL
ORDER BY salary DESC;
BEGIN
DELETE FROM top_dogs;
FOR emp_record IN emp_cursor LOOP
EXIT WHEN emp_cursor%ROWCOUNT > v_n;
INSERT INTO top_dogs (name, salary)
VALUES (emp_record.last_name,
emp_record.salary);
END LOOP;
COMMIT;
END;

" Execute the procedure, and confirm the selection.

PL/SQL> top_dogs1(4);
PL/SQL> SELECT * FROM top_dogs;
NAME SALARY
------------------------- ----------
Velasquez 2500.00
Ropeburn 1550.00
Nguyen 1525.00
Sedeghi 1515.00

4 rows selected.

AĆ178 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 24 Solutions continued

1.—continued
" Execute the procedure with 0 as the parameter, and confirm the selection.

PL/SQL> top_dogs1(0);
PL/SQL> SELECT * FROM top_dogs;
NAME SALARY
------------------------- ----------

No rows selected.

Practice Solutions AĆ179


Practice 24 Solutions continued

1.—continued
" Execute the procedure with 30 as the parameter, and confirm the selection.

PL/SQL> top_dogs1(30);
PL/SQL> SELECT * FROM top_dogs;
NAME SALARY
------------------------- ----------
Velasquez 2500.00
Ropeburn 1550.00
Nguyen 1525.00
Sedeghi 1515.00
Giljum 1490.00
Ngao 1450.00
Dumas 1450.00
Quick-To-See 1450.00
Nagayama 1400.00
Bowman 1400.00
Magee 1400.00
Maduro 1400.00
Havel 1307.00
Catchpole 1300.00
Menchu 1250.00
Urguhart 1200.00
Nozaki 1200.00
Biri 1100.00
Schwartz 1100.00
Smith 940.00
Dancs 860.00
Markarian 850.00
Chang 800.00
Patel 795.00
Patel 795.00
Newman 750.00

26 rows selected.

AĆ180 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 24 Solutions continued

2. Create a stored procedure named ADD_STARS to reward all employees by


appending an asterisk in the STARS column for every commission point.
a. Prepare for this exercise by creating a new column in the S_EMP table for
storing asterisks (*).

PL/SQL> ALTER TABLE s_emp


+> ADD stars VARCHAR2(100);

b. Determine the commission percentage for the employee, rounded to the


nearest whole number. Also, consider the case where the employee has no
commission percent.
c. Add an asterisk to a string of asterisks for every commission point. For
example, if the employee has a commission percentage of 10, then the STARS
column will contain ten asterisks.
d. Update the STARS column for each employee with the string of asterisks.

Practice Solutions AĆ181


Practice 24 Solutions continued

2.—continued
" Solution file: SOLN\p24q2.pls
" From the Tools menu, select Stored Program Unit Editor... Set the Owner to
your username, and click the New button. Create a new procedure. Name it
ADD_STARS.

PROCEDURE add_stars
IS
v_stars s_emp.stars%TYPE := NULL;
CURSOR emp_cursor IS
SELECT id, NVL(ROUND(commission_pct),0) comm
FROM s_emp
FOR UPDATE;
BEGIN
FOR emp_record IN emp_cursor LOOP
BEGIN
FOR i IN 1..emp_record.comm LOOP
v_stars := v_stars || ’*’;
END LOOP;
UPDATE s_emp
SET stars = v_stars
WHERE CURRENT OF emp_cursor;
v_stars := NULL;
END;
END LOOP;
COMMIT;
END;

AĆ182 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 24 Solutions continued

2.—continued
" Execute the procedure to put in the stars, and confirm the changes to the
table.

PL/SQL> add_stars;
PL/SQL> SELECT id, commission_pct, stars
+> FROM s_emp
+> WHERE commission_pct IS NOT NULL;
ID COMMISSION_PCT STARS
-------- -------------- ----------------------------
1 0.00
11 20.00 ********************
12 15.00 ***************
13 10.00 **********
14 10.00 **********
15 17.50 ******************

6 rows selected.

3. Copy the TOP_DOGS1 procedure from exercise 1, and name it TOP_DOGS2.


Modify the TOP_DOGS2 procedure to consider the case where several
employees in the exercise 1 have the same salary. For each name listed, all names
having the same salary should also be listed.
Execute the TOP_DOGS2 procedure. Enter 6, 7, or 8 for n, then Ngao, Dumas,
and Quick-To-See should all display. If you enter 9, 10, or 11 for n, then
Nagayama, Magee, and Maduro should all display.
Remember to empty the TOP_DOGS table after each test.

Practice Solutions AĆ183


Practice 24 Solutions continued

3.—continued
" Solution file: SOLN\p24q3.pls
" In the Navigator, select the TOP_DOGS1 procedure. From the menu, choose
Edit—>Duplicate. Open the copy of TOP_DOGS1_XXX, where XXX
represents an internal number created by Procedure Builder.

PROCEDURE top_dogs2
(v_n IN NUMBER)
IS
v_last_salary s_emp.salary%TYPE := -1;
-- salary never negative
CURSOR emp_cursor IS
SELECT last_name, salary
FROM s_emp
WHERE salary IS NOT NULL
ORDER BY salary DESC;
emp_record emp_cursor%ROWTYPE;
BEGIN
DELETE FROM top_dogs;
OPEN emp_cursor;
FETCH emp_cursor INTO emp_record;
WHILE (emp_cursor%ROWCOUNT <= v_n OR
emp_record.salary = v_last_salary)
AND emp_cursor%FOUND LOOP
INSERT INTO top_dogs (name, salary)
VALUES (emp_record.last_name,
emp_record.salary);
v_last_salary := emp_record.salary;
FETCH emp_cursor INTO emp_record;
END LOOP;
CLOSE emp_cursor;
COMMIT;
END;

AĆ184 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 24 Solutions continued

3.—continued
" Execute the procedure.

PL/SQL> top_dogs2(7);
PL/SQL> SELECT * FROM top_dogs;
NAME SALARY
-------------------- -------------
Velasquez 2500.00
Ropeburn 1550.00
Nguyen 1525.00
Sedeghi 1515.00
Giljum 1490.00
Ngao 1450.00
Dumas 1450.00
Quick-To-See 1450.00

8 rows selected.

PL/SQL> top_dogs2(10);
PL/SQL> SELECT * FROM top_dogs;
NAME SALARY
-------------------- -------------
Velasquez 2500.00
Ropeburn 1550.00
Nguyen 1525.00
Sedeghi 1515.00
Giljum 1490.00
Ngao 1450.00
Dumas 1450.00
Quick-To-See 1450.00
Nagayama 1400.00
Bowman 1400.00
Magee 1400.00
Maduro 1400.00

12 rows selected.

Practice Solutions AĆ185


Practice 25 Solutions
1. Modify the procedure to handle exceptions. The procedure tries to update region
numbers for existing departments.
a. Load the LABS\p25q1a.pls script file. Note: The procedure UPDATE_DEPT2
is loaded and compiled.
" From the menu, select File/Load. Select the file LABS\p25q1a.pls.
b. Execute the procedure by entering the following text.

PL/SQL> update_dept2 (50,’US’);

PL/SQL> update_dept2 (50,’US’);


ERROR 0 at line 6, column 0
Unhandled exception ORA-01401: no data found
which was raised in a statement starting at
line 6 of UPDATE_DEPT2

c. Write an exception handler for the error to pass a message to the user that the
specified region does not exist.
d. Execute the procedure by entering the following text.

PL/SQL> update_dept2 (31,’Asia’);

e. Write an exception handler for the error to pass a message to the user that the
specified region already has a department of that name.
f. Execute the procedure by entering the following text.

PL/SQL> update_dept2 (99,’Europe’);

g. Write an exception handler for the error to pass a message to the user that the
specified department number does not exist.

Reminder: The SQL attribute %NOTFOUND and raise an exception


manually.

AĆ186 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 25 Solutions continued

1.—continued

" Solution file: SOLN\p25q1.pls


" In the Program Unit editor, modify the procedure named UPDATE_DEPT2.
Add the text you see in bold.

PROCEDURE update_dept2
(v_dept_id IN NUMBER,
v_region_name IN VARCHAR2)
IS
v_region_id s_region.id%TYPE;
dept_record s_dept%ROWTYPE;
e_count EXCEPTION;
BEGIN
SELECT id
INTO v_region_id
FROM s_region
WHERE UPPER(name) = UPPER(v_region_name);
UPDATE s_dept
SET region_id = v_region_id
WHERE id = v_dept_id;
IF SQL%NOTFOUND THEN
RAISE e_count;
END IF;
COMMIT;
EXCEPTION
WHEN NO_DATA_FOUND THEN
ROLLBACK;
TEXT_IO.PUT_LINE (v_region_name||
’ region does not exist.’);
WHEN DUP_VAL_ON_INDEX THEN
ROLLBACK;
TEXT_IO.PUT_LINE (v_region_name||
’ already has a department of that name.’);
WHEN e_count THEN
ROLLBACK;
TEXT_IO.PUT_LINE (’Department number ’||
TO_CHAR(v_dept_id)||’ does not exist.’);
END update_dept2;

Practice Solutions AĆ187


Practice 25 Solutions continued

1.—continued
" Execute the subprogram.

PL/SQL> update_dept (50,’US’);


US region does not exist.
PL/SQL> update_dept (31,’Asia’);
Asia already has a department of that name.
PL/SQL> update_dept (99,’Europe’);
Department number 99 does not exist.

AĆ188 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 25 Solutions continued

2. Write a procedure named SALARY_RANGE that prints the names of the


employees that make plus or minus 100 dollars of the salary value entered.
a. If there is no employee within that salary range, then print a message to the
user indicating that is the case. Use an exception for this case.
b. If there are more than 3 employees within that range, then the message should
indicate how many employees have that salary range.

Your results should look like the list below. Results have been formatted to fit
the page.

PL/SQL> SALARY_RANGE (1000);


Employees who make around $1000 are: Biri,
Schwartz, Smith
PL/SQL> SALARY_RANGE (900);
4 employoee salaries are within $100 of $900
PL/SQL> SALARY_RANGE (2000);
No records within the $2000 range.

" Solution file: SOLN\p25q2.pls


" In the Navigator, create a new procedure. Name it SALARY_RANGE.

Practice Solutions AĆ189


Practice 25 Solutions continued

2.—continued

PROCEDURE salary_range
(v_salary IN s_emp.salary%TYPE)
IS
v_count INTEGER := 0;
v_flag BOOLEAN := FALSE;
v_name VARCHAR2(255);
v_emp_name s_emp.last_name%TYPE;
v_emp_sal s_emp.salary%TYPE;
CURSOR emp_cursor IS
SELECT last_name, salary
FROM s_emp
WHERE salary BETWEEN (v_salary - 100)
AND (v_salary + 100)
ORDER BY last_name DESC;
e_no_emp exception;
v_code NUMBER(6);
v_msg VARCHAR2(255);
BEGIN
OPEN emp_cursor;
LOOP
FETCH emp_cursor INTO v_emp_name, v_emp_sal;
EXIT WHEN emp_cursor%NOTFOUND;
IF v_flag THEN
v_count := v_count + 1;
ELSE
IF v_name IS NULL THEN
v_name := v_emp_name;
ELSE
v_name := v_emp_name||’, ’||v_name;
END IF;
v_count := v_count + 1;
IF v_count > 3 THEN
v_flag := TRUE;
END IF;
END IF;
END LOOP;

" Code continues on next page.

AĆ190 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 25 Solutions continued

2.—continued

IF v_name IS NULL THEN


RAISE e_no_emp;
ELSIF v_flag THEN
TEXT_IO.PUT_LINE (TO_CHAR(v_count)
||’ employee salaries are within $100 of $’
||TO_CHAR(v_salary));
ELSE
TEXT_IO.PUT_LINE (’Employees who make around $’
||TO_CHAR(v_salary)||’ are: ’||v_name);
END IF;
EXCEPTION
WHEN e_no_emp THEN
TEXT_IO.PUT_LINE (’No records within the $’
||TO_CHAR(v_salary)||’ range.’);
WHEN OTHERS THEN
v_code := SQLCODE;
v_msg := SQLERRM;
TEXT_IO.PUT_LINE (TO_CHAR(v_code)||’: ’||v_msg);
END salary_range;

" Execute the procedure.


Output has been formatted to fit the page.

PL/SQL> SALARY_RANGE (1000);


Employees who make around $1000 are: Biri,
Schwartz, Smith
PL/SQL> SALARY_RANGE (900);
4 employoee salaries are within $100 of $900
PL/SQL> SALARY_RANGE (2000);
No records within the $2000 range.

Practice Solutions AĆ191


Practice 26 Solutions
1. Complete the database design by writing subprograms to perform the following
actions.
a. Create a function named NEW_MEMBER to return the membership number
for that new member. Be sure to use a sequence generator to create the unique
member numbers. Check the data dictionary for the sequence name.
" Solution file: SOLN\p26q1a.pls
Code has been formatted to fit page.

FUNCTION new_member
(v_first_name IN member.first_name%TYPE,
v_last_name IN member.last_name%TYPE,
v_address IN member.address%TYPE,
v_city IN member.city%TYPE,
v_phone IN member.phone%TYPE)
RETURN number IS
v_member_id member.member_id%TYPE;
BEGIN
INSERT INTO member(member_id, last_name,
first_name, address, city,
phone, join_date)
VALUES (member_id_seq.NEXTVAL, v_last_name,
v_first_name, v_address, v_city,
v_phone, SYSDATE);
COMMIT;
SELECT member_id_seq.CURRVAL
INTO v_member_id
FROM dual;
RETURN (v_member_id);
END;

AĆ192 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 26 Solutions continued

1.—continued
b. Create a function named NEW_RENTAL to record a new rental based on a
member’s last name. Return a message with the expected due date. If two or
more people have the same last name, store the first name, last name, phone,
and membership number for all matching last names in the RESULTS table.
" Solution file: SOLN\p26q1b.pls
Code has been formatted to fit page.

FUNCTION new_rental
(v_last_name IN member.last_name%TYPE,
v_copy_id IN title_copy.copy_id%TYPE,
v_title_id IN title_copy.title_id%TYPE)
RETURN VARCHAR2 IS
v_status title_copy.status%TYPE := ’RENTED’;
v_member_id member.member_id%TYPE;
v_message results.message%TYPE;
BEGIN
DELETE FROM results;
SELECT member_id
INTO v_member_id
FROM member
WHERE UPPER(last_name) = UPPER(v_last_name);
INSERT INTO rental (book_date, copy_id,
member_id, title_id,
act_ret_date, exp_ret_date)
VALUES (sysdate, v_copy_id,
v_member_id, v_title_id,
NULL, sysdate+2);
UPDATE title_copy
SET status = v_status
WHERE copy_id = v_copy_id
AND title_id = v_title_id;
COMMIT;
v_message := ’This video is due: ’||
TO_CHAR(sysdate+2,’DD-MON-YY’);
RETURN (v_message);

Code continued on next page.

Practice Solutions AĆ193


Practice 26 Solutions continued

1b.—continued
Code has been formatted to fit page.

EXCEPTION
WHEN TOO_MANY_ROWS THEN
-- More than one member with the given last name.
DECLARE
CURSOR member_cursor IS
SELECT first_name, last_name, phone,
member_id
FROM member
WHERE UPPER(last_name)
= UPPER(v_last_name);
BEGIN
FOR member_rec IN member_cursor LOOP
INSERT INTO results (member_id, first_name,
last_name, phone)
VALUES (member_rec.member_id,
member_rec.first_name,
member_rec.last_name, member_rec.phone);
END LOOP;
COMMIT;
v_message := ’More than one ’||v_last_name||
’. Please check RESULTS table.’;
RETURN (v_message);
END;
WHEN NO_DATA_FOUND THEN
--No members with the given last name
v_message := v_last_name||
’ is not a registered member.’;
RETURN (v_message);
END;

AĆ194 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 26 Solutions continued

1.—continued
c. Create a procedure named MEM_TITLES to retrieve all the titles rented by a
member. Store the results in the RESULTS table.
" Solution file: SOLN\p26q1c.pls

PROCEDURE mem_titles
(v_mem_id member.member_id%TYPE)
IS
CURSOR member_cursor IS
SELECT r.member_id, t.title, r.title_id
FROM rental r, title t
WHERE r.member_id = v_mem_id
AND r.title_id = t.title_id;
BEGIN
DELETE FROM results;
FOR member_record IN member_cursor LOOP
INSERT INTO results (member_id, title_id, title)
VALUES (member_record.member_id,
member_record.title_id,
member_record.title);
END LOOP;
COMMIT;
END;

Practice Solutions AĆ195


Practice 26 Solutions continued

1.—continued
d. If a title is rented, create a reservation for that movie. Name your procedure
RESERVE_MOVIE.
" Solution file: SOLN\p26q1d.pls
Code has been formatted to fit page.

PROCEDURE reserve_movie
(v_member_id IN member.member_id%TYPE,
v_title IN title.title%TYPE)
IS
v_title_id title.title_id%TYPE;
v_message results.message%TYPE;
v_exp_ret_date rental.exp_ret_date%TYPE;
BEGIN
DELETE FROM results;
SELECT title_id
INTO v_title_id
FROM title
WHERE UPPER(title) = UPPER (v_title);
INSERT INTO reservation (res_date,member_id,
title_id)
VALUES (sysdate,v_member_id,v_title_id);
SELECT MIN(exp_ret_date)
INTO v_exp_ret_date
FROM rental
WHERE title_id = v_title_id;
v_message := ’Earliest expected return date: ’||
TO_CHAR(v_exp_ret_date,’DD-MON-YY’);
INSERT INTO results (title_id, title, message)
VALUES (v_title_id, v_title, v_message);
COMMIT;
END;

AĆ196 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 26 Solutions continued

1.—continued

e. When a video is returned, change the rental status for that returned copy.
When the video is successfully checked in, store a message in the RESULTS
table. Check the to see if there are reservations for the film title, and store a
message in the RESULTS table. Name your procedure RETURN_RENTAL.
" Solution file: SOLN\p26q1e.pls
Code has been formatted to fit page.

PROCEDURE return_rental
(v_copy_id IN rental.copy_id%TYPE,
v_title_id IN rental.title_id%TYPE)
IS
v_message results.message%TYPE;
v_status title_copy.status%TYPE
:= ’AVAILABLE’;
v_res_date reservation.res_date%TYPE;
v_member_id reservation.member_id%TYPE;
e_look_up_failed EXCEPTION;
BEGIN
DELETE FROM results;
UPDATE rental
SET act_ret_date = SYSDATE
WHERE copy_id = v_copy_id
AND title_id = v_title_id;
IF SQL%NOTFOUND THEN
RAISE e_look_up_failed;
END IF;
SELECT MIN(res_date), member_id
INTO v_res_date, v_member_id
FROM reservation
WHERE title_id = v_title_id
GROUP BY member_id;
v_status := ’RESERVED’;
v_message := ’Call this member to say the movie
has been returned.’;

Code continued on next page.

Practice Solutions AĆ197


Practice 26 Solutions continued

1e.—continued
Code has been formatted to fit page.

INSERT INTO results (member_id, title_id, message)


VALUES (v_member_id, v_title_id, v_message);
UPDATE title_copy
SET status = v_status
WHERE copy_id = v_copy_id
AND title_id = v_title_id;
COMMIT;
EXCEPTION
WHEN NO_DATA_FOUND THEN
UPDATE title_copy
SET status = v_status
WHERE copy_id = v_copy_id
AND title_id = v_title_id;
COMMIT;
WHEN e_look_up_failed THEN
v_message := ’Invalid COPY_ID=’||
TO_CHAR(v_copy_id)||
’ and TITLE_ID=’||TO_CHAR(v_title_id)||
’ combination.’;
INSERT INTO results (message)
VALUES (v_message);
COMMIT;
END;

AĆ198 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 26 Solutions continued

1.—continued
f. If a video is returned damaged, change its status to DAMAGED. If that copy
was the only copy owned by the store, store a message to buy another copy in
the RESULTS table. If only one copy remains for rental, store a warning that
only one copy is left for rental in the RESULTS table. Name your procedure
DAMAGED_COPY.
" Solution file: SOLN\p26q1f.pls

PROCEDURE damaged_copy
(v_copy_id IN title_copy.copy_id%TYPE,
v_title_id IN title_copy.title_id%TYPE)
IS
v_status title_copy.status%TYPE
:= ’DESTROYED’;
v_count NUMBER;
v_message results.message%TYPE := NULL;
BEGIN
DELETE FROM results;
UPDATE title_copy
SET status = v_status
WHERE copy_id = v_copy_id
AND title_id = v_title_id;
UPDATE rental
SET act_ret_date = SYSDATE
WHERE copy_id = v_copy_id
AND title_id = v_title_id;
SELECT COUNT(title_id)
INTO v_count
FROM title_copy
WHERE title_id = v_title_id;
IF v_count = 1 THEN
v_message := ’Buy another copy.’;
INSERT INTO results (title_id, message)
VALUES (v_title_id, v_message);

Code continued on next page.

Practice Solutions AĆ199


Practice 26 Solutions continued

1f.—continued

ELSIF v_count = 2 THEN


v_message := ’Only one copy left for rental.’;
INSERT INTO results (title_id, message)
VALUES (v_title_id, v_message);
END IF;
COMMIT;
END;

AĆ200 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice 26 Solutions continued

1.—continued
g. Create a procedure named TOP_RENTAL to determine the top rental. Allow
for more than one top rental. Store the names and a message of the top rentals
in the RESULTS table.
" Solution file: SOLN\p26q1g.pls
Code has been formatted to fit page.

PROCEDURE top_rental
IS
v_count_title NUMBER;
v_title_id title.title_id%TYPE;
v_title title.title%TYPE;
v_flag NUMBER;
v_message results.message%TYPE
:= ’Top rental’;
CURSOR popular_cursor IS
SELECT r.title_id, t.title, COUNT(r.title_id)
FROM rental r, title t
WHERE r.title_id = t.title_id
GROUP BY r.title_id, t.title
ORDER BY 3 DESC;
BEGIN
DELETE FROM results;
OPEN popular_cursor;
FETCH popular_cursor INTO
v_title_id, v_title, v_count_title;
v_flag := v_count_title;
WHILE (popular_cursor%FOUND
AND v_flag = v_count_title) LOOP
INSERT INTO results (title_id, title, message)
VALUES (v_title_id, v_title, v_message);
FETCH popular_cursor INTO
v_title_id, v_title, v_count_title;
END LOOP;
COMMIT;
END;

Practice Solutions AĆ201


AĆ202 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
B

Table Descriptions and Data


BĆ2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Summit Sporting Goods Database Diagram

ORD_ID
ID
S_ITEM S_ORD

PRODUCT_ID SALES_REP_ID CUSTOMER_ID

S_INVENTORY
*
PRODUCT_ID
ID

ID ID ID S_CUSTOMER
S_PRODUCT S_WAREHOUSE
SALES_REP_ID
IMAGE_ID REGION_ID
MANAGER_ID

ID ID ID ID

S_IMAGE S_EMP
DEPT_ID
MANAGER_ID
ID

S_DEPT
REGION_ID

ID ID ID

S_REGION

* Unique occurrences are identified by PRODUCT_ID and WAREHOUSE_ID.

Table Descriptions and Data BĆ3


S_CUSTOMER Table

SQL> DESCRIBE s_customer

Name Null? Type

ID NOT NULL NUMBER(7)


NAME NOT NULL VARCHAR2(50)
PHONE VARCHAR2(25)
ADDRESS VARCHAR2(400)
CITY VARCHAR2(30)
STATE VARCHAR2(20)
COUNTRY VARCHAR2(30)
ZIP_CODE VARCHAR2(75)
CREDIT_RATING VARCHAR2(9)
SALES_REP_ID NUMBER(7)
REGION_ID NUMBER(7)
COMMENTS VARCHAR2(255)

Note: The data on the pages to follow has been formatted. Use the provided table
descriptions for accurate column names.

BĆ4 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


S_CUSTOMER Table continued

SQL> SELECT * FROM s_customer;

Continued on Next Page

Table Descriptions and Data BĆ5


S_CUSTOMER Table continued

BĆ6 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


S_DEPT Table

SQL> DESCRIBE s_dept

Name Null? Type

ID NOT NULL NUMBER(7)


NAME NOT NULL VARCHAR2(25)
REGION_ID NUMBER(7)

SQL> SELECT * FROM s_dept;

Table Descriptions and Data BĆ7


S_EMP Table

SQL> DESCRIBE s_emp

Name Null? Type

ID NOT NULL NUMBER(7)


LAST_NAME NOT NULL VARCHAR2(25)
FIRST_NAME VARCHAR2(25)
USERID NOT NULL VARCHAR2(8)
START_DATE DATE
COMMENTS VARCHAR2(255)
MANAGER_ID NUMBER(7)
TITLE VARCHAR2(25)
DEPT_ID NUMBER(7)
SALARY NUMBER(11,2)
COMMISSION_PCT NUMBER(4,2)

BĆ8 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


S_EMP Table continued

SQL> SELECT * FROM s_emp;

Table Descriptions and Data BĆ9


S_IMAGE Table

SQL> DESCRIBE s_image

Name Null? Type

ID NOT NULL NUMBER(7)


FORMAT VARCHAR2(25)
USE_FILENAME VARCHAR2(25)
FILENAME VARCHAR2(25)
IMAGE LONG RAW

SQL> SELECT * FROM s_image;

BĆ10 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


S_INVENTORY Table

SQL> DESCRIBE s_inventory

Name Null? Type

PRODUCT_ID NOT NULL NUMBER(7)


WAREHOUSE_ID NOT NULL NUMBER(7)
AMOUNT_IN_STOCK NUMBER(9)
REORDER_POINT NUMBER(9)
MAX_IN_STOCK NUMBER(9)
OUT_OF_STOCK_EXPLANATION VARCHAR2(255)
RESTOCK_DATE DATE

Table Descriptions and Data BĆ11


S_INVENTORY Table continued

SQL> SELECT * FROM s_inventory;

Continued on Next Page

BĆ12 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


S_INVENTORY continued

Continued on Next Page

Table Descriptions and Data BĆ13


S_INVENTORY continued

Continued on Next Page

BĆ14 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


S_INVENTORY continued

Table Descriptions and Data BĆ15


S_ITEM Table

SQL> DESCRIBE s_item

Name Null? Type

ORD_ID NOT NULL NUMBER(7)


ITEM_ID NOT NULL NUMBER(7)
PRODUCT_ID NOT NULL NUMBER(7)
PRICE NUMBER(11,2)
QUANTITY NUMBER(9)
QUANTITY_SHIPPED NUMBER(9)

BĆ16 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


S_ITEM Table continued

SQL> SELECT * FROM s_item;

Continued on Next Page

Table Descriptions and Data BĆ17


S_ITEM Table continued

Continued on Next Page

BĆ18 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


S_ITEM Table continued

Table Descriptions and Data BĆ19


S_ORD Table

SQL> DESCRIBE s_ord

Name Null? Type

ID NOT NULL NUMBER(7)


CUSTOMER_ID NOT NULL NUMBER(7)
DATE_ORDERED DATE
DATE_SHIPPED DATE
SALES_REP_ID NUMBER(7)
TOTAL NUMBER(11,2)
PAYMENT_TYPE VARCHAR2(6)
ORDER_FILLED VARCHAR2(1)

BĆ20 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


S_ORD Table continued

SQL> SELECT * FROM s_ord;

Table Descriptions and Data BĆ21


S_PRODUCT Table

SQL> DESCRIBE s_product

Name Null? Type

ID NOT NULL NUMBER(7)


NAME NOT NULL VARCHAR2(50)
SHORT_DESC VARCHAR2(255)
LONGTEXT_ID NUMBER(7)
IMAGE_ID NUMBER(7)
SUGGESTED_WHLSL_PRICE NUMBER(11,2)
WHLSL_UNITS VARCHAR2(25)

BĆ22 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


S_PRODUCT Table continued

SQL> SELECT * FROM s_product;

Continued on Next Page

Table Descriptions and Data BĆ23


S_PRODUCT Table continued

BĆ24 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


S_REGION Table

SQL> DESCRIBE s_region

Name Null? Type

ID NOT NULL NUMBER(7)


NAME NOT NULL VARCHAR2(50)

SQL> SELECT * FROM s_region;

Table Descriptions and Data BĆ25


S_WAREHOUSE Table

SQL> DESCRIBE s_warehouse

Name Null? Type


ID NOT NULL NUMBER (7)
REGION_ID NOT NULL NUMBER (7)
ADDRESS LONG
CITY VARCHAR2 (30)
STATE VARCHAR2 (20)
COUNTRY VARCHAR2 (30)
ZIP_CODE VARCHAR2 (75)
PHONE VARCHAR2 (25)
MANAGER_ID NUMBER (7)

SQL> SELECT * FROM s_warehouse;

ID REGION_ID ADDRESS CITY STATE


_____ ___________ _______________ ______________ _______
101 1 283 King Street SEATTLE WA
10501 5 5 Modrany BRATISLAVA
201 2 68 Via Centrale SAO PAOLO
301 3 6921 King Way LAGOS
401 4 86 Chu Street HONG KONG

COUNTRY ZIP_CODE PHONE MANAGER_ID


__________________ __________ _________ _____________
USA 6
CZECHOZLOVAKIA 10
Brazil 7
Nigeria 8
9

Note: Table has been split into two parts to make it fit in the page.

BĆ26 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


C

Using SQL*Plus to Create


Reports and Manage PL/SQL
Code
CĆ2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Objectives

This lesson covers formatting query output to produce simple reports,


controlling the SQL*Plus environment, and manipulating PL/SQL code using
SQL*Plus.
At the end of this lesson, you should be able to
D Differentiate between SQL and SQL*Plus commands.
D Identify SET commands used to control the SQL*Plus environment.
D Customize reports using SQL*Plus formatting commands.
D Create and modify anonymous blocks and program units with SQL*Plus and the
online editor.
D Execute SQL*Plus commands, anonymous blocks, program units, and SQL
statements.
D Compile procedures and functions.
D Embed messages to assist with debugging code.

Using SQL*Plus to Create Reports and Manage PL/SQL Code CĆ3


The SQL*Plus Environment

CĆ4 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Overview
SQL*Plus is an environment in which you can
D Execute SQL statements to retrieve, modify, add, and remove data from database
tables.
D Format, perform calculations on, store, and print query results in the form of
reports.
D Issue SQL statements to create, alter, and remove database tables.
D Create anonymous blocks, subprograms, database triggers using procedural
language extension, PL/SQL.
SQL*Plus has a variety of commands you need to use to execute subprograms, pass
values in and out of PL/SQL blocks, and debug your code.
SQL*Plus commands may be divided into the following main categories.

Category Purpose
Environment Affects the general behavior of SQL statements for the
session.
Format Formats query results.
File manipulation Saves, loads, and runs script files.
Execution Sends SQL or PL/SQL commands from SQL buffer to
Oracle7 Server.
Edit Modifies SQL commands in the buffer.
Interaction Allows users to create and pass variables to SQL
statements, print variable values, and print messages to
the screen.
Miscellaneous Various commands to connect to the database,
manipulate the SQL*Plus environment, and display
column definitions.

Using SQL*Plus to Create Reports and Manage PL/SQL Code CĆ5


Entering Commands in SQL*Plus

CĆ6 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Entering Commands in SQL*Plus
Once you log in to SQL*Plus, you see the command prompt. Issue all your
commands at this prompt. Three types of commands can be entered at this prompt.
D SQL commands to manipulate data and structures in the database.
D SQL*Plus command to format query results, set the environment, edit commands,
and create variables.
D PL/SQL blocks to work with information in the database in a procedural method.
To execute commands, type them at the command prompt. SQL*Plus commands do
not need to be terminated with a semicolon (;). SQL statements and PL/SQL blocks
do need to be terminated with a semicolon to send the statement to the Oracle7
Server.

Using SQL*Plus to Create Reports and Manage PL/SQL Code CĆ7


CĆ8 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Comparison of SQL and SQL*Plus Commands
This table compares SQL and SQL*Plus commands. They are distinctly different
programs, but are used together to perform some tasks, such as to format data in a
report and to control command files.

SQL SQL*Plus
Is a language for communicating with Recognizes SQL commands, and sends
the Oracle Server to access data. them to the server.
Is based on American National Is the Oracle proprietary interface for
Standards Institute (ANSI) standard executing SQL commands.
SQL.
Manipulates data and table definitions in Does not allow you to manipulate values
the database. in the database.
Is entered into the SQL*Buffer on one or Is entered one line at a time; not stored
more lines. in the SQL buffer.
Does not have a continuation character. Has a dash “-” as a continuation
character if the command is longer than
one line.
Cannot be abbreviated. Can be abbreviated.
Uses a termination character to execute Does not require termination characters;
commands required. commands are immediately executed.
Uses functions to perform some Uses commands to format data.
formatting.

Using SQL*Plus to Create Reports and Manage PL/SQL Code CĆ9


CĆ10 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
SQL*Plus SET Commands
Control the environment in which SQL*Plus is currently operating by using the SET
commands.

Syntax

SET system_variable value

where: system_variable is a variable that controls one aspect of the


session environment.
value is a value for the system variable.

Default Settings Using the login.sql File


The login.sql file contains standard SET and other SQL*Plus commands that you
may require for every session. The file is read and commands are implemented at log
in. When you log out of your session, all customized setting are lost.

Changing the Default Settings


The settings implemented by login.sql can be changed during the current session.
Changes made are only current for that session. As soon as you log out, those settings
are lost.
Add permanent changes to settings to the login.sql file.
For more information, see
SQL*Plus User’s Guide and Reference, Release 3.3, “Command Reference.”

Using SQL*Plus to Create Reports and Manage PL/SQL Code CĆ11


CĆ12 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
SQL* Plus SET Commands

Some Useful SET Commands

SET Variable and Values Description


ARRAY[SIZE] {20|n} Sets the database data fetch size.
COLSEP { |text} Sets text to be printed between columns. Default
is single space.
FEED[BACK] {6|n|OFF|ON} Displays the number of records returned by a
query when the query selects at least n records.
HEA[DING]{OFF|ON} Determine whether column headings are
displayed in reports.
LIN[ESIZE] {80|n} Sets the number of characters per line to n for
reports.
LONG {80|n} Sets maximum width for displaying LONG
values.
PAGES[IZE] {24|n} Specifies the number of lines per page of output.
PAU[SE] {OFF|ON|text} Allows you to control scrolling of your terminal.
You must press [Return] after seeing each pause.
TERM[OUT] {OFF|ON} Determines whether output is displayed to the
screen.

Guidelines
D Use the SHOW command to view current values for any of these settings, for
example SHOW PAUSE. To see all SET variable values, use the SHOW ALL
command.
D The value n represents a numeric value.
D Underlined values shown above indicate default values. If you enter no value with
the variable, then SQL*Plus assumes the default value.

Using SQL*Plus to Create Reports and Manage PL/SQL Code CĆ13


CĆ14 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Creating a Report

Script File
You can create a script file (or command file) that includes both a SQL SELECT
statement and SQL*Plus commands used to format and reset command values. Script
files are useful for saving both a SQL statement and any SQL*Plus settings specific
to that statement.
Additionally, you can create a file to hold all your default SQL*Plus commands,
which may be executed at any time to reset your settings. This file can be executed
from within your command file.

SQL*Plus Format Commands


You can control the report features described above by using the following
commands:

Command Purpose
COL[UMN] [column option] Controls column formats.
TTI[TLE] [text|OFF|ON] Specifies a header to appear at the top of each
page of the report.
BTI[TLE] [text|OFF|ON] Specifies a footer to appear at the bottom of
each page of the report.

Guidelines
D All format commands remain in effect until the end of the SQL*Plus session, or
until the format setting is overwritten or cleared.
D Remember to reset your SQL*Plus settings to default values after every report.
D There is no command for setting a SQL*Plus variable to its default value; you
must know the specific value or log out and log in again.
D If you give an alias to your column, you must reference the alias name, not the
column name.

Using SQL*Plus to Create Reports and Manage PL/SQL Code CĆ15


CĆ16 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Creating a Report continued

TTITLE and BTITLE Commands


Use the TTITLE command to format page headers and the BTITLE command for
footers. Footers appear at the end of the page according to the PAGESIZE value.

Syntax
The syntax for BTITLE and TTITLE is identical. Only the TTITLE syntax is shown.
You can use the vertical bar (|) to split the text of the title across several lines.

TTI[TLE] [printspec [text|variable]][OFF|ON]

where: printspec is an option to specify the type of settings.


text represents the title text. Enter single quotes if
the text is more than one word.
variable is a system-maintained value.

Example
Set the report header to display Salary centered on one line, and Report centered
below it.

SQL> TTITLE ’Salary|Report’

Display or Clear Settings


To show or clear the current header and footer command settings, use the following
commands.

Command Description
TTITLE Displays the current setting for the header.
TTITLE OFF Turns the header off.
BTITLE Displays the current setting for the footer.
BTITLE OFF Turns the footer off.

Using SQL*Plus to Create Reports and Manage PL/SQL Code CĆ17


CĆ18 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Creating a Report continued

Creating the Script File to Run a Report


You can either enter each of the SQL*Plus commands at the SQL prompt or put all
the commands, including the SELECT statement, in a command (or script) file. A
typical script consists of at least one SELECT statement and several SQL*Plus
commands.

Steps to Create a Script File


1. Create the SQL SELECT statement at the SQL prompt. Ensure that the data
required for the report is accurate before you save the statement to a file and
apply formatting commands. Ensure that the relevant ORDER BY clause is
included if you intend to use breaks.
2. Save the SELECT statement to a script file.
3. Edit the script file to enter the SQL*Plus commands.
4. Add the required formatting commands before the SELECT statement. Be certain
not to place SQL*Plus commands within the SELECT statement.
5. Verify that the SELECT statement is followed by a run character, either a
semicolon (;) or a slash (/).
6. Add the format-clearing SQL*Plus commands after the run character. As an
alternative, you can call a reset file which contains all the format-clearing
commands.
7. Save the script file with your changes.
8. In SQL*Plus, run the script file by entering START filename or @filename. This
command is required to read and execute the script file.

Guidelines
D You can include blank lines between SQL*Plus commands in a script.
D You can abbreviate SQL*Plus commands.
D Include reset commands at the end of the file in order to restore the original
SQL*Plus environment.

Using SQL*Plus to Create Reports and Manage PL/SQL Code CĆ19


1

1 Header 2 Column labels and 3 Footer


format

CĆ20 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Creating a Report continued

Example
Create a script file to create a report which displays the job title, last name, and salary
for every employee who is not a vice president or a warehouse manager. Add a
centered, two-lined header that reads Employee Report, and a centered footer that
reads Confidential. Rename the title column to read Job Category split over two lines.
Rename the employee name column to read Employee. Print the salary column with
the label in initial capitalization and formatted as $2,500.00.

REM ** This report covers all employees who are not


REM ** vice presidents or warehouse managers.
SET ECHO OFF
SET PAGESIZE 37
SET LINESIZE 60
SET FEEDBACK OFF
TTITLE ’Employee|Report’
BTITLE ’Confidential’
COLUMN title HEADING ’Job|Category’ FORMAT A22
COLUMN last_name HEADING ’Employee’ FORMAT A22
COLUMN salary HEADING ’Salary’ FORMAT $99,999.99

REM ** Insert SELECT statement


SELECT title, last_name, salary
FROM s_emp
WHERE title NOT LIKE ’VP%’
AND title <> ’Warehouse Manager’
ORDER BY title, last_name, salary
/
REM ** Run a reset command file
START reset.sql
SET ECHO ON

REM represents a remark or comment in SQL*Plus.

Using SQL*Plus to Create Reports and Manage PL/SQL Code CĆ21


Declaring and Creating PL/SQL Blocks

CĆ22 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Declaring and Creating PL/SQL Blocks
You can use two methods to process PL/SQL blocks in SQL*Plus.
D Define a block in the SQL buffer, then execute the contents of the buffer.
D Define a block as part of a SQL*Plus script file, then start the file.

Declaring PL/SQL Blocks in the SQL Buffer


A PL/SQL block is treated as one continuous statement in the buffer, and the
semicolons (;) within the block do not close or execute the contents of the buffer.
SQL*Plus detects the start of a PL/SQL block when you enter either DECLARE or
BEGIN at the prompt. You can close the buffer without executing the block by
entering a period (.) at the number prompt of the buffer.
To run the buffered PL/SQL block, enter the RUN command or a slash (“/”) at the
prompt. If the block executes successfully, without unhandled exceptions or compile
errors, you will see a message.

Creating SQL*Plus Files Containing PL/SQL Blocks


You can include PL/SQL blocks in files of SQL and SQL*Plus commands. Create the
file using the operating system editor. SQL*Plus commands may not occur inside the
PL/SQL block itself, but you can include them elsewhere in the file.
You can reference SQL*Plus substitution variables inside the block, but remember
that they are substituted with the variable’s contents before the code is parsed or
executed. This means that if you reference a SQL*Plus substitution variable in a
PL/SQL loop, then a value is substituted for the variable once, and not for each
iteration of the loop.

Using SQL*Plus to Create Reports and Manage PL/SQL Code CĆ23


SQL*Plus Commands

CĆ24 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Entering Commands in SQL*Plus
SQL*Plus contains an array of commands to format reports and initiate the users’
environment.

SQL*Plus Command Description


ACCEPT Reads input from the user and stores the input into a
variable.
VARIABLE Declares a bind, or host, variable that can be
referenced in PL/SQL with a preceding colon (:).
PRINT Displays the current value of bind variables.
EXECUTE Executes a single PL/SQL statement.

For more information, see


SQL*Plus User’s Guide and Reference, Release 3.3.

Using SQL*Plus to Create Reports and Manage PL/SQL Code CĆ25


CĆ26 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Passing Input and Output Values
A substitution variable, or parameter, preceded by an ampersand (&) is used to
represent a value to be passed into a statement. A global variable preceded by a colon
(:)is used to pass information out of the PL/SQL block.

Input Values
From SQL*Plus, input a value into the PL/SQL block by means of a SQL*Plus
substitution value. Follow the steps listed below.
1. Outside the PL/SQL block, assign a value from the keyboard into a SQL*Plus
substitution value with the SQL*Plus ACCEPT command.
2. Within the PL/SQL block, embed the SQL*Plus substitution parameter wherever
it is needed as input, referencing it with the ampersand (&) prefix.

Syntax

ACCEPT variable PROMPT message

where: variable is the name of the substitution variable to store


the value.
message is the message displayed.

Using SQL*Plus to Create Reports and Manage PL/SQL Code CĆ27


CĆ28 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Passing Input and Output Values continued

Output Values
Output a value from the PL/SQL block into SQL*Plus by using a SQL*Plus global
variable. Follow the steps listed below.
1. Outside the PL/SQL block, declare a SQL*Plus global variable with the
SQL*Plus VARIABLE command.
2. Within the PL/SQL block, embed the SQL*Plus global variable wherever it is
needed as output, referencing it with the colon (:) prefix.
3. Outside the PL/SQL block, print the output value on the screen with the
SQL*Plus PRINT command.

Syntax

VARIABLE variable [NUMBER|CHAR|CHAR(n)|VARCHAR2(n)]

PRINT variable

where: variable is the name of the bind variable.


n is the maximum length for the datatype.

Using SQL*Plus to Create Reports and Manage PL/SQL Code CĆ29


CĆ30 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Debugging in SQL*Plus
When you execute your PL/SQL code, one of two types of errors might appear. One
type is a compilation error. For anonymous blocks, you will see the errors appear on
the screen. For stored subprograms, the compilation errors are stored in the
USER_ERRORS data dictionary table. To access those errors, enter either of the
following commands at the prompt:

SQL> SHOW ERRORS


SQL> SELECT *
2 FROM user_errors;

The second type of error you can encounter is an exception, which is a message from
the PL/SQL engine indicating that an error occurred while performing some of the
tasks in the block. Handling of exceptions is covered in lesson 25 of this course.

Using SQL*Plus to Create Reports and Manage PL/SQL Code CĆ31


CĆ32 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Debugging in SQL*Plus continued

One method for debugging your PL/SQL block using SQL*Plus is to embed global
variables at specific points with a message. Each message can contain information
about how many times a loop was executed, or which statements were executed. You
can print the results of the global variables using the SQL*Plus PRINT command.

Example
Print a message indicating which DML statement was executed.

VARIABLE g_debug VARCHAR2(50)


ACCEPT p_num PROMPT ’Enter a number: ’
DECLARE
v_num NUMBER := &p_num;
BEGIN
IF MOD(v_num,2) = 0 THEN
UPDATE...
:g_debug := ’Even number entered.’;
ELSE
INSERT...
:g_debug := ’Odd number entered.’;
END IF;
END;
/
SQL> START test
Enter a number: 10
PL/SQL procedure successfully completed.
SQL> PRINT g_debug
G_DEBUG
----------------------------------------------------
Even number entered.

Using SQL*Plus to Create Reports and Manage PL/SQL Code CĆ33


CĆ34 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Displaying Contents of a Subprogram
You can obtain the text of a stored procedure or a function from USER_SOURCE
data dictionary view.

Example
Display contents of the procedure CHANGE_SALARY.

SQL> SELECT text


2 FROM user_source
3 WHERE type = ‘PROCEDURE’
4 and name = ‘CHANGE_SALARY’;

TEXT
––––––––––––––––––––––––––––––––––––––––––––––––––––
PROCEDURE change_salary
(v_emp_id IN NUMBER,
v_new_salary IN NUMBER)
IS
BEGIN
UPDATE s_emp
SET salary = v_new_salary
WHERE id = v_emp_id;
COMMIT;
END change_salary;

Using SQL*Plus to Create Reports and Manage PL/SQL Code CĆ35


CĆ36 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Executing Stored Subprograms
Once you create your stored programs, you invoke them by using the SQL*Plus
EXECUTE command.

Executing Stored Procedures


The EXECUTE command runs the PL/SQL statement stored in the database.

Syntax

EXECUTE procedure_name [(argument_list)]

where: procedure_name is the name of the procedure.


argument_list is the set of variables, expressions, constants, or
literals passed to the procedure.

Executing Stored Functions


Functions require that a value be returned. Therefore, you call the function as part of
an expression. Create a global variable to hold the returned value when using the
EXECUTE command.

Syntax

EXECUTE variable := function_name [(argument_list)]

where: procedure_name is the name of the function.


argument_list is the set of variables, expressions, constants, or
literals passed to the function.

Using SQL*Plus to Create Reports and Manage PL/SQL Code CĆ37


CĆ38 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Executing Stored Subprograms continued

Issue SQL commands and evaluate PL/SQL constructs.

Example
Enter a data definition language (DDL) statement at the command prompt to create
the B_TEST table.

SQL> CREATE TABLE b_test (col1 NUMBER);

Insert three rows in the B_TEST table using a PL/SQL statement.

SQL> CREATE PROCEDURE testproc IS


2 BEGIN
3 FOR i IN 1..3 LOOP
4 INSERT INTO b_test VALUES (i);
5 END LOOP;
6 END;
7 /
Procedure created.

Execute the procedure.

SQL> EXECUTE testproc;


PL/SQL procedure successfully completed.

Display the contents of the B_TEST table.

SQL> SELECT *
2 FROM b_test;
COL1
---------
1
2
3

Using SQL*Plus to Create Reports and Manage PL/SQL Code CĆ39


CĆ40 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Summary

Manipulating PL/SQL Using SQL*Plus


You can use SQL*Plus to create, debug, and execute PL/SQL blocks
D Create and modify anonymous blocks and program units with SQL*Plus and the
online editor.
D Execute SQL*Plus commands, anonymous blocks, program units, and SQL
statements.
D Compile procedures and functions.
D Create and manipulate SQL*Plus variables for passing values in and out of your
PL/SQL block.
D Embed messages to assist with debugging code.

SQL and SQL*Plus Comparisons


SQL and SQL*Plus are distinctively different languages, but are used together to
create reports. SQL communicates with the Oracle7 Server to access data. The SQL
commands are stored in the SQL buffer, and they are executed by a termination
character. SQL*Plus commands recognize SQL commands and send them to the
Oracle7 Server. SQL*Plus commands are entered one line at a time and are not stored
in the SQL buffer.

SQL*Plus Commands
SQL*Plus commands are useful in developing reports that are based on a query. They
can set up the environment at log in when they reside in the login.sql file.

Using SQL*Plus to Create Reports and Manage PL/SQL Code CĆ41


CĆ42 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice Overview
This practice will familiarize you with the SQL*Plus commands used to build reports
and those used with PL/SQL blocks.

Practice Contents
D Distinguishing between SQL and SQL*Plus
D Customizing reports
D Executing a PL/SQL anonymous block
D Creating and executing a stored function

Using SQL*Plus to Create Reports and Manage PL/SQL Code CĆ43


CĆ44 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Practice C
1. Determine whether each of the following commands is a SQL or SQL*Plus
command. Place a check in the appropriate column.

Command SQL SQL*Plus


DESCRIBE
SPOOL
SELECT
SET
RUN
INSERT

2. The number of tasks on the left do not match the commands listed on the right.
Draw lines to match the correct command to the correct task.

Task Command
Display the definition of a table. SET LINESIZE
Suppress the message displaying the SPOOL
number of rows returned from a query.
Control the character length of a line. DESCRIBE
Specify a heading to appear at the top SET FEEDBACK
of each report page. OFF
Alter the display characteristics of a TTITLE
column.
Document a command or script file. COLUMN
Send output to a file for printing later. REM

Using SQL*Plus to Create Reports and Manage PL/SQL Code CĆ45


Practice C continued

3. Load and execute a loop counter.


a. Launch SQL*Plus. Your instructor will give you the login information.
b. Start the LABS\pcloop.sql file to create the COUNT_LOOPS procedure.
c. View the arguments for the COUNT_LOOPS procedure by using the
DESCRIBE command.
d. Create a global variable named G_OUTPUT to hold a text string from the
argument V_OUTPUT.
e. Execute the COUNT_LOOPS procedure.
f. Display the value in the G_OUTPUT global variable.
4. Execute an anonymous PL/SQL block that accepts a number and determines if it
is odd or even.
a. Start the LABS\pcmsg.sql file to execute the PL/SQL block.
b. Enter a value at the prompt. Sample values are 3, “hello”, “NULL”, and 6
c. Display the value in the G_MESSAGE global variable.

CĆ46 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice C Solutions
1. Determine whether each of the following commands is a SQL or SQL*Plus
command.

Command SQL SQL*Plus


DESCRIBE X
SPOOL X
SELECT X
SET X
RUN X
INSERT X

2. The number of tasks on the left do not match the commands listed on the right.
Draw lines to match the correct command to the correct task.

Task Command
Display the definition of a table. SET LINESIZE
Suppress the message displaying the SPOOL
number of rows returned from a query.
Control the character length of a line. DESCRIBE
Specify a heading to appear at the top of SET FEEDBACK
each report page. OFF
Alter the display characteristics of a TTITLE
column.
Document a command or script file. COLUMN
Send output to a file for printing later. REM

Using SQL*Plus to Create Reports and Manage PL/SQL Code CĆ47


Practice C Solutions continued

3. Load and execute a loop counter.


a. Launch SQL*Plus. Your instructor will give you the login information.
b. Start the LABS\pcloop.sql file to create the COUNT_LOOPS procedure.

SQL> START c:\labs\pcloop


Procedure created.

c. View the arguments for the COUNT_LOOPS procedure by using the


DESCRIBE command.

SQL> DESCRIBE count_loops


PROCEDURE count_loops
Argument Name Type In/Out Default?
--------------------- ------------- ----- --------
V_COUNT NUMBER IN
V_OUTPUT VARCHAR2 OUT

d. Create a global variable named G_OUTPUT to hold a text string from the
argument V_OUTPUT.

SQL> VARIABLE g_output VARCHAR2(50)

e. Execute the COUNT_LOOPS procedure.

SQL> EXECUTE count_loops (4, :g_output);


PL/SQL procedure successfully completed.

f. Display the value in the G_OUTPUT global variable.

SQL> PRINT g_output


G_OUTPUT
-------------------------------------------
4 times through the loop

CĆ48 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder


Practice C Solutions continued

4. Execute an anonymous PL/SQL block that accepts a number and determines if it


is odd or even.
a. Start the LABS\pcmsg.sql file to execute the PL/SQL block.
b. Enter a value at the prompt. Sample values are 3, “hello”, “NULL”, and 6
c. Display the value in the G_MESSAGE global variable.

SQL> START c:\labs\pcmsg


Enter a number: 3

PL/SQL procedure successfully completed.


SQL> PRINT g_message
G_message
-------------------------------------------
ODD number

SQL> START c:\labs\pcmsg


Enter a number: hello
”hello” is not a valid number
Enter a number: NULL
”null” is not a valid number
Enter a number: 6

PL/SQL procedure successfully completed.


SQL> PRINT g_message
G_message
-------------------------------------------
EVEN number

Using SQL*Plus to Create Reports and Manage PL/SQL Code CĆ49


CĆ50 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
D

Related Products and Services


DĆ2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Related Products
DBA*Assist Version 1.4 is a SQL*Forms application that aids the DBA in managing
the Oracle Version 6.0 database. Using a simple and effective menu structure,
DBA*Assist provides a powerful productivity tool to simplify Oracle database
administration in the key areas below.

User Maintenance
D Query, add, and alter database users and their attributes.

Space Analysis
D Displays information screens on tablespace size, usage and fragmentation at the
three distinct levels of tablespace, user and object.

Space Estimation
D Define tables and indexes and perform “what if” analysis to estimate space and
proper storage procedures.

Tablespace and Rollback Segment Maintenance


D Query, add, drop, and alter tablespaces and rollback segments.

Client/Server
D Invoke DBA*Assist as a client SQL*Forms application and “manage” the target
database over a SQL*Net connection.

Related Products and Services DĆ3


DĆ4 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Related Services
When you need to augment your internal resources, need specific technical expertise,
or are seeking to maximize your technology investments fully, partnering with Oracle
Services is the answer. No one is more qualified than the Oracle Services team of
consultants to help you implement, customize, or integrate client-server technology.
Our 3,500 consultants in 43 countries can help you with local projects or
enterprise-wide, global, or multi-size implementations. We work closely with your
in-house staff to ensure that the solutions are tailored to your needs, and to transfer
the skills required to maintain and expand the completed system.

Oracle Consulting
D Business Process Reengineering (BPR) increases productivity by rapidly
providing you with efficient, streamlined yet flexible processes and technology
solutions that support your strategy.
D Custom Application Development draws upon our tools and CASE experience
to deploy rapidly specialized, easy–to–maintain client-server applications for your
business.
D Applications Consulting services offer experienced consultants who specialize
in rapidly implementing Oracle Cooperative Applications.
D Oracle Industries develops integrated solutions for specific industries using a
combination of Oracle and third-party products and services.
D Core Technology Services help you through support, system and applications
audits, performance tuning, and technology upgrades.
D Open Systems Transformation services provide an architecture and
implementation road map to transfer systems from legacy environments to
client-server.
For more information on Oracle Services, please call 1–800–ORACLE1 or contact
your local Oracle office.

Related Products and Services DĆ5


DĆ6 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Glossary

A MY_PROC(x), x is the argument. 2.


Clauses containing keywords and their
actual parameter The variable or specified values. For example,
expression referenced in the parameter ‘PRINT=YES’ is an argument.
list of a subprogram call.
ASCII Acronym for American National
Ada A high-level programming Standard Code for Information
language developed by the U.S. Interchange.
Department of Defense for use in
embedded computer systems.
B
alias A temporary name assigned to a
batch compile To translate, at once,
table, view, column, or value within a
several PL/SQL program units into a
SQL statement, used to refer to that item
machine executable form.
later in the same statement or in
associated SQL*Plus commands. bind reference A reference to a
parameter used to replace a single literal
anonymous block A PL/SQL program value (for example, a character string,
unit that has no name and does not require number, or date) appearing anywhere in a
the explicit presence of the BEGIN and PL/SQL construct or a SQL SELECT
END keywords to enclose the executable statement. For a bind reference, you must
statements. Since they are unnamed, precede the parameter name with a colon
anonymous blocks cannot be referenced (:). See also: lexical reference, parameter,
by other program units. global variable.
application One or more program bind variable A global variable you can
modules used to achieve a specific result. create outside of a package in a
Applications can be nested within other standalone session of Procedure Builder.
applications. For example, an application
block The basic program unit in
to control a company’s inventory could
PL/SQL, defined by the keywords
consist of various Forms applications for
DECLARE, BEGIN, EXCEPTION, and
input of data, and various Graphics
END.
applications to display the data visually.
body Contains the same information as
application subprogram A procedure the program unit specification, and also
or function that resides and executes in an includes the actual implementation of the
application. subprogram (that is, its sequence of
actions). In most cases, only a body must
argument 1. An expression within the
be defined for a subprogram.
parentheses of a subprogram, supplying a
value for the subprogram to operate on. breakpoint A debug action you can
For example, in the expression place at any source in a PL/SQL

GlossaryĆ1
subprogram that interrupts execution of resulting Cartesian product will be
the program unit and passes control to the 10,000 rows.
PL/SQL Interpreter. Breakpoints allow
CHAR datatype An Oracle datatype
you to incrementally execute a
provided for ANSI/ISO compatibility. A
subprogram.
CHAR column is a fixed-length column
built-ins A collection of extensions to and can contain any printable characters,
the PL/SQL language that are designed to such as A, 3, &, or blanks, and can have
be used with Developer/2000. Built-ins from 1 to 255 characters or can be null.
include datatypes, procedures, functions, child An object that is a member of a
exceptions, and constants. group, and is immediately below that
group object in its group tree. The objects
buffer A temporary storage area for data that compose a group object are children
during the transfer of that data between of that group. Every object is a child of its
the computer and a peripheral, or between parent.
parts of a computer. A buffer prevents
loss of information due to differences in clause A part of a SQL statement that
the speed or timing of the transfer and does not constitute the full statement; for
speeds up certain functions. example, a “WHERE clause.”
client A user, software application, or
computer that requests the services, data,
or processing of another application or
C computer (the “server”). In a two-task
call stack A chain of subprogram calls, environment, the client is the user
from the initial entry point down to the process. In a network environment, the
currently executing subprogram. Each client is the local user process and the
subprogram call is represented by a frame server may be local or remote.
on the downward-growing call stack, in client-server architecture Separation of
which newly entered subprograms are processing between two CPUs, one
added to the bottom of the stack. acting as the server that provides services
in a transaction and the other as the client
Cartesian product When you
in the transaction, requesting and
deactivate a relationship that is the only
receiving services. All responsibilities of
path relating two data sources, then
shared data management can be
execute a query using fields from both
processed by the computer running the
sides of the relationship, the result is a
database management system while the
Cartesian product. The query combines
workstations running the database
all rows from all included data sources.
application concentrate on the
A Cartesian product always retrieves
interpretation and display of data.
many rows and information that is
seldom useful. For example, if two data Clipboard A memory buffer. An
sources each contain 100 rows, the object remains on the Clipboard until you

GlossaryĆ2
cut or copy another object, or until you modify queries or access an application
quit the application. stored in a database.

column A vertical space in a database connect string The set of parameters,


table that represents a particular domain including a protocol, that SQL*Net uses
of data. A column has a column name (for to connect to a specific Oracle instance on
example, ENAME) and a specific the network.
datatype (for example, CHAR). For
example, in a table of employee constraint A rule or restriction
information, all of the employees’ names concerning a piece of data (such as a NOT
would constitute one column. A record NULL restriction on a column) that is
group column represents a database enforced at the database level, rather than
column. the object or application level.
construct A PL/SQL code structure.
command line An operating-system
There are two types of constructs:
command line. Most Oracle products can
non-value constructs do not return a
be invoked from a command line using a
value; value constructs return a value.
number of executable arguments.
control structures Programming
commit To make changes to data structures related to decision-making:
(inserts, updates, deletes) in the database selection, iteration, and sequence.
permanent. Before changes are stored,
both the old and new data exist so that copy To store a replica of a selected
changes can be stored or the data can be object on the Clipboard, so that it may be
restored to its prior state. pasted elsewhere in an editor if desired.
compile To translate a source program Cue Cards Just-in-time coaching for
as into a binary, executable format. frequently performed tasks. Available in
PL/SQL program units must be compiled Oracle Procedure Builder.
before they can be executed.
cursor 1. A small icon representing the
composite datatype Datatype composed position of the mouse. The shape of the
of multiple components. cursor varies, depending on the selected
tool. 2. An internal pointer to data
condition An expression whose value retrieved by a query. A cursor points only
is either true or false, such as X> 100. For to one row of data at a time; however, you
example, you can set a condition in a can use built-in subprograms to move the
query when you want the query to display cursor to any row in the data set.
only those rows that evaluate as true in
your expression. cut To delete one or more objects and
store them in the Clipboard, so that they
connect To log on to a database. You may be pasted elsewhere in an editor, if
must connect if you want to create or desired.

GlossaryĆ3
D NUMBER, LONG, RAW, and LONG
RAW.
data control language (DCL) The
category of SQL statements that control DATE An Oracle Server datatype. A
access to the data and to the database. date column may contain a date and time
Examples are the GRANT and REVOKE between January 1, 4712 B.C. and
statements. Occasionally DCL December 31, 4712 A.D.
statements are grouped with DML debug To detect, diagnose, and
statements. eliminate errors in programs.
data definition language (DDL) The debug action An user specified event
category of SQL statements that define or placed in a PL/SQL subprogram using
delete database objects such as tables or Procedure Builder functionality, usually
views. Examples are the CREATE, for the purpose of troubleshooting errors
ALTER, and DROP statements. raised during subprogram execution. See
also: breakpoint, debug trigger.
data dictionary A set of tables and
views owned by the database debug trigger A conditional debug
administrator. It is a central source of action you can place at any source line in
information for Oracle Server and other a PL/SQL subprogram. If the specified
relational databases. condition is met, the specified action is
taken before execution of the subprogram
data manipulation language (DML) resumes.
The category of SQL statements that debugger The Procedure Builder
query and update the database data. functionality within another
Common DML statements are SELECT, Developer/2000 component that
INSERT, UPDATE, and DELETE. simulates runtime execution of an
Occasionally DCL statements are application for testing and debugging.
grouped with DML statements.
default A value supplied by the system
data model A relational model that when a user does not specify a required
defines what data should be fetched from command parameter or attribute.
the database, what values should be
computed, and how data should be descendant An object that appears in
ordered in a report. Reports objects that another object’s group tree at any position
define the data model are queries, groups, below that other object. Every object is a
columns, parameters, and links. descendant of its antecedents.
drag Press and hold down a mouse
database A set of dictionary tables and button while you slide the mouse pointer
user tables that are treated as a unit. to a particular location in a window.
datatype A standard form of data. The duplicate An option that allows you to
Oracle datatypes are CHAR, DATE, copy objects directly on the layout

GlossaryĆ4
without affecting the contents of the foreign key A value or column in one
Clipboard. See also: copy. table that refers to a primary key in
another table.
formal parameter The variable
E declared in a subprogram specification
and referenced in the subprogram body.
editor A work area in which you
perform a specific set of tasks, such as function A PL/SQL subprogram that
creating a program unit or designing an executes an operation and returns a value
application. at the completion of the operation. A
function can be either built-in or
equijoin A type of join where the join user-named. Contrast with procedure.
condition is an equality, such as WHERE
S_EMP.DEPT_ID = S_DEPT.ID.
G
exception A warming or error condition
generated from a PL/SQL subprogram. global variable A logical container that
exists across an application. When an
executable argument An argument you application uses a global variable, the
can pass to a product executable, such as application maintains the variable until
‘OPENFILE=my_disp’ and the application is exited, or until another
‘PRINT=YES’. These arguments usually object explicitly removes it. See also:
are specified when the executable is parameter, bind variable, local variable
invoked from a command line.
grant To give a user access to a module.
export To store a copy of a module to Only a module’s creator can grant its
a file or database. access to other users.

expression A PL/SQL construct group function A SQL function that


combining variables, constants, literals, computes a single summary value from
and operations on their values. the individual values in specified groups
of rows. Examples are AVG, MAX, or
external PL/SQL library See library. SUM.
external query An ANSI-standard SQL GUI Acronym for Graphical User
SELECT statement that can be Interface. Also known as a bitmapped
referenced by other Oracle products. interface.

H
F
heading node A node in the Object
field The data stored at the intersection Navigator denoting a type of object
of a row and a column. which can be contained within or

GlossaryĆ5
associated with a report. Selecting a J
heading node does not select an object in
join Combining data from two (or more)
the report.
tables in a single SELECT statement.
host variable See global variable.

K
keyword Part of a command line syntax
I that must be supplied with a
corresponding argument.
icon A graphic representation of a
window or tool.
L
identifier See name.
lexical reference A reference to a
IF statement Control structure that parameter used to represent a string of
allows you to execute a sequence of text in a SQL SELECT statement. For a
statements conditionally. lexical reference, you must precede the
parameter name with an ampersand (&).
import To read a module from the file See also: bind reference, parameter
system or database, and incorporate it
into an application. library A collection of one or more
PL/SQL program units that are stored
index An optional structure associated together in a file or database, and that can
with a table that is used by Oracle Server be referenced by several applications at
to locate rows of the table quickly, and once.
(optionally) to guarantee that every row is
local database 1. The database on the
unique.
computer running the application. 2. The
insert mode A mode in which each database to which an application is
character you enter is inserted at the connected. This database parses and
cursor, pushing the following characters executes all SQL statements generated by
to the right. The opposite of Replace the application. See also: NO TAGremote
mode. database.
local variable A PL/SQL variable
Interpreter Define, display, debug, and declared only within the scope of the
execute Pl/SQL program units in the current program unit. See also:
Interpreter window of Oracle Procedure parameter, bind variable, global
Builder. variable.
Interpreter script A file containing any LONG datatype A standard ORACLE
mixture of PL/SQL source, Procedure datatype. A LONG column may contain
Builder commands, and SQL statements. any printable character, such as A, 3, &,

GlossaryĆ6
or blanks, and can be any length from 1 to O
65K characters; alternatively it can be
Object Navigator The window
null.
containing a hierarchical list of objects
loop In a PL/SQL subprogram, a for the current session. The list appears in
conditional statement that is repeated outline form, and enables the user to
until the condition is no longer met. accomplish several tasks such as creating,
editing, renaming, and deleting objects.
object privileges Privileges granted
(assigned) to end users so that they can
M use a database application to accomplish
specific tasks. Object privileges perform
megabyte (Mb) A unit of memory equal a particular action on a specific object.
to 1,048,576 bytes (1024 x 1024). Often For example, the privilege to delete rows
rounded to one million bytes. of a specific table is an object privilege.

module An object that can be shared by outer join A type of join that returns
multiple applications. External queries rows from one table that do not satisfy the
and PL/SQL libraries are examples of join condition, in addition to those that do
modules. satisfy the condition. Each additional row
is joined to an imaginary row in the other
table in which all the fields are null.

N P
name The unique identifier given to an packaged function A PL/SQL function
object. provided with Developer/2000 that can
be referenced anywhere within a program
node A specific location in the Object unit.
Navigator object hierarchy. Nodes can be package A method of encapsulating and
expanded to reveal information about an storing related procedures, functions,
object, such as cross references to other variables, and other package constructs
objects. together as a unit in the database. While
packages provide the database
NULL value The absence of a value. administrator or application developer
organizational benefits, they also offer
Number datatype A standard ORACLE
increased functionality and database
datatype. A NUMBER column can
performance.
contain a number, with or without a
decimal point and a sign, and can have package body Includes the actual
from 1 to 105 decimal digits (only 38 implementation of the package, which
digits are significant). may include private subprograms and

GlossaryĆ7
datatypes. The body is optional if the .pls The standard extension given to a
package consists only of declarations. PL/SQL program unit that has been
exported to a text file.
package specification Declares the
primary key In a database table, a set of
public interface to the package—that is,
columns used to enforce uniqueness of
the datatypes and subprograms that can
rows. The combination of column values
be referenced by other program units.
is unique for each row in the table. The
pane A distinct portion of an editor primary key is the most frequently used
where work is performed, usually means of accessing rows.
resizeable. privilege A right to successfully execute
a particular type of SQL statement. Some
parameter A global variable that is examples of privileges include rights to
defined in an application and exists connect to the database (create a session),
outside of a PL/SQL package or to create a table in your schema, to select
subprogram. See also: bind reference, rows from someone else’s table, and to
lexical reference. execute someone else’s stored procedure.
The privileges of an Oracle database can
parameter list A named programmatic be divided into two distinct categories:
construct that lists parameter names system privileges and object privileges.
(called keys), their types, and their
values. procedure A PL/SQL subprogram that
performs a specified sequence of actions.
parent An object that is immediately program unit A code structure you can
above another object in its group tree. A create using PL/SQL. Anonymous
group object is the parent to each of the blocks, subprogram specifications and
objects that compose it. Every object is bodies, and package specifications and
the parent of its children. bodies are examples of program units.
See also: subprogram
paste To place the contents of the
Clipboard (cut or copied objects) on the protocol A string you can enter when
layout. connecting to a database or server that
allows you to connect to a remote
PL/SQL A procedural extension of SQL database or server.
that provides programming constructs pull-down menu A set of options,
such as conditionals and procedures. displayed horizontally under the
application window title. Each option can
.pld The standard extension given to the represent a submenu or an action.
file representation of a Procedure Builder
Interpreter script.
Q
.pll The standard extension given to the query A SQL SELECT statement that
file representation of a PL/SQL library. specifies the data you wish to retrieve

GlossaryĆ8
from one or more tables or views of a row One set of field values in a table;
database. for example, the fields representing one
employee in the example table S_EMP.
Quick Tour Online help used to
introduce you to product terminology,
workflow, and theoretical concepts. S
Available in Oracle Procedure Builder.
schema A collection of related objects.
quit An option that terminates the Schema objects includes tables, views,
current session and returns the user to the sequences, stored program units,
operating system. On some systems, Quit synonyms, indexes, clusters, and
is Exit. database links.
scope The level at, or range in which,
an object operates.
R script See SQL script, Interpreter script
RDBMS (Relational Database SELECT statement A SQL statement
Management System) An Oracle that specifies which rows and columns to
Version 6 (and earlier) term. Refers to the fetch from one or more tables or views.
software used to create and maintain the See also: SQL statement, query
system, as well as the actual data stored in
the database. sequence A database structure used to
generate unique integers to be used as
record One row fetched by a SELECT primary keys (which are guaranteed to be
statement. unique). Concurrent database users can
use a sequence simultaneously.
relational operator A symbol used in
Sequences may be defined with many
search criteria to indicate a comparison
characteristics (for example, to ascend or
between two values, such as the equal
descend, have any increment or
sign in “WHERE DEPTNO = 10.” Rows
decrement, and to recycle values or not).
in which the comparison results in
“TRUE” are returned in the result session The period between invoking
(fetched), while rows in which the and quitting the executable.
comparison returns “FALSE” are source PL/SQL statements provided in
rejected from the result. a subprogram or package. You must have
replace mode A mode in which each the source code for a program unit before
character you enter replaces the current you can compile it into executable form.
character at the cursor. The opposite of specification Defines only the names,
insert mode. parameters, and return type (applies to
functions only) of the subprogram.
roles Named groups of related
privileges that are granted to users or split bar A small rectangle at the bottom
other roles. of the vertical scroll bar and to the left of

GlossaryĆ9
the horizontal scroll bar in an editor. stored subprogram A procedure or
Dragging and releasing the mouse button function that resides and executes in the
creates a pane, creates a new split bar at Oracle7 Server. Procedure Builder can
that location, and divides the scroll bar call stored subprograms.
into separate scroll bars for each pane. See
subprogram A PL/SQL procedure or
also: pane, scroll bar.
function. See also: program unit
SQL Standard interface for storing and subquery A query that is nested in a
retrieving information in a relational clause of a SQL command.
database. SQL is an acronym for
Structured Query Language. substitution parameter A
two-character variable of type CHAR
SQL buffer In SQL*Plus, the default that is referenced in a menu item
buffer used to contain the SQL command command or in a PL/SQL program unit,
or PL/SQL block most recently entered. and substituted with a value at runtime.
SQL*Plus An interactive SQL-based synonym An alias for a table, view,
language for data manipulation, data sequence, or program unit; a synonym is
definition and the definition of access not actually an object itself, it is a direct
rights for an Oracle database. Often used reference to its base object. Synonyms are
as an end-user reporting tool. used to mask the real name and owner of
an object, provide public access to an
SQL script A file containing SQL object, provide location transparency for
statements that you can run to perform tables, views, or program units of a
database administration quickly and remote database, and simplify the SQL
easily. Several SQL scripts are shipped statements for database users. A synonym
with Oracle products. can be public or private.
SQL statement A SQL instruction to syntax The orderly system by which
Oracle. A SELECT statement is one type commands, qualifiers, and parameters are
of SQL statement. See also: SELECT combined to form valid command
statement, query strings.
stack See call stack.
statement A PL/SQL construct used for T
conditional, iterative, and sequential table A named collection of related
control, and for error handling. A information, stored in a relational
semi-colon (;) must terminate every database or server, in a two-dimensional
PL/SQL statement. grid that is made up of rows and columns.
stored program unit A procedure, toggle A setting that can be turned either
function, or package that resides and on or off. For example, you can hide or
executes in the Oracle7 Server. show the Object Navigator.

GlossaryĆ10
tool An icon that appears in the Layout (alphanumeric) data. In Oracle RDBMS
editor or Object Navigator. Tools are used V6, CHAR and VARCHAR are
to create and manipulate objects in an equivalent. In Oracle7, CHAR data is
application. fixed-length and VARCHAR is
variable-length.
toolbar Collection of iconic buttons that
perform product commands. Usually variable A named object that can be
aligned horizontally along the top, or assigned a value and whose assigned
vertically down the side of a window. value may change over time. See also:
parameter, bind variable, global
transaction A sequence of SQL
variable, local variable
statements treated as a single unit.
view A virtual table whose rows do not
trigger A PL/SQL procedure that is
actually exist in the database, but which is
executed, or “fired,” at upon a specific
based on a table that is physically stored
event.
in the database.

U
W
update To change the values for table
data, in particular, by altering data values wildcard A character used to mean “any
using the SQL command UPDATE, but one character” or “a contiguous set of
also by deleting values using the SQL characters” within a word or phase.
command DELETE or by inserting window A rectangular area of the
values using the command INSERT. desktop that contains an application.
user-named parameter A type of Each window has an area where you can
substitution parameter that is created in interact with the application. Windows
the Forms designer (valid for a given can be opened, resized, moved, reduced
menu module). to an icon, or enlarged to fill the entire
desktop.

V
VARCHAR2 datatype Equivalent to the
XYZ
CHAR datatype, a standard Oracle zoom To expand an object to allow more
datatype used to store character room for editing the contents of the field.

GlossaryĆ11
GlossaryĆ12
Index
Symbols application partitioning, 19Ć11
argument, 20Ć11
;. See semicolon IN, 20Ć13, 22Ć19
:. See colon arithmetic expressions, 1Ć13
:=. See assignment operator arithmetic operators, 1Ć13, 3Ć25
". See quotation marks ASC, 2Ć5
`'. See quotation marks assignment operator, 21Ć7, 21Ć29, 22Ć21
(+). See outer join operator asterisk (*), 1Ć9, 8Ć33
&. See ampersand attribute, 8Ć15
#. See unique identifier %FOUND, 24Ć17
-. See dash %ISOPEN, 24Ć17, 24Ć19
%NOTFOUND, 24Ć17
*. See asterisk %ROWCOUNT, 24Ć17, 24Ć19
||. See concatenation operator %ROWTYPE, 21Ć23
%TYPE, 21Ć13, 22Ć9
cursor, 24Ć25
A definition, 8Ć13
explicit cursor, 24Ć17
ACCEPT command, 7Ć15, 11Ć17
active set, 24Ć11, 24Ć13, 24Ć15
B
alias
column, 1Ć21, 2Ć7, 14Ć11 B*Tree. See index
table, 4Ć13 BINARY_INTEGER, 21Ć15
ALTER SEQUENCE command, 13Ć17 block, 18Ć9
ALTER TABLE command, 12Ć7 Boolean condition, 23Ć7, 23Ć13
ADD clause, 12Ć7
add columns, 12Ć7 breakpoint, 19Ć37, 19Ć39, 19Ć41
ADD constraint clause, 12Ć11 setting, 19Ć37
DEFAULT keyword, 12Ć7 BTITLE command, CĆ17
DISABLE clause, 12Ć15
DROP constraint clause, 12Ć11 built-in package, 19Ć19
ENABLE clause, 12Ć15 button
MODIFY clause, 12Ć9 Go, 19Ć39
modify columns, 12Ć9 reset, 19Ć39
NOT NULL constraint, 12Ć7 Step Into, 19Ć39
ALTER USER command, password, 16Ć13 Step Out, 19Ć39
Step Over, 19Ć39
alternate key, 8Ć25 Vertical Button Bar, 19Ć21
ampersand (&), 7Ć9, 11Ć17, 20Ć21
single, 7Ć9
anonymous block, 18Ć11, 18Ć13
C concatenation operator, 1Ć23
condition, 23Ć25
Call Stack, 19Ć43
conditional construct. See IF statement
candidate key, 8Ć25
CONSTANT keyword, 21Ć7
Cartesian Product, 4Ć7
constraint. See CHECK constraint;
character function, 3Ć9 FOREIGN KEY constraint; NOT NULL
character pattern matching, 2Ć21 constraint; PRIMARY KEY constraint;
UNIQUE constraint
CHECK constraint, 8Ć23, 9Ć15, 9Ć23
constraints, 9Ć15
code column, 9Ć17
breakpoint, 19Ć41 data integrity, 8Ć23
commenting, 21Ć43 column, 8Ć23
conventions, 21Ć45 entity, 8Ć23
debugging, 19Ć37, 21Ć43, 25Ć11 referential, 8Ć23
naming, 21Ć45 user-defined, 8Ć23
stepping through, 19Ć39 table, 9Ć17
testing, 19Ć37, 19Ć43
control structure, 18Ć5, 23Ć5
colon (:), 21Ć41 IF statement, syntax, 23Ć7
column, IĆ11 loop, 23Ć17
column alias, 1Ć21, 2Ć7, 14Ć11 conversion function, 3Ć33
See also column heading COUNT function, 5Ć11
COLUMN command, 1Ć45 CREATE FUNCTION command, 20Ć7
format model elements, 1Ć49 RETURN statement, 20Ć17
column constraint, 9Ć17 CREATE INDEX command, 15Ć13
CHECK, 9Ć23
FOREIGN KEY, 9Ć21 CREATE PROCEDURE command, 20Ć7
NOT NULL, 9Ć19 CREATE SEQUENCE command, 13Ć7
PRIMARY KEY, 9Ć21
UNIQUE, 9Ć19 CREATE SYNONYM command, 16Ć25

column heading, 1Ć11 CREATE TABLE command, 9Ć7, 9Ć25


subquery, 9Ć31
command file, CĆ15
CREATE USER command, 16Ć7
comment, 21Ć43
delimiter, 21Ć25 CREATE VIEW command, 14Ć7
WITH CHECK OPTION clause, 14Ć17
COMMENT command, 12Ć21 WITH READ ONLY option, 14Ć19
COMMIT command, 24Ć27 Cue Cards, 19Ć13
COMMIT statement, 11Ć37, 11Ć41, 22Ć27 CURRVAL, 9Ć9, 13Ć13
comparison operator. See operator cursor, 22Ć23, 24Ć5
compile, 19Ć31, 20Ć7 attribute, 24Ć25
steps, 19Ć29 explicit, 22Ć7, 22Ć15, 24Ć5, 24Ć7, 24Ć21
attributes, 24Ć17
composite primary key, 8Ć25 closing, 24Ć15
compound primary key, 8Ć25 CURSOR statement, 24Ć9
declaring, 24Ć9 data manipulation language (DML), IĆ25,
FETCH statement, 24Ć13 11Ć5, 11Ć35, 22Ć5, 22Ć23
fetching, syntax, 24Ć13 DELETE statement, 11Ć29
FOR UPDATE clause, 24Ć27 INSERT command, 11Ć7
opening, 24Ć11, 24Ć23 UPDATE statement, 11Ć21
WHERE CURRENT OF clause, 24Ć27 view, 14Ć15, 14Ć19
FOR loop, 24Ć25 database, IĆ9
implicit, 22Ć23, 24Ć5
database design, 8Ć5
cursor FOR loop. See cursor table instance chart, 8Ć29
CURSOR statement. See cursor database security, 16Ć5
Database Trigger editor, 19Ć5, 19Ć9
D datatype, 9Ć13, 21Ć9
BINARY_INTEGER, 21Ć15
dash (-), 11Ć17 composite, 21Ć15
data control language (DCL), IĆ25, 9Ć7, conversion, 21Ć39
11Ć35, 22Ć5 parameter, 24Ć23
ALTER USER command, 16Ć13 scalar, 21Ć9
CREATE ROLE command, 16Ć11
date format elements, 3Ć37
CREATE SYNONYM command, 16Ć25
CREATE USER command, 16Ć7 date function, 3Ć27
DROP SYNONYM command, 16Ć27 DBMS_SQL package, 22Ć5
GRANT command, 16Ć15
REVOKE command, 16Ć23 DCL. See data control language

data definition language (DDL), IĆ25, 9Ć7, DDL. See data definition language
11Ć35, 19Ć25 debug action, 19Ć33, 19Ć35, 19Ć37
ALTER TABLE command, 12Ć5
declarative section, 18Ć9, 21Ć5
COMMENT command, 12Ć5
CREATE TABLE command, 9Ć7 DEFAULT keyword, 9Ć7, 9Ć9, 12Ć7, 21Ć7
DROP TABLE command, 12Ć17 default value, 22Ć19
RENAME command, 12Ć5
TRUNCATE command, 12Ć5 DEFINE command, 7Ć15
data dictionary, 9Ć17, 9Ć33, 10Ć5 DELETE statement, 11Ć29, 22Ć19
DICT_COLUMNS, 10Ć9 DESC, 2Ć5
DICTIONARY, 10Ć9
DESCRIBE command, 1Ć39, 9Ć33, 10Ć13
privileges, 16Ć21
USER_CONS_COLUMNS, 10Ć15, 12Ć13 DISTINCT keyword, 1Ć31
USER_CONSTRAINTS, 10Ć13, 12Ć13 DML. See data definition language
USER_IND_COLUMNS, 15Ć17
USER_INDEXES, 15Ć17 DROP INDEX command, 15Ć19
USER_OBJECTS, 10Ć9, 13Ć11 DROP SEQUENCE command, 13Ć19
USER_SEQUENCES, 13Ć11
DROP SYNONYM command, 16Ć27
USER_VIEWS, 14Ć21
DROP TABLE command, 12Ć17
data integrity constraints, IĆ15, 8Ć23
CASCADE CONSTRAINTS option, 12Ć17
DROP VIEW command, 14Ć23
DUAL table, 3Ć23 footer. See BTITLE command
FOR UPDATE clause, 24Ć27
E foreign key, IĆ11, 8Ć27, 8Ć37
FOREIGN KEY constraint, 8Ć23, 9Ć15, 9Ć21,
empty string (`'), 11Ć9 9Ć31
entity, 8Ć15 ON DELETE CASCADE, 9Ć23
definition, 8Ć13 function, 3Ć5, 18Ć13, 20Ć5, 22Ć23
entity relationship model, 8Ć13, 8Ć29 character, 3Ć9
attribute, 8Ć13 CONCAT, 3Ć9
entity, 8Ć13 INITCAP, 3Ć9
normalization, 8Ć21 LENGTH, 3Ć9
relationship, 8Ć13 LOWER, 3Ć9
NVL, 3Ć9
equijoin, 4Ć11
SUBSTR, 3Ć9
error handling. See exception-handling UPPER, 3Ć9
section conversion, 3Ć33
exception, 18Ć9, 22Ć13, 22Ć15, 24Ć11, 25Ć5 See also date format elements
INVALID_CURSOR, 24Ć15, 25Ć11 TO_CHAR, 3Ć33, 3Ć35, 3Ć45
NO_DATA_FOUND, 22Ć15, 22Ć17, 25Ć5, TO_DATE, 3Ć33, 3Ć49
25Ć11 TO_NUMBER, 3Ć33, 3Ć49
non-predefined Oracle7 Server error, date, 3Ć27
25Ć7, 25Ć15 ADD_MONTHS, 3Ć27
predefined Oracle7 Server error, 25Ć7, LAST_DAY, 3Ć27
25Ć11 MONTHS_BETWEEN, 3Ć27
propagating, 25Ć5, 25Ć21 NEXT_DAY, 3Ć27
RAISE statement, 25Ć5, 25Ć17 ROUND, 3Ć27
SQLCODE, 25Ć19 TRUNC, 3Ć27
SQLERRM, 25Ć19 group, 5Ć5
TOO_MANY_ROWS, 22Ć15, 22Ć17, 25Ć11 AVG, 5Ć7
trapping, 25Ć5 COUNT, 5Ć7
syntax, 25Ć9 MAX, 5Ć7
user-defined, 25Ć7, 25Ć17 MIN, 5Ć7
WHEN OTHERS clause, 25Ć9, 25Ć19 STDDEV, 5Ć7
exception-handling section, 18Ć9, 20Ć5, SUM, 5Ć7
21Ć5, 25Ć5, 25Ć9 VARIANCE, 5Ć7
in SQL statements, 20Ć25
executable section, 18Ć9, 21Ć5, 25Ć5 invoking, 20Ć25
EXECUTE command, 20Ć21 multiple row, 3Ć5
nesting, 3Ć51
EXIT statement. See loop
number, 3Ć17
export, program unit, 19Ć29 MOD, 3Ć17
ROUND, 3Ć17
TRUNC, 3Ć17
F NVL, 1Ć29
single row, 3Ć5, 3Ć7
FETCH statement. See cursor SQL, 20Ć15
field, IĆ11 SQLCODE, 25Ć19
SQLERRM, 25Ć19 DROP INDEX command, 15Ć19
standalone, 20Ć23 guidelines, 15Ć15
syntax, 20Ć17 non-unique, 15Ć11
SYSDATE, 3Ć23, 3Ć25 optimization, 15Ć7
TO_DATE, 11Ć13 ROWID, 15Ć9
user-defined, 20Ć15 single column, 15Ć11
UNIQUE, 9Ć19, 9Ć21, 15Ć11
INSERT statement, 11Ć7, 22Ć19
G subquery, 11Ć19
Go button, 19Ć39 integration, 18Ć7
GRANT command, 16Ć9 Interpreter, 19Ć9, 19Ć23
object privileges, 16Ć15
Interpreter pane, 19Ć23, 19Ć25
PUBLIC keyword, 16Ć19
WITH GRANT OPTION clause, 16Ć19 INTO clause, 22Ć7, 22Ć9, 24Ć9, 24Ć13
GRANT ROLE command, 16Ć11 INVALID_CURSOR exception, 24Ć15
GROUP BY clause, 5Ć13, 5Ć19, 5Ć23
group function, 5Ć5 J
subquery, 6Ć13
join
Cartesian Product, 4Ć7
H equijoin, 4Ć11
non-equijoin, 4Ć19
HAVING clause, 5Ć21, 5Ć25 outer, 4Ć21
group function, 5Ć25 self join, 4Ć25
header. See TTITLE command simple, 4Ć9
table alias, 4Ć17
help table prefix, 4Ć13
Cue Cards, 19Ć13 WHERE clause, 4Ć9
online, 19Ć9
Quick Tour, 19Ć11 join condition, 4Ć5

I L

identifier, 18Ć5, 20Ć23, 21Ć7, 21Ć25, 22Ć9, lexical unit, 21Ć25


22Ć21, 25Ć5 library, 19Ć19, 19Ć21
IF statement, 23Ć5 attached, 19Ć19
nested, 23Ć11 LIKE operator, 2Ć21
syntax. See control structure
literal, 1Ć25, 21Ć25
IN mode, 20Ć11
logical condition, 23Ć13
IN OUT mode, 20Ć11, 20Ć19
login.sql file, 7Ć19, CĆ11
index, 15Ć5
loop, 23Ć17
B*Tree, 15Ć5, 15Ć9
basic, 23Ć5
concatenated, 15Ć11
syntax, 23Ć17
CREATE INDEX command, 15Ć13
cursor FOR, 24Ć25
EXIT statement, 23Ć5, 23Ć17 O
FOR, 23Ć5
syntax, 23Ć21 Object Navigator, 19Ć5, 19Ć9, 19Ć15, 19Ć27,
labels, 23Ć27 19Ć37
nested, 23Ć27 ON DELETE CASCADE. See FOREIGN KEY
WHILE, 23Ć5 constraint
syntax, 23Ć25
with cursors, 24Ć17, 24Ć19 OPEN cursor. See cursor

looping constructs, 23Ć5 operator, 21Ć35


AND, 2Ć27
BETWEEN, 2Ć19
M comparison, 2Ć11, 2Ć15
IN, 2Ć19
mode IS NULL, 2Ć25
IN, 20Ć11 LIKE, 2Ć21
IN OUT, 20Ć11 %, 2Ć21
OUT, 20Ć11 _, 2Ć21
ESCAPE option, 2Ć23
model. See entity relationship model
logical, 2Ć15, 23Ć13
modularity, 18Ć5 OR, 2Ć27
multiple row subquery, 6Ć17 SQL, 2Ć15
operator precedence, 1Ć17

N Oracle7 Server, IĆ19


ORDER BY clause, 2Ć5
naming guidelines, 9Ć11 See also SELECT statement
naming rules, 9Ć11 OUT mode, 20Ć11, 20Ć19
nested block, 21Ć27 outer join, 4Ć21
nesting functions. See function outer join operator ((+)), 4Ć21
NEXTVAL, 9Ć9, 13Ć13
NO_DATA_FOUND exception. See P
exception
node, 19Ć21 package, 18Ć11, 20Ć5
normalization, 8Ć21 parameter, 7Ć21, 24Ć23, 24Ć25
actual, 20Ć11, 20Ć21
NOT NULL constraint, 1Ć27, 8Ć25, 8Ć33, formal, 20Ć11
9Ć15, 9Ć19, 9Ć31, 9Ć33, 12Ć7 local, 19Ć43
NOT NULL keyword, 21Ć7, 21Ć13 modes, 20Ć11
NULL keyword, 11Ć9 substitution, 20Ć21
syntax, 20Ć9
null value, IĆ11, 1Ć27, 2Ć25, 8Ć27, 21Ć7
password, 16Ć13
number function, 3Ć17
PL/SQL, IĆ19, IĆ23, 18Ć5, 18Ć15
NVL function, 1Ć29
PL/SQL block, nesting, 21Ć27
PL/SQL Interpreter. See Interpreter
PL/SQL record, 21Ć19, 22Ć7, 22Ć11, 24Ć21, R
24Ć25
declaring, 21Ć21 RAISE statement. See exception
syntax, 21Ć21
recursive relationship, 8Ć17, 8Ć19
PL/SQL table, 21Ć15
referential integrity constraint. See
declaring, 21Ć17 FOREIGN KEY constraint
syntax, 21Ć17
relational database, IĆ9
portability, 18Ć7
relationship, 8Ć17
pragma EXCEPTION_INIT, 25Ć15 definition, 8Ć13
precedence, 2Ć29 many-to-many, 8Ć19
primary key, IĆ11, 8Ć25, 8Ć27 many-to-one, 8Ć19, 8Ć37
one-to-one, 8Ć19, 8Ć37
PRIMARY KEY constraint, 1Ć27, 8Ć23, 9Ć15, recursive, 8Ć17
9Ć21, 12Ć15
index, 15Ć5 RENAME command, 12Ć19

PRIMARY KEY index, 12Ć15 Reset button, 19Ć39

privilege, 9Ć7, 10Ć5, 16Ć5 RETURN statement, 20Ć17


object, 16Ć5 REVOKE command, 16Ć23
system, 16Ć5
role, 16Ć5, 16Ć11
procedure, 18Ć13, 20Ć5
ROLLBACK statement, 11Ć37, 11Ć43, 22Ć27
syntax, 20Ć9
row, IĆ11
Procedure Builder, 18Ć17, 19Ć5, 20Ć7,
22Ć27, 25Ć11, 25Ć21 ROWID, 15Ć9, 24Ć21, 24Ć27
program construct, 18Ć11
program unit, 19Ć5, 19Ć19, 19Ć29, 20Ć5 S
Program Unit editor, 19Ć5, 19Ć9, 19Ć27
SAVEPOINT statement, 11Ć37, 11Ć45, 22Ć29
pseudocolumn
schema, 9Ć9
CURRVAL, 9Ć23
LEVEL, 9Ć23 scope, 21Ć27
NEXTVAL, 9Ć23 script file, 7Ć21, 9Ć25, CĆ15, CĆ19
ROWNUM, 9Ć23
search, 19Ć21
PUBLIC keyword, 16Ć19
security, 16Ć5
role, 16Ć5
Q SELECT command. See SELECT statement
Quick Tour, 19Ć11 SELECT statement, 11Ć11, 24Ć5
basic query, 1Ć5
quotation marks FROM clause, 1Ć9
double, 1Ć21, 21Ć25 GROUP BY clause, 5Ć13
single, 1Ć25, 2Ć13, 7Ć11, 7Ć17, 11Ć7, guidelines, 1Ć7
11Ć15, 21Ć25, 21Ć31 HAVING clause, 5Ć25
INTO clause, 22Ć7
ORDER BY clause, 2Ć5
outer join, 4Ć21 stack, 19Ć19
rules, 1Ć7 Stack node, 19Ć11, 19Ć43
SELECT clause, 1Ć9, 22Ć9
simple join, 4Ć9 statement level rollback, 11Ć47
syntax, 22Ć7 Step Into button, 19Ć39
WHERE clause, 2Ć11
Step Out button, 19Ć39
self join, 4Ć25
Step Over button, 19Ć39
semicolon (;), 22Ć7
stored function, 18Ć11
sequence, 20Ć13, 22Ć19
ALTER SEQUENCE command, 13Ć17 stored procedure, 18Ć11
cache, 13Ć15 stored program unit, 19Ć33
CREATE SEQUENCE command, 13Ć7 Stored Program Unit editor, 19Ć5, 19Ć9,
DROP SEQUENCE command, 13Ć19 19Ć31
gaps, 13Ć15
stored subprograms, 20Ć5
SET command, CĆ11
subprogram, 18Ć13, 19Ć7
SET VERIFY command, 7Ć9 See also function; procedure
simple join, 4Ć9 application, 20Ć5
creating, 20Ć7
sort order. See ORDER BY clause
invoking, 20Ć21
Source pane, 19Ć23
subquery, 14Ć7
SQL, 18Ć5, CĆ9 CREATE TABLE, 9Ć31
SQL buffer, 1Ć7, 1Ć41 HAVING clause, 6Ć19
INSERT statement, 11Ć19
SQL command, IĆ13, IĆ23, 1Ć35 multiple row, 6Ć17
SQL cursor attributes, 22Ć23 single row, 6Ć11
SQL%FOUND, 22Ć23 UPDATE statement, 11Ć21
SQL%ISOPEN, 22Ć23 WHERE clause, 6Ć19
SQL%NOTFOUND, 22Ć23 substitution variable, 11Ć15
SQL%ROWCOUNT, 22Ć23
syntax, rules, 21Ć25
SQL function, 20Ć15, 21Ć37
conversion, 21Ć39 SYSDATE, 9Ć9, 9Ć23, 11Ć11
SYSDATE, 3Ć23, 3Ć25, 20Ć13, 22Ć19 See also SQL function
USER, 20Ć13, 22Ć19 system development cycle, IĆ17, 8Ć7
SQL statement, 22Ć5 system privilege, 16Ć7
SQL*Plus, IĆ23, 1Ć35, 20Ć7, 20Ć21, 25Ć21,
CĆ9
editing commands, 1Ć41 T
file commands, 1Ć43
format commands, CĆ15 table, IĆ11, 1Ć5
parameter, 7Ć21 ALTER TABLE command, 12Ć5
SET command, CĆ11 CREATE SYNONYM command, 16Ć25
CREATE TABLE command, 9Ć7
SQLCODE function, 25Ć19 DROP TABLE command, 12Ć17
SQLERRM function, 25Ć19 properties, IĆ13
table alias, 4Ć17
table constraint, 9Ć17 V
CHECK, 9Ć23
FOREIGN KEY, 9Ć21 variable, 21Ć5, 24Ć9
PRIMARY KEY, 9Ć21 bind, 20Ć21
UNIQUE, 9Ć19 host, 21Ć41, 24Ć23
table instance chart, 8Ć29, 8Ć33, 9Ć25 input, 24Ć11
local, 19Ć43
table prefix, 4Ć13 scalar, 21Ć9
tables, 9Ć5 Vertical Button Bar, 19Ć21
TEXT_IO package, 20Ć23 view, 14Ć5
TO_CHAR, 3Ć35, 3Ć45 complex, 14Ć9, 14Ć13
CREATE VIEW command, 14Ć7
TO_DATE, 3Ć49 DROP VIEW command, 14Ć23
TO_DATE function, 11Ć13 simple, 14Ć9
TO_NUMBER, 3Ć49
TOO_MANY_ROWS exception. See W
exception
transaction, 11Ć5, 11Ć35, 24Ć27 WHEN OTHERS clause. See exception

transaction control, 22Ć27 WHERE clause, 2Ć11, 5Ć21, 22Ć7, 22Ć13,


22Ć21
TRUNCATE TABLE command, 12Ć19 See also join
TTITLE command, CĆ17 DELETE statement, 11Ć29
UPDATE statement, 11Ć25
WHERE CURRENT OF clause, 24Ć27
U
wildcard search, 2Ć21
UID, 9Ć23
See also unique identifier
UNDEFINE command, 7Ć19
UNIQUE constraint, 8Ć25, 9Ć15, 9Ć19, 12Ć15
index, 15Ć5
unique identifier, 8Ć15, 8Ć19, 8Ć35
number symbol (#), 8Ć15, 8Ć35
UNIQUE index, 9Ć19, 9Ć21, 12Ć15
unique key, 8Ć25, 8Ć27
UPDATE statement, 11Ć21, 22Ć19, 22Ć21
USER, 9Ć9, 9Ć23
USERENV, 9Ć23
USERID, 11Ć11

Potrebbero piacerti anche