0% found this document useful (0 votes)
11 views39 pages

SQL 31 69

Uploaded by

mai elsayed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views39 pages

SQL 31 69

Uploaded by

mai elsayed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Explicit Data Type Conversion Using the TO_CHAR Function with Dates

TO_NUMBER TO_DATE TO_CHAR(date, 'format_model')

The format model:


• Must be enclosed by single quotation marks
• Is case-sensitive
NUMBER CHARACTER DATE
• Can include any valid date format element
• Has an fm element to remove padded blanks or
suppress leading zeros
• Is separated from the date value by a comma
TO_CHAR TO_CHAR

3-30 Copyright © 2004, Oracle. All rights reserved. 3-32 Copyright © 2004, Oracle. All rights reserved.

Elements of the Date Format Model Elements of the Date Format Model

Element Result • Time elements format the time portion of the date:
YYYY Full year in numbers
HH24:MI:SS AM 15:45:32 PM
YEAR Year spelled out (in English)
MM Two-digit value for month • Add character strings by enclosing them in double
MONTH Full name of the month quotation marks:
MON Three-letter abbreviation of the month DD "of" MONTH 12 of OCTOBER
DY Three-letter abbreviation of the day of the
week • Number suffixes spell out numbers:
DAY Full name of the day of the week
ddspth fourteenth
DD Numeric day of the month

3-33 Copyright © 2004, Oracle. All rights reserved. 3-34 Copyright © 2004, Oracle. All rights reserved.

Using the TO_CHAR Function with Dates Using the TO_CHAR Function with Numbers

SELECT last_name, TO_CHAR(number, 'format_model') ddspth


TO_CHAR(hire_date, 'fmDD Month YYYY')
AS HIREDATE
These are some of the format elements that you can
FROM employees; use with the TO_CHAR function to display a number
value as a character:
Element Result
9 Represents a number
0 Forces a zero to be displayed
$ Places a floating dollar sign
… L Uses the floating local currency symbol
. Prints a decimal point
, Prints a comma as thousands indicator

3-35 Copyright © 2004, Oracle. All rights reserved. 3-36 Copyright © 2004, Oracle. All rights reserved.

Using the TO_CHAR Function with Numbers Using the TO_NUMBER and TO_DATE
Functions

SELECT TO_CHAR(salary, '$99,999.00') SALARY • Convert a character string to a number format


FROM employees using the TO_NUMBER function:
WHERE last_name = 'Ernst';
TO_NUMBER(char[, 'format_model'])

• Convert a character string to a date format using


the TO_DATE function:
TO_DATE(char[, 'format_model'])

• These functions have an fx modifier. This


modifier specifies the exact matching for the
character argument and date format model of a
TO_DATE function. 31
3-37 Copyright © 2004, Oracle. All rights reserved. 3-38 Copyright © 2004, Oracle. All rights reserved.
RR Date Format Example of RR Date Format

Current Year Specified Date RR Format YY Format To find employees hired prior to 1990, use the RR date
1995 27-OCT-95 1995 1995 format, which produces the same results whether the
1995 27-OCT-17 2017 1917
command is run in 1999 or now:
2001 27-OCT-17 2017 2017
2001 27-OCT-95 1995 2095 SELECT last_name, TO_CHAR(hire_date, 'DD-Mon-YYYY')
FROM employees
If the specified two-digit year is: WHERE hire_date < TO_DATE('01-Jan-90','DD-Mon-RR');

0–49 50–99
If two digits The return date is in The return date is in
of the 0–49 the current century the century before
current the current one
year are: The return date is in The return date is in
50–99 the century after the current century
the current one

3-40 Copyright © 2004, Oracle. All rights reserved. 3-41 Copyright © 2004, Oracle. All rights reserved.

Nesting Functions Nesting Functions

• Single-row functions can be nested to any level. SELECT last_name,


UPPER(CONCAT(SUBSTR (LAST_NAME, 1, 8), '_US'))
• Nested functions are evaluated from deepest level FROM employees
to the least deep level. WHERE department_id = 60;

F3(F2(F1(col,arg1),arg2),arg3)

Step 1 = Result 1
Step 2 = Result 2
Step 3 = Result 3

3-42 Copyright © 2004, Oracle. All rights reserved. 3-43 Copyright © 2004, Oracle. All rights reserved.

General Functions NVL Function

The following functions work with any data type and Converts a null value to an actual value:
pertain to using nulls: • Data types that can be used are date, character,
• NVL (expr1, expr2) and number.
• NVL2 (expr1, expr2, expr3) • Data types must match:
• NULLIF (expr1, expr2) – NVL(commission_pct,0)
• COALESCE (expr1, expr2, ..., exprn) – NVL(hire_date,'01-JAN-97')
– NVL(job_id,'No Job Yet')

3-44 Copyright © 2004, Oracle. All rights reserved. 3-45 Copyright © 2004, Oracle. All rights reserved.

Using the NVL Function Using the NVL2 Function

SELECT last_name, salary, NVL(commission_pct, 0), 1 SELECT last_name, salary, commission_pct, 1


(salary*12) + (salary*12*NVL(commission_pct, 0)) AN_SAL NVL2(commission_pct,
FROM employees;
2 'SAL+COMM', 'SAL') income 2
FROM employees WHERE department_id IN (50, 80);

1 2 1 2
32
3-46 Copyright © 2004, Oracle. All rights reserved. 3-47 Copyright © 2004, Oracle. All rights reserved.
Using the NULLIF Function Using the COALESCE Function
1
SELECT first_name, LENGTH(first_name) "expr1", • The advantage of the COALESCE function over the
last_name, LENGTH(last_name) "expr2", 2 NVL function is that the COALESCE function can
NULLIF(LENGTH(first_name), LENGTH(last_name)) result 3
FROM employees; take multiple alternate values.
• If the first expression is not null, the COALESCE
function returns that expression; otherwise, it
does a COALESCE of the remaining expressions.


1 2 3

3-48 Copyright © 2004, Oracle. All rights reserved. 3-49 Copyright © 2004, Oracle. All rights reserved.

Using the COALESCE Function Conditional Expressions

SELECT last_name, • Provide the use of IF-THEN-ELSE logic within a


COALESCE(manager_id,commission_pct, -1) comm SQL statement
FROM employees
ORDER BY commission_pct; • Use two methods:
– CASE expression
– DECODE function

3-50 Copyright © 2004, Oracle. All rights reserved. 3-51 Copyright © 2004, Oracle. All rights reserved.

CASE Expression Using the CASE Expression

Facilitates conditional inquiries by doing the work of Facilitates conditional inquiries by doing the work of
an IF-THEN-ELSE statement: an IF-THEN-ELSE statement:
SELECT last_name, job_id, salary,
CASE expr WHEN comparison_expr1 THEN return_expr1 CASE job_id WHEN 'IT_PROG' THEN 1.10*salary
[WHEN comparison_expr2 THEN return_expr2 WHEN 'ST_CLERK' THEN 1.15*salary
WHEN comparison_exprn THEN return_exprn WHEN 'SA_REP' THEN 1.20*salary
ELSE else_expr] ELSE salary END "REVISED_SALARY"
END FROM employees;

3-52 Copyright © 2004, Oracle. All rights reserved. 3-53 Copyright © 2004, Oracle. All rights reserved.

DECODE Function Using the DECODE Function

Facilitates conditional inquiries by doing the work of a SELECT last_name, job_id, salary,
CASE expression or an IF-THEN-ELSE statement: DECODE(job_id, 'IT_PROG', 1.10*salary,
'ST_CLERK', 1.15*salary,
DECODE(col|expression, search1, result1 'SA_REP', 1.20*salary,
[, search2, result2,...,] salary)
[, default]) REVISED_SALARY
FROM employees;

33
3-54 Copyright © 2004, Oracle. All rights reserved. 3-55 Copyright © 2004, Oracle. All rights reserved.
Using the DECODE Function Summary

Display the applicable tax rate for each employee in In this lesson, you should have learned how to:
department 80: • Perform calculations on data using functions
SELECT last_name, salary, • Modify individual data items using functions
DECODE (TRUNC(salary/2000, 0),
0, 0.00, • Manipulate output for groups of rows using
1, 0.09, functions
2, 0.20, • Alter date formats for display using functions
3, 0.30,
4, 0.40, • Convert column data types using functions
5, 0.42, • Use NVL functions
6, 0.44,
0.45) TAX_RATE • Use IF-THEN-ELSE logic
FROM employees
WHERE department_id = 80;

3-56 Copyright © 2004, Oracle. All rights reserved. 3-57 Copyright © 2004, Oracle. All rights reserved.

Practice 3: Overview of Part 2

This practice covers the following topics:


• Creating queries that require the use of numeric,
character, and date functions
Reporting Aggregated Data
• Using concatenation with functions
Using the Group Functions
• Writing case-insensitive queries to test the
usefulness of character functions
• Performing calculations of years and months of
service for an employee
• Determining the review date for an employee

3-58 Copyright © 2004, Oracle. All rights reserved. Copyright © 2004, Oracle. All rights reserved.

Objectives What Are Group Functions?

Group functions operate on sets of rows to give one


