Beruflich Dokumente
Kultur Dokumente
Edition 1.1
M03992
T1001E11
Authors Copyright EĂOracle Corporation, 1992, 1996. All rights reserved.
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.
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.
4. Show the structure of the S_CUSTOMER table. Using this table, perform the
following actions:
SQL> SELECT *
2 FROM s_customer;
Continued
4.—continued
b. Display the name and phone number for each 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
4.—continued
c. Display the phone number and name for each customer, with phone number
appearing first.
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.
SQL> SELECT *
2 FROM s_emp
3 WHERE salary*12 = 9600;
4. There are four coding errors in this statement. Can you identify them?
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
Continued
5.—continued
d. Retrieve p2q5 into the SQL buffer. Order the query results in descending
order by customer number. Run your query.
6.—continued
a. Display the user name for employee 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.
Employees DEPT_ID
------------------------------------ ---------
Mark Quick-To-See 10
Audry Ropeburn 50
Carmen Velasquez 50
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.
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.
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.
LAST_NAME SALARY
------------------------- ---------
Smith 940
Patel 795
Newman 750
Markarian 850
Chang 800
Patel 795
Dancs 860
7 rows selected.
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.
c. Display the last name and start date of every employee who was hired in
1991.
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.
FIRST_NAME LAST_NAME
------------------------- -------------------------
Carmen Velasquez
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
8.—continued
b. Display all product names and short descriptions for all descriptions
containing the word bicycle.
" Results have been formatted.
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.
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.
4. Display the employee number, last name, and salary increased by 15% and
expressed as a whole number.
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.
5. Display the employee last name and title in parentheses for all employees. The
report should look like the output below.
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.
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.
Continued
6.—continued
25 rows selected.
7. Display the product name for products that have “ski” in the name.
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.
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.
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.
25 rows selected.
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.
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.
Continued
1.—continued
25 rows selected.
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.
LAST_NAME NAME
------------ ----------------------
Smith Operations
4. Display the product name, product number, and quantity ordered of all items in
order number 101. Label the quantity column ORDERED.
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.
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.
Continued
6.—continued
18 rows selected.
7. Display all employees by last name name and employee number along with their
manager’s last name and manager number.
Continued
7.—continued
24 rows selected.
8. Modify the solution to exercise 7 to also display Velasquez, who has no manager.
25 rows selected.
9. Display all customers and the product number and quantities they ordered for
those customers whose order totaled more than 100,000.
Continued
9.—continued
26 rows selected.
Highest Lowest
---------- ----------
1020935 377
3. Write a query to display the minimum and maximum salary for each job type
ordered alphabetically.
Continued
3.—continued
8 rows selected.
Number of Managers
------------------
8
5. Display the number of line items in each order under each order number, labeled
Number of Items.
Continued
5.—continued
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.
Continued
6.—continued
DIFFERENCE
----------
1750
8 rows selected.
9. Retrieve the region number, region name, and the number of departments within
each region.
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.
9 rows selected.
11. Display the customer name and the number of orders for each customer.
13 rows selected.
3. Display the employee number, first name, last name, and user name for all
employees with salaries above the average salary.
13 rows selected.
4. Display last name, department number, and title for all employees assigned to
region 1 or region 2.
13 rows selected.
5. Display the last name and salary for all employees that report to LaDoris Ngao.
LAST_NAME SALARY
------------------------- ---------
Urguhart 1200
Menchu 1250
Biri 1100
Catchpole 1300
Havel 1307
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”.
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.
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.
6 rows selected.
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.
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.
9. Display the customer name and credit rating for all customers of sales
representative Andre Dumas.
NAME CREDIT_RA
------------------------ ---------
Kam’s Sporting Goods EXCELLENT
Sportique EXCELLENT
Muench Sports GOOD
Kuhn’s Sports EXCELLENT
Sporta Russia POOR
10. Display each sales representative’s last name in region 1 and region 2, their
customers’ names and each customer’s total sales orders.
6 rows selected.
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.
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.
" 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.
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.
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.
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.
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.
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
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
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
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.
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
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.
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’);
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.
4.—continued
EMPLOYEE_ID_PK P
EMPLOYEE_DEPT_ID_FK R
DEPARTMENT_ID_PK
EMPLOYEE_DEPT_ID_NN C
DEPT_ID IS NOT NULL
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.
1b.—continued
EMPLOYEE_ID_PK P
EMPLOYEE_DEPT_ID_FK R
DEPARTMENT_ID_PK
1 row created.
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?
1 row created.
1d.—continued
1.—continued
f. Confirm your additions to the tables.
SQL> SELECT *
2 FROM department;
ID NAME
---------- -------------------------
10 Finance
SQL> SELECT *
2 FROM employee;
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.
1 row created.
1 row created.
1 row created.
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.
1 row created.
1 row created.
1 row created.
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;
SQL> COMMIT;
Commit complete.
SQL> SELECT *
2 FROM department
3 WHERE name = ’Human Resources’;
ID NAME
---- -------------------------
75 Human Resources
SQL> SELECT *
2 FROM employee
3 WHERE id = 202;
2.—continued
d. Attempt to delete department 54. What was the result and why?
SQL> SELECT *
2 FROM employee
3 WHERE last_name = ’Jones’;
2.—continued
" 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;
2.—continued
h. Commit all pending changes.
SQL> COMMIT;
Commit complete.
1 row created.
SQL> SELECT *
2 FROM department
3 WHERE id = 54;
ID NAME
---- -------------------------
54 Sales
3.—continued
d. Empty the entire EMPLOYEE table.
SQL> SELECT *
2 FROM employee;
no rows selected
f. Discard the most recent DELETE operation without discarding the most
recent INSERT operation.
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
3g.—continued
SQL> SELECT *
2 FROM employee;
SQL> COMMIT;
Commit complete.
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.
" Your constraint names may be different from those listed here because they
are system generated.
3. Compare these constraints to those in the EMPLOYEE table. Note the types and
names of the constraints.
4. Add a table level PRIMARY KEY constraint to the WORKER table using the ID
column. The constraint should be immediately enabled.
5.—continued
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.
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
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.
7. Drop the EMPLOYEE table, while leaving the WORKER table in the database.
TABLE_NAME COMMENTS
--------------- ------------------------------
DEPARTMENT Departmental Listing
WORKER Employee Information
TABLE_NAME COMMENTS
--------------- ------------------------------
DEPARTMENT Departmental Listing
WORKER Employee Information
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.
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.
4.—continued
1 row created.
1 row created.
SQL> SELECT *
2 FROM department;
ID NAME
––– -------------------------
10 Finance
37 Marketing
76 Education
75 Human Resources
54 Sales
77 Administration
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.
1 row created.
1 row created.
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;
1 row created.
1 row created.
1 row created.
8.—continued
10. Add the Research department by using your script named p13q4.sql. Make this
addition permanent.
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.
11.—continued
SQL> SELECT *
2 FROM worker;
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
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.
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.
2.—continued
SQL> SELECT *
2 FROM mns_vu;
ID FULL_NAME NAME
--------- ------------------------ -------------
200 Donna Smith Marketing
203 Rey Guiliani Marketing
2.—continued
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> SELECT *
2 FROM emp_vu;
ID EMPLOYEE DEPT_ID
--------- ------------------------- -------------
200 Smith 37
203 Guiliani 37
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?
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.
VIEW_NAME
------------------------------
EMP_VU
MNS_VU
5.—continued
SQL> SELECT *
2 FROM s_emp
3 WHERE last_name = ’Biri’;
2. Create a non-unique index on the foreign key column in the WORKER table.
3. Since users will frequently query on the employee last name, create a non-unique
index on that column in the WORKER table.
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.
4.—continued
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.
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.
8. Remove the index on the employee last name from the WORKER table.
" Where user1 is the name of team 1 and user2 is the name of team 2.
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> 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.
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.
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.
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.
SQL> SELECT *
2 FROM user_tab_privs_made;
12.—continued
" Team 2 executes the query.
SQL> SELECT *
2 FROM user_tab_privs_made;
SQL> SELECT *
2 FROM team2;
Error at line 1:
ORA-00942: table or view does not exist
SQL> SELECT *
2 FROM team1;
Error at line 1:
ORA-00942: table or view does not exist
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
1.—continued
b. Table name: TITLE
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
1b.—continued
1.—continued
c. Table name: TITLE_COPY
1.—continued
1.—continued
e. Table name: RESERVATION
2. Verify that the tables and constraints were created properly by checking the data
dictionary.
OBJECT_NAME
-------------------
RESERVATION
RENTAL
TITLE_COPY
TITLE
MEMBER
2.—continued
16 rows selected.
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.
b. Title number for the TITLE table, start with 92, no caching.
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.
4a.—continued
4a.—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
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.
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
4b.—continued
4b.—continued
4b.—continued
" Verify the additions.
SQL> SELECT *
2 FROM member
3 ORDER BY member_id;
4b.—continued
6 rows selected.
4.—continued
c. Add the following movie copies in the TITLE_COPY table:
4c.—continued
" Script p17q4c.sql contents.
4c.—continued
SQL> SELECT *
2 FROM title_copy
3 ORDER BY title_id, copy_id;
9 rows selected.
4.—continued
d. Add the following rentals to the RENTAL table:
4d.—continued
SQL> COMMIT;
Commit complete
SQL> SELECT *
2 FROM rental
3 ORDER BY title_id;
09-FEB-96 101 2
11-FEB-96 93
08-FEB-96 102 3
10-FEB-96 95
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> SELECT *
2 FROM title_avail
3 ORDER BY title, copy_id;
9 rows selected.
" Obtain the title number for use in the TITLE_COPY table.
TITLE_ID TITLE
---------- ---------------------
98 Interstellar Wars
" Insert a record for the copies into the TITLE_COPY table.
6a.—continued
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”.
TITLE_ID TITLE
---------- ---------------
97 Soda Gang
98 Interstellar
Wars
6b.—continued
SQL> COMMIT;
Commit complete.
SQL> SELECT *
2 FROM reservation;
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.
" Update the title copy information to show that the film is rented.
6c.—continued
" Confirm the rental information from the TITLE_AVAIL view.
SQL> SELECT *
2 FROM title_avail;
11 rows selected.
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
1 row updated.
7b.—continued
1 row updated.
1 row updated.
1 row updated.
1 row updated.
7b.—continued
1 row updated.
1 row updated.
SQL> COMMIT;
Commit complete.
7b.—continued
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.
7c.—continued
CONSTRAINT_NAME C SEARCH_CONDITION
--------------- - --------------------
R_CONSTRAINT_NA
---------------
TITLE_NN C TITLE IS NOT NULL
TITLE_ID_PK P
6 rows selected.
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.
8.—continued
Interstellar 10-FEB-96
Wars
***************** ---------------
Total Rentals 5
PL/SQL> count_loops(4);
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;
PROCEDURE my_message IS
BEGIN
TEXT_IO.PUT_LINE (’Hello World’);
END;
PL/SQL> my_message;
a. Header
b. Declarative
c. Executable
d. Exception handling
" 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;
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
DECLARE
v_id NUMBER (4);
a. Legal
DECLARE
v_x, v_y, v_z VARCHAR2(10);
DECLARE
v_birthdate DATE NOT NULL;
DECLARE
v_in_stock BOOLEAN := 1;
DECLARE
emp_record emp_record_type;
DECLARE
TYPE name_table_type IS TABLE OF VARCHAR2(20)
INDEX BY BINARY_INTEGER;
dept_name_table name_table_type;
f. Legal
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;
END;
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;
PL/SQL> multiplier(2,4);
4.5
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.
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.
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;
PL/SQL> SELECT *
+> FROM s_dept
+> WHERE name = ’Health’;
ID NAME REGION_ID
-------- ------------------------- ---------
51 Health
1 row selected.
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?
2.—continued
e. Display the department number, region number, and region name for the
updated department.
1 row selected.
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;
3.—continued
c. Test the procedure. What happens if you enter a department number that does
not exist?
" 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.
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.
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;
4.—continued
" Execute the procedure.
g. Verify the record has been added by viewing the employee’s number, userid,
and salary.
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;
1.—continued
Test the procedure.
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.
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;
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**
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;
3.—continued
" Test the procedure.
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.
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;
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.
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.
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.
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;
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.—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;
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.
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.
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.
g. Write an exception handler for the error to pass a message to the user that the
specified department number does not exist.
1.—continued
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;
1.—continued
" Execute the subprogram.
Your results should look like the list below. Results have been formatted to fit
the page.
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;
2.—continued
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;
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);
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;
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;
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;
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.’;
1e.—continued
Code has been formatted to fit page.
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);
1f.—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;
ORD_ID
ID
S_ITEM S_ORD
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
Note: The data on the pages to follow has been formatted. Use the provided table
descriptions for accurate column names.
Note: Table has been split into two parts to make it fit in the page.
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.
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.
Syntax
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.
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.
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.
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.
Example
Set the report header to display Salary centered on one line, and Report centered
below it.
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.
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.
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.
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
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
PRINT variable
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.
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.
Example
Display contents of the procedure 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;
Syntax
Syntax
Example
Enter a data definition language (DDL) statement at the command prompt to create
the B_TEST table.
SQL> SELECT *
2 FROM b_test;
COL1
---------
1
2
3
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.
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
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
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
d. Create a global variable named G_OUTPUT to hold a text string from the
argument V_OUTPUT.
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.
Client/Server
D Invoke DBA*Assist as a client SQL*Forms application and “manage” the target
database over a SQL*Net connection.
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.
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.
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.
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
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