After completing this lesson, you should be able to do result per group.
the following: EMPLOYEES

• Identify the available group functions


• Describe the use of group functions
• Group data by using the GROUP BY clause
• Include or exclude grouped rows by using the Maximum salary in
HAVING clause EMPLOYEES table

4-2 Copyright © 2004, Oracle. All rights reserved. 4-3 Copyright © 2004, Oracle. All rights reserved.

Types of Group Functions Group Functions: Syntax

• AVG SELECT [column,] group_function(column), ...


FROM table
• COUNT
[WHERE condition]
• MAX [GROUP BY column]
Group [ORDER BY column];
• MIN functions
• STDDEV
• SUM
• VARIANCE

34
4-4 Copyright © 2004, Oracle. All rights reserved. 4-5 Copyright © 2004, Oracle. All rights reserved.
Using the AVG and SUM Functions Using the MIN and MAX Functions

You can use AVG and SUM for numeric data. You can use MIN and MAX for numeric, character, and
date data types.
SELECT AVG(salary), MAX(salary),
MIN(salary), SUM(salary) SELECT MIN(hire_date), MAX(hire_date)
FROM employees FROM employees;
WHERE job_id LIKE '%REP%';

4-6 Copyright © 2004, Oracle. All rights reserved. 4-7 Copyright © 2004, Oracle. All rights reserved.

Using the COUNT Function Using the DISTINCT Keyword

COUNT(*) returns the number of rows in a table: • COUNT(DISTINCT expr) returns the number of
SELECT COUNT(*) distinct non-null values of the expr.
1 FROM employees • To display the number of distinct department
WHERE department_id = 50;
values in the EMPLOYEES table:
SELECT COUNT(DISTINCT department_id)
FROM employees;
COUNT(expr) returns the number of rows with non-
null values for the expr:
SELECT COUNT(commission_pct)
2 FROM employees
WHERE department_id = 80;

4-8 Copyright © 2004, Oracle. All rights reserved. 4-9 Copyright © 2004, Oracle. All rights reserved.

Group Functions and Null Values Creating Groups of Data

Group functions ignore null values in the column: EMPLOYEES


SELECT AVG(commission_pct) 4400
1 FROM employees; 9500

3500 Average
salary in
The NVL function forces group functions to include EMPLOYEES
null values: 6400 table for each
SELECT AVG(NVL(commission_pct, 0)) department
2 FROM employees; 10033

4-10 Copyright © 2004, Oracle. All rights reserved. 4-11 Copyright © 2004, Oracle. All rights reserved.

Creating Groups of Data: Using the GROUP BY Clause


GROUP BY Clause Syntax

SELECT column, group_function(column) All columns in the SELECT list that are not in group
FROM table functions must be in the GROUP BY clause.
[WHERE condition]
[GROUP BY group_by_expression] SELECT department_id, AVG(salary)
[ORDER BY column]; FROM employees
GROUP BY department_id ;
You can divide rows in a table into smaller groups by
using the GROUP BY clause.

35
4-12 Copyright © 2004, Oracle. All rights reserved. 4-13 Copyright © 2004, Oracle. All rights reserved.
Using the GROUP BY Clause Grouping by More Than One Column

The GROUP BY column does not have to be in the EMPLOYEES


SELECT list.
SELECT AVG(salary)
FROM employees
GROUP BY department_id ;
Add the
salaries in
the EMPLOYEES
table for
each job,
grouped by
department

4-14 Copyright © 2004, Oracle. All rights reserved. 4-15 Copyright © 2004, Oracle. All rights reserved.

Using the GROUP BY Clause Illegal Queries


on Multiple Columns Using Group Functions

SELECT department_id dept_id, job_id, SUM(salary) Any column or expression in the SELECT list that is not
FROM employees an aggregate function must be in the GROUP BY clause:
GROUP BY department_id, job_id ;
SELECT department_id, COUNT(last_name)
FROM employees;

SELECT department_id, COUNT(last_name)


*
ERROR at line 1:
ORA-00937: not a single-group group function

4-16 Copyright © 2004, Oracle. All rights reserved. 4-17 Copyright © 2004, Oracle. All rights reserved.

Illegal Queries Restricting Group Results


Using Group Functions

• You cannot use the WHERE clause to restrict groups. EMPLOYEES


• You use the HAVING clause to restrict groups.
• You cannot use group functions in the WHERE clause.
SELECT department_id, AVG(salary)
FROM employees
WHERE AVG(salary) > 8000 The maximum
GROUP BY department_id; salary
per department
WHERE AVG(salary) > 8000 when it is
* greater than
ERROR at line 3: $10,000
ORA-00934: group function is not allowed here …
Cannot use the WHERE clause to restrict groups

4-18 Copyright © 2004, Oracle. All rights reserved. 4-19 Copyright © 2004, Oracle. All rights reserved.

Restricting Group Results Using the HAVING Clause


with the HAVING Clause

When you use the HAVING clause, the Oracle server SELECT department_id, MAX(salary)
restricts groups as follows: FROM employees
GROUP BY department_id
1. Rows are grouped. HAVING MAX(salary)>10000 ;
2. The group function is applied.
3. Groups matching the HAVING clause are
displayed.
SELECT column, group_function
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];
36
4-20 Copyright © 2004, Oracle. All rights reserved. 4-21 Copyright © 2004, Oracle. All rights reserved.
Using the HAVING Clause Nesting Group Functions

SELECT job_id, SUM(salary) PAYROLL Display the maximum average salary:


FROM employees
WHERE job_id NOT LIKE '%REP%' SELECT MAX(AVG(salary))
GROUP BY job_id FROM employees
HAVING SUM(salary) > 13000 GROUP BY department_id;
ORDER BY SUM(salary);

4-22 Copyright © 2004, Oracle. All rights reserved. 4-23 Copyright © 2004, Oracle. All rights reserved.

Summary Practice 4: Overview

In this lesson, you should have learned how to: This practice covers the following topics:
• Use the group functions COUNT, MAX, MIN, and AVG • Writing queries that use the group functions
• Write queries that use the GROUP BY clause • Grouping by rows to achieve more than one result
• Write queries that use the HAVING clause • Restricting groups by using the HAVING clause

SELECT column, group_function


FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];

4-24 Copyright © 2004, Oracle. All rights reserved. 4-25 Copyright © 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
• Write SELECT statements to access data from
Displaying Data more than one table using equijoins and non-
from Multiple Tables equijoins
• Join a table to itself by using a self-join
• View data that generally does not meet a join
condition by using outer joins
• Generate a Cartesian product of all rows from two
or more tables

Copyright © 2004, Oracle. All rights reserved. 5-2 Copyright © 2004, Oracle. All rights reserved.

Obtaining Data from Multiple Tables Types of Joins

EMPLOYEES DEPARTMENTS Joins that are compliant with the SQL:1999 standard
include the following:
• Cross joins

• Natural joins
• USING clause
• Full (or two-sided) outer joins
• Arbitrary join conditions for outer joins

37
5-3 Copyright © 2004, Oracle. All rights reserved. 5-4 Copyright © 2004, Oracle. All rights reserved.
Joining Tables Using SQL:1999 Syntax Creating Natural Joins

Use a join to query data from more than one table: • The NATURAL JOIN clause is based on all columns
in the two tables that have the same name.
SELECT table1.column, table2.column
FROM table1 • It selects rows from the two tables that have equal
[NATURAL JOIN table2] | values in all matched columns.
[JOIN table2 USING (column_name)] |
• If the columns having the same names have
[JOIN table2
ON (table1.column_name = table2.column_name)]| different data types, an error is returned.
[LEFT|RIGHT|FULL OUTER JOIN table2
ON (table1.column_name = table2.column_name)]|
[CROSS JOIN table2];

5-5 Copyright © 2004, Oracle. All rights reserved. 5-6 Copyright © 2004, Oracle. All rights reserved.

Retrieving Records with Natural Joins

SELECT department_id, department_name, Select empno,Ename,Dname,Deptno


location_id, city
FROM departments
From EMP,DEPT
NATURAL JOIN locations ; Where deptno=deptno;

Select e.empno,e.Ename,d.Dname,e.Deptno
From EMP e,DEPT d
Where e.deptno=d.deptno;

5-7 Copyright © 2004, Oracle. All rights reserved. 5-8 Copyright © 2004, Oracle. All rights reserved.

Creating Joins with the USING Clause Joining Column Names

• If several columns have the same names but the EMPLOYEES DEPARTMENTS
data types do not match, the NATURAL JOIN clause
can be modified with the USING clause to specify
the columns that should be used for an equijoin.
• Use the USING clause to match only one column
when more than one column matches.
• Do not use a table name or alias in the referenced
columns.
• The NATURAL JOIN and USING clauses are
mutually exclusive.
… …
Foreign key Primary key

5-9 Copyright © 2004, Oracle. All rights reserved. 5-10 Copyright © 2004, Oracle. All rights reserved.

Retrieving Records with the USING Clause Qualifying Ambiguous


Column Names

SELECT employees.employee_id, employees.last_name, • Use table prefixes to qualify column names that
departments.location_id, department_id are in multiple tables.
FROM employees JOIN departments
USING (department_id) ; • Use table prefixes to improve performance.
• Use column aliases to distinguish columns that
have identical names but reside in different tables.
• Do not use aliases on columns that are identified
in the USING clause and listed elsewhere in the
SQL statement.

38
5-11 Copyright © 2004, Oracle. All rights reserved. 5-12 Copyright © 2004, Oracle. All rights reserved.
Using Table Aliases Creating Joins with the ON Clause

• Use table aliases to simplify queries. • The join condition for the natural join is basically
• Use table aliases to improve performance. an equijoin of all columns with the same name.
• Use the ON clause to specify arbitrary conditions
SELECT e.employee_id, e.last_name,
d.location_id, department_id or specify columns to join.
FROM employees e JOIN departments d • The join condition is separated from other search
USING (department_id) ; conditions.
• The ON clause makes code easy to understand.

5-13 Copyright © 2004, Oracle. All rights reserved. 5-14 Copyright © 2004, Oracle. All rights reserved.

Retrieving Records with the ON Clause Self-Joins Using the ON Clause

SELECT e.employee_id, e.last_name, e.department_id, EMPLOYEES (WORKER) EMPLOYEES (MANAGER)


d.department_id, d.location_id
FROM employees e JOIN departments d
ON (e.department_id = d.department_id);

… …

MANAGER_ID in the WORKER table is equal to


EMPLOYEE_ID in the MANAGER table.

5-15 Copyright © 2004, Oracle. All rights reserved. 5-16 Copyright © 2004, Oracle. All rights reserved.

Self-Joins Using the ON Clause Applying Additional Conditions


to a Join

SELECT e.last_name emp, m.last_name mgr SELECT e.employee_id, e.last_name, e.department_id,


FROM employees e JOIN employees m d.department_id, d.location_id
ON (e.manager_id = m.employee_id); FROM employees e JOIN departments d
ON (e.department_id = d.department_id)
AND e.manager_id = 149 ;

5-17 Copyright © 2004, Oracle. All rights reserved. 5-18 Copyright © 2004, Oracle. All rights reserved.

Creating Three-Way Joins with the Non-Equijoins


ON Clause

SELECT employee_id, city, department_name EMPLOYEES JOB_GRADES


FROM employees e
JOIN departments d
ON d.department_id = e.department_id
JOIN locations l
ON d.location_id = l.location_id;

Salary in the EMPLOYEES


table must be between
… lowest salary and highest
… salary in the JOB_GRADES
table.
39
5-19 Copyright © 2004, Oracle. All rights reserved. 5-20 Copyright © 2004, Oracle. All rights reserved.
Retrieving Records Outer Joins
with Non-Equijoins

SELECT e.last_name, e.salary, j.grade_level DEPARTMENTS EMPLOYEES


FROM employees e JOIN job_grades j
ON e.salary
BETWEEN j.lowest_sal AND j.highest_sal;


… There are no employees in
department 190.

5-21 Copyright © 2004, Oracle. All rights reserved. 5-22 Copyright © 2004, Oracle. All rights reserved.

INNER Versus OUTER Joins LEFT OUTER JOIN

• In SQL:1999, the join of two tables returning only SELECT e.last_name, e.department_id, d.department_name
matched rows is called an inner join. FROM employees e LEFT OUTER JOIN departments d
ON (e.department_id = d.department_id) ;
• A join between two tables that returns the results
of the inner join as well as the unmatched rows
from the left (or right) tables is called a left (or
right) outer join. …
• A join between two tables that returns the results
of an inner join as well as the results of a left and
right join is a full outer join.

5-23 Copyright © 2004, Oracle. All rights reserved. 5-24 Copyright © 2004, Oracle. All rights reserved.

RIGHT OUTER JOIN FULL OUTER JOIN

SELECT e.last_name, e.department_id, d.department_name SELECT e.last_name, d.department_id, d.department_name


FROM employees e RIGHT OUTER JOIN departments d FROM employees e FULL OUTER JOIN departments d
ON (e.department_id = d.department_id) ; ON (e.department_id = d.department_id) ;


5-25 Copyright © 2004, Oracle. All rights reserved. 5-26 Copyright © 2004, Oracle. All rights reserved.

Cartesian Products Generating a Cartesian Product

• A Cartesian product is formed when: EMPLOYEES (20 rows) DEPARTMENTS (8 rows)


– A join condition is omitted
– A join condition is invalid

– All rows in the first table are joined to all rows in the
second table
• To avoid a Cartesian product, always include a
valid join condition.

Cartesian product:
20 x 8 = 160 rows

… 40
5-27 Copyright © 2004, Oracle. All rights reserved. 5-28 Copyright © 2004, Oracle. All rights reserved.
Creating Cross Joins Summary

• The CROSS JOIN clause produces the cross- In this lesson, you should have learned how to use
product of two tables. joins to display data from multiple tables by using:
• This is also called a Cartesian product between • Equijoins
the two tables. • Non-equijoins
SELECT last_name, department_name
• Outer joins
FROM employees • Self-joins
CROSS JOIN departments ;
• Cross joins
• Natural joins
• Full (or two-sided) outer joins

5-29 Copyright © 2004, Oracle. All rights reserved. 5-30 Copyright © 2004, Oracle. All rights reserved.

Practice 5: Overview

This practice covers the following topics:


• Joining tables using an equijoin
• Performing outer and self-joins Using Subqueries to Solve Queries
• Adding conditions

5-31 Copyright © 2004, Oracle. All rights reserved. Copyright © 2004, Oracle. All rights reserved.

Objectives Using a Subquery


to Solve a Problem

After completing this lesson, you should be able to do Who has a salary greater than Abel’s?
the following:
• Define subqueries Main query:

• Describe the types of problems that subqueries


can solve Which employees have salaries greater
than Abel’s salary?
• List the types of subqueries
• Write single-row and multiple-row subqueries Subquery:

What is Abel’s salary?

6-2 Copyright © 2004, Oracle. All rights reserved. 6-3 Copyright © 2004, Oracle. All rights reserved.

Subquery Syntax Using a Subquery

SELECT select_list SELECT last_name


FROM table FROM employees 11000
WHERE expr operator WHERE salary >
(SELECT select_list (SELECT salary
FROM table); FROM employees
WHERE last_name = 'Abel');
• The subquery (inner query) executes once before
the main query (outer query).
• The result of the subquery is used by the main
query.

41
6-4 Copyright © 2004, Oracle. All rights reserved. 6-5 Copyright © 2004, Oracle. All rights reserved.
Guidelines for Using Subqueries Types of Subqueries

• Enclose subqueries in parentheses. • Single-row subquery


• Place subqueries on the right side of the Main query
comparison condition. returns
Subquery ST_CLERK
• The ORDER BY clause in the subquery is not
needed unless you are performing Top-N analysis.
• Multiple-row subquery
• Use single-row operators with single-row
subqueries, and use multiple-row operators with Main query
multiple-row subqueries. returns ST_CLERK
Subquery
SA_MAN

6-6 Copyright © 2004, Oracle. All rights reserved. 6-7 Copyright © 2004, Oracle. All rights reserved.

Single-Row Subqueries Executing Single-Row Subqueries

• Return only one row SELECT last_name, job_id, salary


FROM employees
• Use single-row comparison operators ST_CLERK
WHERE job_id =
Operator Meaning (SELECT job_id
FROM employees
= Equal to WHERE employee_id = 141)
> Greater than AND salary > 2600
(SELECT salary
>= Greater than or equal to FROM employees
< Less than WHERE employee_id = 143);
<= Less than or equal to
<> Not equal to

6-8 Copyright © 2004, Oracle. All rights reserved. 6-9 Copyright © 2004, Oracle. All rights reserved.

Using Group Functions in a Subquery The HAVING Clause with Subqueries

SELECT last_name, job_id, salary • The Oracle server executes subqueries first.
FROM employees 2500
• The Oracle server returns results into the HAVING
WHERE salary =
(SELECT MIN(salary) clause of the main query.
FROM employees);
SELECT department_id, MIN(salary)
FROM employees
GROUP BY department_id 2500
HAVING MIN(salary) >
(SELECT MIN(salary)
FROM employees
WHERE department_id = 50);

6-10 Copyright © 2004, Oracle. All rights reserved. 6-11 Copyright © 2004, Oracle. All rights reserved.

What Is Wrong with This Statement? Will This Statement Return Rows?

SELECT employee_id, last_name SELECT last_name, job_id


FROM employees FROM employees
WHERE salary = WHERE job_id =
(SELECT MIN(salary) (SELECT job_id
FROM employees FROM employees
GROUP BY department_id); WHERE last_name = 'Haas');

no rows selected
ERROR at line 4:
ORA-01427: single-row subquery returns more than
one row Subquery returns no values.

Single-row operator with multiple-row subquery

42
6-12 Copyright © 2004, Oracle. All rights reserved. 6-13 Copyright © 2004, Oracle. All rights reserved.
Multiple-Row Subqueries Using the ANY Operator
in Multiple-Row Subqueries

• Return more than one row SELECT employee_id, last_name, job_id, salary
FROM employees

9000, 6000, 4200
Use multiple-row comparison operators
WHERE salary < ANY
(SELECT salary
Operator Meaning FROM employees
IN Equal to any member in the list WHERE job_id = 'IT_PROG')
AND job_id <> 'IT_PROG';
ANY (OR) Compare value to each value returned by the
subquery
ALL Compare value to every value returned by
the subquery

6-14 Copyright © 2004, Oracle. All rights reserved. 6-15 Copyright © 2004, Oracle. All rights reserved.

Using the ALL Operator Null Values in a Subquery


in Multiple-Row Subqueries

SELECT employee_id, last_name, job_id, salary SELECT emp.last_name


FROM employees 9000, 6000, 4200 FROM employees emp
WHERE salary < ALL WHERE emp.employee_id NOT IN
(SELECT salary (SELECT mgr.manager_id
FROM employees FROM employees mgr);
WHERE job_id = 'IT_PROG')
AND job_id <> 'IT_PROG'; no rows selected

6-16 Copyright © 2004, Oracle. All rights reserved. 6-17 Copyright © 2004, Oracle. All rights reserved.

Summary Practice 6: Overview

In this lesson, you should have learned how to: This practice covers the following topics:
• Identify when a subquery can help solve a • Creating subqueries to query values based on
question unknown criteria
• Write subqueries when a query is based on • Using subqueries to find out which values exist in
unknown values one set of data and not in another
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);

6-18 Copyright © 2004, Oracle. All rights reserved. 6-19 Copyright © 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do


the following:
• Describe set operators
Using the Set Operators
• Use a set operator to combine multiple queries
into a single query
• Control the order of rows returned

43
Copyright © 2004, Oracle. All rights reserved. 7-2 Copyright © 2004, Oracle. All rights reserved.
Set Operators Tables Used in This Lesson
A B A B

UNION/UNION ALL The tables used in this lesson are:


• EMPLOYEES: Provides details regarding all
current employees
A B
• JOB_HISTORY: Records the details of the start
date and end date of the former job, and the job
INTERSECT identification number and department when an
employee switches jobs

A B

MINUS

7-3 Copyright © 2004, Oracle. All rights reserved. 7-4 Copyright © 2004, Oracle. All rights reserved.

UNION Operator Using the UNION Operator

A B Display the current and previous job details of all


employees. Display each employee only once.
SELECT employee_id, job_id
FROM employees
UNION
SELECT employee_id, job_id
FROM job_history;



The UNION operator returns results from both
queries after eliminating duplications.

7-5 Copyright © 2004, Oracle. All rights reserved. 7-6 Copyright © 2004, Oracle. All rights reserved.

UNION ALL Operator Using the UNION ALL Operator

Display the current and previous departments of all


A B employees.
SELECT employee_id, job_id, department_id
FROM employees
UNION ALL
SELECT employee_id, job_id, department_id
FROM job_history
ORDER BY employee_id;

The UNION ALL operator returns results from both …


queries, including all duplications.

7-7 Copyright © 2004, Oracle. All rights reserved. 7-8 Copyright © 2004, Oracle. All rights reserved.

INTERSECT Operator Using the INTERSECT Operator


Display the employee IDs and job IDs of those
employees who currently have a job title that is the
A B
same as their job title when they were initially hired
(that is, they changed jobs but have now gone back to
doing their original job).
SELECT employee_id, job_id
FROM employees
INTERSECT
SELECT employee_id, job_id
FROM job_history;

The INTERSECT operator returns rows that are


common to both queries. 44
7-9 Copyright © 2004, Oracle. All rights reserved. 7-10 Copyright © 2004, Oracle. All rights reserved.
MINUS Operator MINUS Operator

A B Display the employee IDs of those employees who


have not changed their jobs even once.
SELECT employee_id,job_id
FROM employees
MINUS
SELECT employee_id,job_id
FROM job_history;


The MINUS operator returns rows in the first query
that are not present in the second query.

7-11 Copyright © 2004, Oracle. All rights reserved. 7-12 Copyright © 2004, Oracle. All rights reserved.

Set Operator Guidelines The Oracle Server and Set Operators

• The expressions in the SELECT lists must match in • Duplicate rows are automatically eliminated
number and data type. except in UNION ALL.
• Parentheses can be used to alter the sequence of • Column names from the first query appear in the
execution. result.
• The ORDER BY clause: • The output is sorted in ascending order by default
– Can appear only at the very end of the statement except in UNION ALL.
– Will accept the column name, aliases from the first
SELECT statement, or the positional notation

7-13 Copyright © 2004, Oracle. All rights reserved. 7-14 Copyright © 2004, Oracle. All rights reserved.

Matching the SELECT Statements Matching the SELECT Statement:


Example
Using the UNION operator, display the department ID,
location, and hire date for all employees. Using the UNION operator, display the employee ID, job
SELECT department_id, TO_NUMBER(null) ID, and salary of all employees.
location, hire_date
FROM employees SELECT employee_id, job_id,salary
UNION FROM employees
SELECT department_id, location_id, TO_DATE(null) UNION
FROM departments; SELECT employee_id, job_id,0
FROM job_history;


7-15 Copyright © 2004, Oracle. All rights reserved. 7-16 Copyright © 2004, Oracle. All rights reserved.

Controlling the Order of Rows Summary

Produce an English sentence using two UNION


operators. In this lesson, you should have learned how to:
• Use UNION to return all distinct rows
COLUMN a_dummy NOPRINT
SELECT 'sing' AS "My dream", 3 a_dummy • Use UNION ALL to return all rows, including
FROM dual duplicates
UNION
SELECT 'I''d like to teach', 1 a_dummy • Use INTERSECT to return all rows that are shared
FROM dual by both queries
UNION • Use MINUS to return all distinct rows that are
SELECT 'the world to', 2 a_dummy
FROM dual
selected by the first query but not by the second
ORDER BY a_dummy; • Use ORDER BY only at the very end of the
statement

45
7-17 Copyright © 2004, Oracle. All rights reserved. 7-18 Copyright © 2004, Oracle. All rights reserved.
Practice 7: Overview

In this practice, you use the set operators to create


reports:
• Using the UNION operator
• Using the INTERSECTION operator
• Using the MINUS operator

7-19 Copyright © 2004, Oracle. All rights reserved.

46
Enhanced Guide to Oracle 10g Forms
 Application with a graphical user
Chapter 5: interface that looks like a paper
form
Introduction To Form Builder
 Used to insert, update, delete and

Modified By: Dr. Bilal Hawashin


view database data
Department of Computer Information Systems
Alzaytoonah University of Jordan

1 2

Primary Form Uses Data Block Forms


 Viewing/retrieving records  Form associated with a specific
 Inserting/updating/deleting Oracle database table
records  System automatically creates:
 Text fields associated with table
fields
Performing operations on Form
 Programs for inserting, modifying,
Builder is easier than on SQL.
deleting, and viewing data records

3 4

Data Block Forms Steps of running the form


 ORACLE 10g forms are displayed  Design the form and write its code
on web browser as a web page. (.fmb file)
 They are displayed in Forms  Compile the form (.fmx file)
Services Window named When you run the form:
Window1.  OC4J Instance process converts
 The form specification is the compiled file into java applet
translated into Java Applet.  Java applet form starts on the
web browser
5 6

Important Shortcuts Form Modes


Layout Editor: F2  Normal
Object Navigator: F3  You can view records and sequentially step
Properties: Select item then F4 through records
PL_SQL Code: Select item then F11  Enter Query
Open: CTRL+O
 You can enter search parameters in form
Close: Select form then CTRL+W fields and then retrieve the associated
Connect: CTRL+J records
Save: CTRL+S  To place the form in Enter Query mode,
Compile: Select form then CTRL+T click the Enter Query button
47
7 8
Inserting New Records Retrieving Records
 In Normal mode, click the Insert Record  Click the Enter Query button to
button to insert a new blank record place the form in Enter Query mode
 Type the data values in the form fields  Type a search condition
 Click the Save button to save the  Click the Execute Query button to
values in the database retrieve selected records
 If you click , do not enter a search
condition, and then click , all table
records will be retrieved
9 10

Form Search Types Restricted Search Operators


 Exact search: only retrieves records  _: wildcard replacing a single character
that exactly match the entered search  %: wildcard replacing multiple
condition characters
 Restricted search: retrieves records  >, <: greater than, less than
that fall within a range of values  >=, <=: greater than or equal to, less
than or equal to
 <> or !=: not equal to

11 12

Scrolling Through Retrieved Updating and Deleting


Records Records
 To view the next record, click the Next  Retrieve the record to be updated
Record button or deleted
 To view the previous record, click the  To update, change the data value and
Previous Record button click the Save button
 To delete, click the Remove Record
button

13 14

Data Block Form File Types Form Components


 .fmb  Form module: form application
 Form design file, used by form  Form window
programmer in Form Builder  Title bar on top
 .fmx  Horizontal and vertical scrollbars
 Form executable file, run by form  Can be resized, maximized,
users minimized

48
15 16
Form Components Form Components
 Canvas Window
 Surface that displays form items Name Canvas
 Default Canvas type is Content Canvas.
 Other types are Tab Canvas, Stacked, … Cash Block of items
 Block
Check
Credit Card

 Object that contains form items


 Every canvas can have one or more blocks
 Every block is contained with one Frame.
 Form items
 Command buttons, radio (option) buttons, text
items, list items,…
17 18

Canvas Creating a Data Block Form


 It is the surface that has the form items on it.
 It has many types:
 Steps:
 Content (The default) 1. Create the data block using the
 Tab Data Block Wizard
 Stacked 2. Create the form layout using the
 … Layout Wizard
 All canvases inside some window must have
the property ‘Window’ has the name of the
enclosing window.

20

Data Block Wizard Layout Wizard


 Welcome page  Canvas page
 Type page  Select the canvas where the block is displayed
 Select table or view on which to base the block  Data Block page
source
 Select the fields that are displayed on the layout
 Table page
 Select table associated with form  Items page
 Enforce Integrity Constraint Check Box  Specify the column labels, heights and widths
 Finish page  Style page
 Option to use the Layout Wizard to automate  Specify to create a form- or tabular-style layout
creating the layout
21 22

Form Builder Wizards


Layout Styles Are Re-entrant
 Form style  When you select the frame of the block and go
 One record appears on the form at a to data block wizard or layout wizard, you will be
time in the re-entrant mode.
 A Wizard is in re-entrant mode when its pages
 Tabular style
appear as tabs
 Multiple records display on the form in
a table

49
23 24
Configuring Form Windows Modifying Form Properties
 Every form object has a Property
Palette that allows you to configure
form properties

Property
Nodes Property List
Window Minimize/ Window
Title Maximize buttons size
25 26

Intersection Property Palette Custom Blocks


 Used to change property of several  Data Blocks are related to database tables
items to the same value. or other objects.
 Select items while pressing CTRL.  Custom Blocks are not related to database.
 Example:
Put all the buttons in the form in one block. This
block is not related to database and its type is
custom block.

27 28

Multiple-Table Forms Master-Detail Forms


 Data block forms can display data from
multiple tables that have a master-detail
relationship Master block
 Master record has multiple related detail
records
 Examples:
 One ITEM record has multiple related INVENTORY
records
Detail block
 One CUSTOMER might have multiple CUST_ORDER
records
29 30

Creating a Master-Detail Form Master-Detail Relationships


 Create the Example
master block  Create the departments block.
 Unselect the department block frame.
first
 Create the employees block.
 Specify the  You will see the master-detail relationship page in the data block
relationship wizard of the employees.
on the Data  Uncheck ‘Auto Join’
Block Wizard  Press: Create Relationship
Master-Detail  Select the master block(departments)
page of the  In the Detail Item, select the foreign key(Department_ID)
detail block  In the Master Item, select the primary key(Department_ID)
 Make sure that the relation displayed below is correct. 50
31 32
Master-Detail
Master-Detail Relationships Relationship Example
 You can check that the Master Detail
relationship is correct using two methods:
Method1
Go to the object navigator (F3).
Go to the Master Block(Departments),
You will see the relation under RELATIONS.
Select it and click F4 to go to properties.
You can see the relation in the property JOIN CONDITION.

33 34

Master-Detail
Relationship Example Master-Detail Relationship
 You can check that the Master Detail relationship is
correct using two methods:
Method2
Run The form
Click ENTER QUERY
Go to the primary key in the Master Block(Department_ID) in
Departments.
Write an existing number (20 for example)
Click EXECUTE QUERY
You will see that data is retrieved in the two blocks.

35 36

Creating an LOV Using the


Form Lists of Values (LOVs) LOV Wizard
1. Go to the Object Navigator (F3)
 List of legal values that can be selected 2. Select LOVs and click the button Create
for use in a form field 3. Select ‘Use LOV Wizard’
4. Select Build SQL Query to write the query. You need to select
LOV the Primary Key here (Dept_id from Departments)
command 5. Specify which fields will be in the LOV
button 6. Click on Look Up Return Item to select the form fields that
will take the LOV item.
7. You can write the title of the LOV and specify some options
LOV
8. Select Assigned Item, the field that will display the LOV.
display

37 38

Opening the LOV Display Opening the LOV Display


 Run the Form
 Place the insertion point in the text item to which the
LOV is attached
 Press CTRL+L, or from Edit menu of the form choose
the option ‘Display List’
 In order to display LOV automatically when the
cursor is in the text item, go to the Object Navigator
(F3), click on the list of value (For example, LOV10,
as in the next slide), press F4 to go to the properties,
select Automatic Display property to be YES.
51
39 40
Creating a Command Button
to Open the LOV Display LOV Command Button Trigger
 Create a command button on the Create a trigger for the button.
canvas  Select the button, click F11 or right click and select
 The button can have a label or an icon. PL/SQL Editor.
 For Icon, select the button, click F4 for  Select WHEN BUTTON PRESSED
properties, set property Iconic to be YES.  Write in the code:
GO_ITEM(‘Block.Item’);
 Complete path to .ico file must be specified --For example: Go_Item(‘Departments.Department_ID’);
in Icon Filename. List_Values;
 For Label, select Label property and write
‘Display LOV’
41 42

Trigger Program Units


 It is a PL/SQL Code that is executed  Program units are procedures,
due to an event. functions, packages,…
 Example:  We need them to save effort.
WHEN BUTTON PRESSED: A code that  Function returns a value, but procedure
is executed when a button is pressed. do not.
WHEN NEW ITEM INSTANCE: A code
that is executed when the cursor go to
a field.
43 44

Creating A Program Unit Creating A Program Unit


 Go to object navigator.
 Select Program Units, and click Create.
 Select Procedure radio button, and
write its name.
 Write the code of the procedure in the
next page.

45 46

Example Calling the Procedure


 Assume that you want to check if the  Create a button and label it ‘Save’
department id is greater than 0.  Select When Button Pressed trigger.
 Write in the code the name of the procedure:
 Write in the procedure: Check_dept_id;
If :Departments.Department_ID<0 Then --The prev. statement is a procedure call
Message(‘ID must be >0’); --Procedure call must have the name of the proc.
Go_Item(‘Departments.Department_ID’); Followed by ;
Raise Form_Trigger_Failure; --You can write then:
END If; Commit;
Message(‘Saved Successfully’); 52
47 48
Alerts Creating an Alert
 Form-level object  Go to object Navigator
 Select Alerts and click Create
 Object properties define alert  Change Alert Name to ‘Stop’ or ‘Note’
appearance  Select the Alert (‘Stop’ for e.g) and click on F4 for
Message
Title properties.
 Change the property Alert Style to Stop.
Style
 Do not write a message.
icon
 Make Alert Button1 is ‘ok’ and other buttons null.
 Create two alerts, one for stop and one for note.
Buttons
50

Calling an Alert Enhanced Guide to Oracle 10g


Create a button named Save. Write in the code:
Declare
Y Integer;
Begin
Extra Forms Builder &
IF :departments.department_id>0 THEN
SET_ALERT_PROPERTY('stop', ALERT_MESSAGE_TEXT, ‘ID must be >0');
Reports Builder Topics
y:=SHOW_ALERT('stop');
IF y=ALERT_BUTTON1 THEN
GO_ITEM(‘departments.department_id'); Modified By: Dr. Bilal Hawashin
Department of Computer Information Systems
Raise form_trigger_failure;
Alzaytoonah University of Jordan
END IF;
End IF;
End;
51 1

Canvas Tab Canvases


 It is the surface that has the form items on it.  Multiple-page canvases that allow users
 It has many types: to move among different canvas
 Content (The default) surfaces by clicking tabs
 Tab
 Stacked
 …
 All canvases inside some window must have
the property ‘Window’ has the name of the
enclosing window.

Creating a Data Block in a Tab


Tab Canvas Components Canvas
 Tab canvas  Create a data block using the data block
 Collection of related tab pages wizard.
 Tab pages  In the layout wizard, select TAB in the
 Surfaces that display form items canvas type. By default, one tab page
 Tab labels will be created, and the data block will
 Identifier at top of tab page be placed on it.
 A tab canvas lies on top of a content canvas
 A tab canvas can have one or more tab
pages. 53
Creating a Tab Canvas Creating a Tab Canvas

Creating a Data Block on a


Creating a Tab Canvas Different Tab Page
If you want to create another data block
on a different tab page:
 Use data block wizard

 In the layout wizard, select new

page(see next slide)


 The resulting block will be placed in the

new page.

Creating a Data Block on a


Different Tab Page Important Tab Page Properties
Name: how the page
Is referenced in the form

Label: Caption that


appears
on the associated tab

Adjusting the Tab Page Order List Item


 Tab page that appears first is tab page  A fixed list.
whose block items appear first in the  Has a specific and fixed number of
Object Navigator values(LOV is not fixed).

Block order

Tab page order 54


doesn’t matter
Important Text Item
Creating List Item Properties
 Select the item that you want to 


Name: Item name.
Item Type: Used to convert to list, image, radio, check, …
convert into a list.  Conceal Data: If yes, data will be displayed like ***. Used for
Password fields.
 Click F4 for properties.  Iconic: If yes, button will be iconic.
Icon Filename
Set Item Type to List Item

  Previous Navigation Item: Which item leads to this item when
using keyboard.
 Use Elements In List to insert the  Next Navigation Item: Which is the next item when using
values that will be displayed and will keyboard.
Required: If yes, you need to insert a value in the field before
be inserted into the database.

leaving it.
 Enabled: If no, You can not select the item by the mouse.
 List of Values: Is there a list of value related to the item.
 Hint: to display a hint
 Display Hint Automatically: yes or no
 Tooltip: to display a tooltip

Hint & Tooltip Radio Buttons


 Limits user to one of two or more
related, mutually exclusive choices

Tooltip

Hint

17

Radio Groups Creating a Radio Group


 Related radio 1. Create the form using the Data Block and
buttons are part of Layout Wizards
a radio group 2. Open the item Property Palette, and change
the Item Type value to Radio Group
Radio group 3. Draw and format the radio buttons on the
canvas
Individual related
4. Modify the radio button properties
radio buttons 5. Modify the radio group properties

18 19

Important Radio Button Important Radio Group


Properties Properties
Name: how the
button is
referenced Name: how the
within the form radio group is
referenced
within the form
Label: description that
appears next to the
button on the canvas

Initial Value: data value


Radio Button Value: of the radio button
associated data value within the radio group
in the database that is selected when
the form first appears

55
20 21
Check Boxes Check Box Example
 Used to represent fields that can
have one of two values
 Check box caption is interpreted as
TRUE or FALSE
 If checked, caption is true
 If cleared, caption is false

22 23

Important Check Box


Creating a Check Box Properties
1. Create the form using the Data Block Label: description that

and Layout Wizards


appears next to the check
box on the canvas

2. Open the item Property Palette, and Value when Checked: data

change the Item Type value to Check


value of the item when the
box is checked

Box Value when Unchecked:

Modify the item properties


data value of the item when
3. the box is checked

Check Box Mapping of


Other Values: check
box status when form
first opens, or when new
blank record is added
24 25

Adding A Custom Menu Creating a user-defined Menu


 By default, oracle forms will display a  Go to the object navigator (F3)
built in menu during the runtime.  Select Menus (See left)
 This menu can be changed to user-  Click Create
defined menu.

26 27

Creating a user-defined Menu Creating a user-defined Menu


 A New Module (Module5) will be  Click on Create Down button to create the first
created. item in Action menu. Name it Save.
 Go to Menus inside it and click  Click on Action again, and click on Create
Create. Sibling button to create another list. Name it
 Menu(Menu1) will be created. Query. Create Create
Down Sibling
 Right click on Menu1
 Select Menu Editor
 In the menu editor screen, name
the first menu list: Action 56
28 29
Creating a user-defined Menu Creating a user-defined Menu
 Now, we want to add code to the Save. Using the same method, you can create the
 Right click Save, select PL/SQL following menu.
 You can write:
Do_Key(‘COMMIT_FORM’);

Go to Tools  Menu Editor to return back.

30 31

Creating a user-defined Menu Creating a user-defined Menu


 The code for each menu list is: Some functions are built in such as copy, paste,…
Insert Record: Do_Key(‘CREATE_RECORD’);  Create another list named Edit, and create three

Delete Record:Do_Key(‘DELETE_RECORD’); items in it: Cut, Copy, and Paste.


Enter Query: Do_Key(‘ENTER_QUERY’);  Right click on the cut item and go to properties.
Execute Query: Do_Key(‘EXECUTE_QUERY’);  In Menu Item Type property, select Magic.
Next Record: Do_Key(‘NEXT_RECORD’);
 In Magic Item property, select the built in
Clear Record: Do_Key(‘CLEAR_RECORD’);
function cut.
 Each line of the code is added to the  In Command Type property, select Null.
PL/SQL editor of the corresponding menu  You can do the same with Copy and Paste.
item. 32 33

Final Menu! Attaching Menu to Form


 The final output should look like this! In order to attach the menu to a form:
 Click on the menu module (Module5 for example), and go
 You can reorder the lists or the items inside each
to FileSave As. You can save it on C: For example.
list by drag and drop method.
 Select Module5 and go to ProgramCompile Module.

 Now, create another form(to which you want to attach

the menu). Name it Menu_Test.


 Select Menu_Test and click F4 for properties.

 Select Menu Module property and change it from

DEFAULT&SMARTBAR to C:\Module5.mmx
 Run this form and you will see the new menu.

34 35

Formatting Character Text


Formatting Text Items Items
 Specify desired format mask in text  Place embedded characters in double
item Format Mask property quotes
 If format mask makes value wider than
text item Data Width property, data
appears as #####
 E.g: make the format mask for the empno field
in the form builder: 99”- - “ 99 and make the
data length for the field 4.

57
36 37
Format Mask Examples Report Builder
 Value Format Mask Result  Used to facilitate creating professional
7945 999 ### reports based on the database.
7945 9999$ 7945$  From Developer Suite  Report
7945 99”-”99 79-45 Builder.
34.28 99.9 34.3
 Select ‘Use the Report Wizard’.
34.28 99.999 34.280
SYSDATE Day-MON-YY Friday-NOV-06

38 39

Report Builder Report Builder

40 41

Report Builder Report Builder

42 43

Report Builder Report Builder

58
44 45
Report Builder Report Builder
Move all fields to the right

46 47

Report Builder Report Builder


Output!

48 49

Visual Attributes Visual Attributes


 Used as a user-defined package of Example:
visual effects.  If the user in the Employees Form
 Create a visual group, name it, define write an employee id less than zero,
the visual effects, and then assign it to change the text field color to red and
item or trigger. display an error message.
 All the effects will take place together.

50 51

Visual Attributes Visual Attributes


• Name the visual attribute Error.
How?
• Select it and go to properties.
• Create a data block for
Employees • You can here make the effects you
want. For example, change
• Go to object navigator
Background color to red.
(F3)
• Select Visual Attributes
as shown left, then
CREATE button. 59
52 53
Visual Groups Visual Attributes
• Next, go to layout wizard (F2), click on
Employee_ID field, then click on F11
for writing a trigger.
• Select KEY_NEXT_ITEM
• This trigger works when you move
from this item to the next item by
keyboard.

54 55

Visual Attributes Visual Attributes


• In the KEY_NEXT_ITEM, write: Now, run the form and insert a negative
if :Employees.Employee_ID<0 then value in the Employee_ID, press Tab
set_item_property('Employees.Employee_ID',
VISUAL_ATTRIBUTE, 'ERROR'); to move to next item.
go_item('Employees.Employee_ID');
Result:
message('ID must be greater than zero');
end if;

56 57

Stored Procedures Stored Procedure Examples


• PL/SQL blocks, similar to Procedures in The following examples depend of the
Forms Builder, but are stored in the table DBUSER.
database server. CREATE TABLE DBUSER
( USER_ID NUMBER (5) NOT NULL,
USERNAME VARCHAR2 (20) NOT NULL,
CREATED_BY VARCHAR2 (20) NOT NULL,
CREATED_DATE DATE NOT NULL,
PRIMARY KEY ( USER_ID ) );

58 59

Stored Procedure Example1 Stored Procedures


SQL>CREATE OR REPLACE PROCEDURE getUserInfo(  Two types of parameters: In and Out
p_userid IN DBUSER.USER_ID%TYPE,
o_username OUT DBUSER.USERNAME%TYPE,  In parameter is used to insert data to the
o_createdby OUT DBUSER.CREATED_BY%TYPE, procedure
o_date OUT DBUSER.CREATED_DATE%TYPE)  Out parameter is used to output data from
IS
the procedure.
BEGIN
SELECT USERNAME , CREATED_BY, CREATED_DATE INTO  As a convention, we need to use p_ with
o_username, o_createdby, o_date FROM DBUSER WHERE input parameters, and o_ with output
USER_ID = p_userid;
parameters.
END;
/ 60
60 61
Call of the Procedure Stored Procedure Example2
getUserInfo deleteUser
DECLARE CREATE OR REPLACE PROCEDURE deleteUser
o_username DBUSER.USERNAME%TYPE; (p_userid IN DBUSER.USER_ID%TYPE)
o_createdby DBUSER.CREATED_BY%TYPE; IS
o_date DBUSER.CREATED_DATE%TYPE; BEGIN
BEGIN DELETE DBUSER WHERE USER_ID = p_userid;
--the next statement is the call to the stored procedure. COMMIT;
getUserInfo(1001,o_username,o_createdby,o_date); END;
DBMS_OUTPUT.PUT_LINE('username : ' || o_username); /
DBMS_OUTPUT.PUT_LINE('createdby : ' || o_createdby);
DBMS_OUTPUT.PUT_LINE('createddate : ' || o_date);
END;
/

62 63

Call of the Procedure Stored Procedure Example3


deleteUser Update User
BEGIN CREATE OR REPLACE PROCEDURE updateUser
deleteUser(1001); (p_userid IN DBUSER.USER_ID%TYPE,
p_username IN BUSER.USERNAME%TYPE)
END; IS
Important: BEGIN
Stored procedure is created in UPDATE DBUSER SET USERNAME = p_username
database server. WHERE USER_ID = p_userid;
Stored procedure call can be from COMMIT;
Server SQL or from Client(E.g END;
form builder button). /
64 65

Call of the Procedure


updateUser
BEGIN
updateUser(1001,'new_mkyong');
END;

66

61
About PL/SQL
PL/SQL
 Declaring Variables  PL/SQL is an extension to SQL with design
features of programming languages.
 Writing Executable Statements
 It includes SQL statements plus additional
 Interacting with the Oracle Server instructions.
 Writing Control Structures

 Working with Composite Datatypes

 Cursors

 Handling Exceptions

PL/SQL Block Structure Declaring PL/SQL Variables


 DECLARE – Optional
Variables, cursors, user-defined exceptions
Syntax
 BEGIN – Mandatory identifier [CONSTANT] datatype [NOT NULL]
[:= expr];
– SQL statements
– PL/SQL statements
 EXCEPTION – Optional Examples
Actions to perform when errors occur
DECLARE Declare
 END; – Mandatory v_hiredate DATE;
BEGIN
v_deptno NUMBER(2) NOT NULL := 10;
EXCEPTION v_location VARCHAR2(13) := 'Atlanta';
c_comm CONSTANT NUMBER := 1400;
END;

Declaring PL/SQL Variables Scalar Variable Declarations

 Examples
 Guidelines
 Follow naming conventions. v_job VARCHAR2(9);
v_count BINARY_INTEGER := 0;
 Initialize variables designated as NOT NULL v_total_sal NUMBER(9,2) := 0;
and CONSTANT. v_orderdate DATE := SYSDATE + 7;
c_tax_rate CONSTANT NUMBER(3,2) := 8.25;
 Declare at most one identifier per line. v_valid BOOLEAN NOT NULL := TRUE;

Declaring Variables Declaring Boolean Variables


with the %TYPE Attribute
 Only the values TRUE, FALSE, and NULL
can be assigned to a Boolean variable.
 Examples  The variables are connected by the logical
... operators AND, OR, and NOT.
v_ename emp.ename%TYPE;
v_balance NUMBER(7,2);
v_min_balance v_balance%TYPE := 10;
...

62
Manipulating Data Using
PL/SQL
 Make changes to database tables by using
DML commands:
Writing Executable 


INSERT
UPDATE INSERT

Statements  DELETE
UPDATE

DELETE

Inserting Data Updating Data


 Increase the salary of all employees in the
 Add new employee information to the EMP table who are Analysts.
EMP table.  Example
 Example DECLARE
BEGIN v_sal_increase emp.sal%TYPE := 2000;
INSERT INTO emp(empno, ename, job, deptno) BEGIN
VALUES (empno_sequence.NEXTVAL, 'HARDING', UPDATE emp
'CLERK', 10); SET sal = sal + v_sal_increase
END; WHERE job = 'ANALYST';
END;

Deleting Data Example


Declare
V_no emp.sal%type;
 Delete rows that belong to department 10 from
Begin
the EMP table. Select sal into v_no from emp where deptno=20;
 Example Dbms_output.put_line(v_no);
DECLARE Update emp set sal = sal+v_no;
v_deptno emp.deptno%TYPE := 10; Exception
BEGIN
DELETE FROM emp When no_data_found then
WHERE deptno = v_deptno;
END; Dbms_output.put_line('No Data');
When too_many_rows then
Dbms_output.put_line('Many Rows');
End;
/

Naming Conventions
 DECLARE
 orderdate ord.orderdate%TYPE;
 shipdate ord.shipdate%TYPE;
 ordid ord.ordid%TYPE := 601;
 BEGIN



SELECT orderdate, shipdate
INTO
FROM
orderdate, shipdate
ord
Writing Control
Structures
 WHERE ordid = ordid;
 END;
 SQL> /
 DECLARE
 *
 ERROR at line 1:
 ORA-01422: exact fetch returns more than
requested
 number of rows 63
 ORA-06512: at line 6
Controlling PL/SQL Flow IF Statements
of Execution Syntax
IF condition THEN
statements;
 You can change the logical flow of [ELSIF condition THEN
statements;]
statements using conditional IF [ELSE
statements;]
statements and loop control structures. END IF;

 Conditional IF statements: Simple IF statement:


 IF-THEN-END IF Set the manager ID to 22 if the employee
 IF-THEN-ELSE-END IF name is Osborne.
IF v_ename = 'OSBORNE' THEN
 IF-THEN-ELSIF-END IF
v_mgr := 22;
END IF;

Simple IF Statements IF-THEN-ELSE Statements


 Set the job title to Salesman, the department  Set a flag for orders where there are fewer
number to 35, and the commission to 20% than five days between order date and ship
of the current salary if the last name is Miller. date.
 Example  Example
...
. . . IF v_shipdate - v_orderdate < 5 THEN
IF v_ename = 'MILLER' THEN v_ship_flag := 'Acceptable';
v_job := 'SALESMAN'; ELSE
v_deptno := 35; v_ship_flag := 'Unacceptable';
v_new_comm := sal * 0.20; END IF;
END IF; ...
. . .

IF-THEN-ELSIF Statements Iterative Control: LOOP


Statements
 For a given value, calculate a percentage of
that value based on a condition.  Loops repeat a statement or sequence of
statements multiple times.
 Example
. . .
 There are three loop types:
IF v_start > 100 THEN  Basic loop
v_start := 2 * v_start;
ELSIF v_start >= 50 THEN  FOR loop
v_start := .5 * v_start;  WHILE loop
ELSE
v_start := .1 * v_start;
END IF;
. . .

Basic Loop Basic Loop


 Syntax  Example
LOOP -- delimiter
DECLARE
statement1; -- statements v_ordid item.ordid%TYPE := 601;
. . .
-- EXIT statement v_counter NUMBER(2) := 1;
EXIT [WHEN condition];
BEGIN
END LOOP; -- delimiter LOOP
INSERT INTO item(ordid, itemid)
VALUES(v_ordid, v_counter);
v_counter := v_counter + 1;
where: condition is a Boolean variable or
EXIT WHEN v_counter > 10;
expression (TRUE, FALSE,
END LOOP;
or NULL);
END;

64
DECLARE
v_grade NUMBER(3); FOR Loop
v_status Varchar2(30);
BEGIN  Syntax
v_grade :=10;
FOR counter in [REVERSE]
loop lower_bound..upper_bound LOOP
if v_grade>80 then statement1;
v_status :='Excellent'; statement2;
elsif v_grade>60 then . . .
END LOOP;
v_status :='Good';
else  Use a FOR loop to shortcut the test for the
v_status :='Bad'; number of iterations.
end if;
 Do not declare the counter; it is declared
insert into stgrades values(v_grade, v_status);
v_grade := v_grade+10; implicitly.
exit when v_grade>99;
end loop;
END;
/

FOR Loop FOR Loop


 Guidelines  Insert the first 10 new line items for order
 Reference the counter within the loop only; it is number 601.
undefined outside the loop.  Example
 The lower and upper bounds of the loop could
DECLARE
be values, variables, or expressions v_ordid item.ordid%TYPE := 601;
BEGIN
 Do not reference the counter as the target of an FOR i IN 1..10 LOOP
assignment. An error message rises if you do so. INSERT INTO item(ordid, itemid)
VALUES(v_ordid, i);
END LOOP;
END;

WHILE Loop WHILE Loop


 Example
SQL>ACCEPT v_dept_name PROMPT 'Enter the dept. name: '
 Syntax SQL>ACCEPT num_depts PROMPT 'Enter number of depts: '
Condition is SQL>DECLARE
WHILE condition LOOP evaluated at the v_count NUMBER(2) := 1;
statement1; beginning of BEGIN
statement2; each iteration. WHILE v_count <= &num_depts LOOP
. . . INSERT INTO dept(deptno,dname)
END LOOP; VALUES (v_count, &v_dept_name);
v_count := v_count + 1;
END LOOP;
COMMIT;
 Use the WHILE loop to repeat END;
/
statements while a condition is TRUE.

The %ROWTYPE Attribute The %ROWTYPE Attribute


 Examples
 Declare a variable according to a collection of
columns in a database table or view.  Declare a variable to store the same
 Prefix %ROWTYPE with the database table.
information about a department as it is
 Fields in the record take their names and
stored in the DEPT table.
datatypes from the columns of the table or dept_record dept%ROWTYPE;

view.  Declare a variable to store the same


information about an employee as it is
stored in the
emp_record EMP table.
emp%ROWTYPE;

65
%ROWTYPE Example
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
d dept%ROWTYPE;
BEGIN
SELECT deptno,dname,loc INTO d FROM dept Cursors
WHERE deptno=10;
DBMS_OUTPUT.PUT_LINE(d.dname);
END;
/
ACCOUNTING

SQL Cursor
 A cursor is a private SQL work area. Database Server Memory
 There are two types of cursors:
 Implicit cursors
Cursor
 Explicit cursors
 The Oracle Server uses implicit cursors to Number of Parsed
parse and execute your SQL statements. rows
processed
command
statement
Context Area
 Explicit cursors are explicitly declared by the CID CALLID CNAME CCREDIT

programmer. active set 1


2
3
MIS 101
MIS 301
MIS 441
Intro. to Info. Sy stems
Sy stems Analy sis
Database Management
3
3
3
4 CS 155 Programming in C++ 3
5 MIS 451 Client/Serv er Sy stems 3

SQL Cursor Attributes Implicit Cursor SQL%ROWCOUNT


Example
 Using SQL cursor attributes, you can test SQL> SET SERVEROUTPUT ON;
the outcome of your SQL statements. SQL> DECLARE
SQL%ROWCOUNT Number of rows affected by the
most recent SQL statement (an r NUMBER;
integer value) BEGIN
SQL%FOUND Boolean attribute that evaluates to
TRUE if the most recent SQL
DELETE FROM emp WHERE empno=7900;
statement affects one or more rows r:=SQL%ROWCOUNT;
SQL%NOTFOUND Boolean attribute that evaluates to DBMS_OUTPUT.PUT_LINE(r);
TRUE if the most recent SQL
statement does not affect any rows END;
SQL%ISOPEN Always evaluates to FALSE because /
PL/SQL closes implicit cursors
immediately after they are executed 1

Implicit Cursor SQL%FOUND Implicit Cursor SQL%ISOPEN


Example Example
SQL> DECLARE SQL> DECLARE
r BOOLEAN; r BOOLEAN;
BEGIN BEGIN
DELETE FROM emp WHERE empno=1000; UPDATE emp SET sal=1000 WHERE empno>7900;
r:=SQL%FOUND; r:=SQL%ISOPEN;
IF r THEN IF r THEN
DBMS_OUTPUT.PUT_LINE('Rows are founded'); DBMS_OUTPUT.PUT_LINE('The cursor is opened');
ELSE ELSE
DBMS_OUTPUT.PUT_LINE('No Rows are founded'); DBMS_OUTPUT.PUT_LINE('The cursor is closed');
END IF; END IF;
END; END;
/ /
No Rows are founded The cursor is closed

66
About Cursors Explicit Cursor Functions

 Every SQL statement executed by the Active set


Oracle Server has an individual cursor 7369 SMITH CLERK
associated with it: 7566 JONES MANAGER
 Implicit cursors: Declared for all DML Cursor 7788 SCOTT ANALYST Current row
and PL/SQL SELECT statements 7876 ADAMS CLERK
7902 FORD ANALYST
 Explicit cursors: Declared and named by
the programmer

Controlling Explicit Cursors Controlling Explicit Cursors


Open the cursor.
No Pointer

Yes Cursor
DECLARE OPEN FETCH EMPTY? CLOSE Fetch a row from the cursor.

Pointer
• Create a • Identify • Load the • Test for • Release Cursor
named the active current existing the active Continue until empty.
SQL area set row into rows set
variables • Return to Pointer
FETCH if
Cursor
rows
found Close the cursor.

Explicit Cursor Example Declaring the Cursor


SQL> DECLARE  Syntax
v_num emp.empno%TYPE;
v_name emp.ename%TYPE; CURSOR cursor_name IS
CURSOR my_cursor IS SELECT empno,ename FROM emp WHERE empno>7900; select_statement;
BEGIN
OPEN my_cursor;
LOOP  Do not include the INTO clause in the cursor
FETCH my_cursor INTO v_num,v_name;
EXIT WHEN my_cursor%NOTFOUND; declaration.
DBMS_OUTPUT.PUT_LINE(v_num || ' has the name ' ||v_name);
END LOOP;
CLOSE my_cursor;
END;
/
7902 has the name FORD
7934 has the name MILLER

Declaring the Cursor Opening the Cursor


 Example  Syntax
DECLARE OPEN cursor_name;
CURSOR emp_cursor IS
SELECT empno, ename
FROM emp;  Open the cursor to execute the query and
CURSOR dept_cursor IS
identify the active set.
SELECT *  If the query returns no rows, no exception is
FROM dept
WHERE deptno = 10; raised.
BEGIN
...  Use cursor attributes to test the outcome after
a fetch.

67
Fetching Data from the Cursor Fetching Data from the Cursor
 Syntax
 Examples
FETCH cursor_name INTO [variable1, variable2, ...]
| record_name];
FETCH emp_cursor INTO v_empno, v_ename;


 Retrieve the current row values into variables. ...
OPEN defined_cursor;
 Include the same number of variables. LOOP
FETCH defined_cursor INTO defined_variables
 Match each variable to correspond to the EXIT WHEN ...;
...
columns positionally. -- Process the retrieved data
...
 Test to see if the cursor contains rows. END;

Closing the Cursor Explicit Cursor Attributes


 Obtain status information about a cursor.
 Syntax Attribute Type Description
CLOSE cursor_name; %ISOPEN Boolean Evaluates to TRUE if the cursor
is open
 Close the cursor after completing the %NOTFOUND Boolean Evaluates to TRUE if the most
processing of the rows. recent fetch does not return a row

 Reopen the cursor, if required. %FOUND Boolean Evaluates to TRUE if the most
recent fetch returns a row;
 Do not attempt to fetch data from a cursor complement of %NOTFOUND
once it has been closed. %ROWCOUNT Number Evaluates to the total number of
rows returned so far

Controlling Multiple Fetches The %ISOPEN Attribute


 Fetch rows only when the cursor is open.
 Process several rows from an explicit cursor  Use the %ISOPEN cursor attribute before
using a loop. performing a fetch to test whether the cursor
 Fetch a row with each iteration. is open.
 Use the %NOTFOUND attribute to write a  Example
test for an unsuccessful fetch.
 Use explicit cursor attributes to test the IF NOT emp_cursor%ISOPEN THEN
OPEN emp_cursor;
success of each fetch. END IF;
LOOP
FETCH emp_cursor...

The %NOTFOUND Explicit Cursor %ISOPEN Example


and %ROWCOUNT Attributes
SQL> DECLARE
v_num emp.empno%TYPE;
v_name emp.ename%TYPE;
 Use the %ROWCOUNT cursor attribute to r BOOLEAN;
retrieve an exact number of rows. CURSOR my_cursor IS SELECT empno,ename FROM emp WHERE empno>7900;
BEGIN
 The value of %ROWCOUNT before fetching OPEN my_cursor;
r:=my_cursor%ISOPEN;
any row is NULL. IF r THEN
DBMS_OUTPUT.PUT_LINE('The Cursor is opened after the open statement');
 Use the %NOTFOUND cursor attribute to ELSE
determine when to exit the loop. DBMS_OUTPUT.PUT_LINE('The Cursor is closed after the open statement');
END IF;

68
Explicit Cursor %ISOPEN Example Explicit Cursor %ROWCOUNT
Cont. Example
LOOP SQL> DECLARE
v_name emp.ename%TYPE;
FETCH my_cursor INTO v_num,v_name; r NUMBER;
EXIT WHEN my_cursor%NOTFOUND; c NUMBER:=1;
END LOOP; CURSOR my_cursor IS SELECT ename FROM emp WHERE empno>7900;
CLOSE my_cursor; BEGIN
OPEN my_cursor;
r:=my_cursor%ISOPEN; LOOP
IF r THEN FETCH my_cursor INTO v_name;
DBMS_OUTPUT.PUT_LINE('The Cursor is opened after the close statement'); EXIT WHEN my_cursor%NOTFOUND;
r:=my_cursor%ROWCOUNT;
ELSE DBMS_OUTPUT.PUT_LINE('After fetch number ' || c || ' ROWCOUNT has the value ' || r);
DBMS_OUTPUT.PUT_LINE('The Cursor is closed after the close statement'); c:=c+1;
END IF; END LOOP;
END; CLOSE my_cursor;
END;
/ /
The Cursor is opened after the open statement After fetch number 1 ROWCOUNT has the value 1
The Cursor is closed after the close statement After fetch number 2 ROWCOUNT has the value 2

Cursors and Records


 Process the rows of the active set
conveniently by fetching values into a
PL/SQL RECORD.
 Example
DECLARE
Handling Exceptions
CURSOR emp_cursor IS
SELECT empno, ename
FROM emp;
emp_record emp_cursor%ROWTYPE;
BEGIN
OPEN emp_cursor;
LOOP
FETCH emp_cursor INTO emp_record;
...

Handling Exceptions Exception Types


 Trap the exception
 Predefined Oracle Server
DECLARE
 Non-predefined Oracle Server
Implicitly
raised }
BEGIN  User-defined Explicitly raised
Exception
is raised
EXCEPTION

Exception
is trapped END;

Trapping Predefined Predefined Exception


Oracle Server Errors  Syntax
 Common errors that have been given predefined BEGIN
EXCEPTION
names WHEN NO_DATA_FOUND THEN
statement1;
 Reference the standard name in the exception- statement2;
WHEN TOO_MANY_ROWS THEN
handling routine. statement1;
WHEN OTHERS THEN
 Sample predefined exceptions: statement1;
Error Code Exception Name Description
statement2;
ORA-00001 DUP_VAL_ON_INDEX Unique constraint violated statement3;
ORA-01001 INVALID_CURSOR Illegal cursor operation
ORA-01403 NO_DATA_FOUND Query returns no records
END;
ORA-01422 TOO_MANY_ROWS Query returns more rows than expected
ORA-01476 ZERO_DIVIDE Division by zero

69
ORA-01722 INVALID_NUMBER Invalid numeric conversion
ORA-06502 VALUE_ERROR Error in arithmetic or numeric function operation

You might also like