Sunteți pe pagina 1din 62

1

Using SET Operators

Copyright Oracle Corporation, 1998. All rights reserved.

1
Writing Correlated Subqueries

Copyright Oracle Corporation, 1998. All rights reserved.

Objectives
After completing this lesson, you should be able to do the following:

Describe the types of problems that can be solved with correlated subqueries
Write correlated subqueries

Use the EXISTS and NOT EXISTS operators


Update and delete rows using correlated subqueries

1-3

Copyright Oracle Corporation, 1998. All rights reserved.

What Is a Subquery?
A subquery is a SELECT statement embedded in a clause of another SQL statement.
Main Query SELECT . . . FROM . . . WHERE . . . (SELECT . . . FROM . . . WHERE . . .) Subquery

1-4

Copyright Oracle Corporation, 1998. All rights reserved.

Subqueries
SELECT FROM WHERE select_list table expr operator (SELECT FROM

select_list table);

The subquery (inner query) executes once before the main query.

The result of the subquery is used by the main query (outer query).
1-5
Copyright Oracle Corporation, 1998. All rights reserved.

Using a Subquery
SQL> SELECT ename 2 FROM emp 2975 3 WHERE sal > 4 (SELECT sal 5 FROM emp 6 WHERE empno = 7566); ENAME ---------KING FORD SCOTT

1-6

Copyright Oracle Corporation, 1998. All rights reserved.

Correlated Subqueries
Used to affect row-by-row processing, each subquery is executed once for every row of the outer query.
GET candidate row

EXECUTE inner query using candidate row value

USE value(s) from inner query to qualify candidate row


1-7
Copyright Oracle Corporation, 1998. All rights reserved.

Correlated Subqueries
SELECT outer1, outer2, ... FROM table1 alias1 WHERE outer1 operator (SELECT inner1 FROM table2 alias2 WHERE alias1.outer2 = alias2.inner1);

The subquery references a column from a table in the parent query.

1-8

Copyright Oracle Corporation, 1998. All rights reserved.

Using Correlated Subqueries


Find all employees who make more than the average salary in their department.
SQL> SELECT empno, sal, deptno Each time the outer query is processed the 2 FROM emp outer inner query is 3 WHERE sal > (SELECT AVG(sal) evaluated. 4 FROM emp inner 5 WHERE outer.deptno = inner.deptno); EMPNO SAL DEPTNO -------- --------- --------7839 5000 10 7698 2850 30 7566 2975 20 ... 6 rows selected.
1-9
Copyright Oracle Corporation, 1998. All rights reserved.

Using the EXISTS Operator


If a subquery row value is found:
The search does not continue in the

inner query.
The condition is flagged TRUE.

If a subquery row value is not found:


The condition is flagged FALSE. The search continues in the inner

query.
1-10
Copyright Oracle Corporation, 1998. All rights reserved.

Using the EXISTS Operator


Find employees who have at least one person reporting to them.
SQL> SELECT empno, ename, job, deptno 2 FROM emp outer 3 WHERE EXISTS (SELECT empno 4 FROM emp inner 5 WHERE inner.mgr = outer.empno); EMPNO ENAME --------- ---------7839 KING 7698 BLAKE 7782 CLARK 7566 JONES ... 6 rows selected.
1-11

JOB DEPTNO --------- --------PRESIDENT 10 MANAGER 30 MANAGER 10 MANAGER 20

Copyright Oracle Corporation, 1998. All rights reserved.

Using the NOT EXISTS Operator


Find all departments that do not have any employees.
SQL> SELECT 2 FROM 3 WHERE 4 5 deptno, dname dept d NOT EXISTS (SELECT '1' FROM emp e WHERE d.deptno = e.deptno);

DEPTNO DNAME --------- ---------40 OPERATIONS

1-12

Copyright Oracle Corporation, 1998. All rights reserved.

Correlated UPDATE
UPDATE table1 alias1 SET column = (SELECT expression FROM table2 alias2 WHERE alias1.column = alias2.column);

Use a correlated subquery to update rows in one table based on rows from another table.

1-13

Copyright Oracle Corporation, 1998. All rights reserved.

Correlated DELETE
DELETE FROM table1 alias1 WHERE column operator (SELECT expression FROM table2 alias2 WHERE alias1.column = alias2.column);

Use a correlated subquery to delete only those rows that also exist in another table.

1-14

Copyright Oracle Corporation, 1998. All rights reserved.

Summary
Correlated subqueries are useful whenever a subquery must return a different result for each candidate row. The EXISTS operator is a Boolean operator, testing the presence of a value. Correlated subqueries can be used with SELECT, UPDATE, and DELETE statements.
1-15
Copyright Oracle Corporation, 1998. All rights reserved.

Practice Overview
Writing correlated subqueries Using the EXISTS operator

1-16

Copyright Oracle Corporation, 1998. All rights reserved.

1
Generating Scripts to Generate Scripts

Copyright Oracle Corporation, 1998. All rights reserved.

Objectives
After completing this lesson, you should be able to do the following: Describe the types of problems that are solved by using SQL to generate SQL Write a script that generates a script of drop table statements Write a script that generates a script of insert into statements
1-18
Copyright Oracle Corporation, 1998. All rights reserved.

Using SQL to Generate SQL

SQL Script
1-19
Copyright Oracle Corporation, 1998. All rights reserved.

Creating a Basic Script


SQL> SELECT 'DROP TABLE ' || object_name || ';' 2 FROM user_objects 3 WHERE object_type = 'TABLE';

DROP TABLE EMP; DROP TABLE DEPT; DROP TABLE SALGRADE; . . .

1-20

Copyright Oracle Corporation, 1998. All rights reserved.

Controlling the Environment


SET ECHO OFF SET FEEDBACK OFF SET PAGESIZE 0 SPOOL droptab.sql SQL STATEMENT SPOOL OFF Set system variables to appropriate values

SET ECHO ON SET FEEDBACK ON SET PAGESIZE 24

Set system variables back to default value

1-21

Copyright Oracle Corporation, 1998. All rights reserved.

The Complete Picture


SET ECHO OFF SET FEEDBACK OFF SET PAGESIZE 0 SPOOL dropem.sql SELECT 'DROP TABLE ' || object_name || ';' FROM user_objects WHERE object_type = 'TABLE';

SPOOL OFF

SET ECHO ON SET FEEDBACK ON SET PAGESIZE 24


1-22
Copyright Oracle Corporation, 1998. All rights reserved.

Dumping the Contents of a Table to a File


SET HEADING OFF ECHO OFF FEEDBACK OFF SET PAGESIZE 0
SPOOL data.sql

SELECT 'INSERT INTO dept VALUES ('|| deptno||','|| ''''||dname||''''||','|| ''''||loc||''''||');' FROM dept;
SPOOL OFF SET HEADING ON ECHO OFF FEEDBACK ON SET PAGESIZE 24

1-23

Copyright Oracle Corporation, 1998. All rights reserved.

Dumping the Contents of a Table to a File


Source
''''X'''' '''' ''''||dname||'''' 'X' ' 'BOSTON'

Result

1-24

Copyright Oracle Corporation, 1998. All rights reserved.

Generating a Dynamic Predicate


Statement 1

Statement 2
1-25
Copyright Oracle Corporation, 1998. All rights reserved.

Summary
You can select virtually anything. Script files often use the data dictionary. You use the SPOOL command to capture output in a file.

1-26

Copyright Oracle Corporation, 1998. All rights reserved.

Practice Overview
Writing a script to DESCRIBE and SELECT the data from your tables Writing a script to revoke user privileges

1-27

Copyright Oracle Corporation, 1998. All rights reserved.

1
Reporting Using SQL*Plus

Copyright Oracle Corporation, 1998. All rights reserved.

Objectives
After completing this lesson, you should be able to do the following: Format output with the SET commands Add header and footer information Aggregate data in the output

1-29

Copyright Oracle Corporation, 1998. All rights reserved.

SQL*Plus SET Command Variables


The SET command is a system variable that affects the way SQL*Plus runs commands. The following conditions are controlled by system variables: Number of blank lines between records

Number of spaces between columns


Characters used to underline column headings Value to display for null values
1-30
Copyright Oracle Corporation, 1998. All rights reserved.

Additional SET Command Variables


RECSEP

RECSEPCHAR
SPACE UNDERLINE

WRAP
NULL HEADSEP NEWPAGE
1-31
Copyright Oracle Corporation, 1998. All rights reserved.

Using SET Command Variables


SET RECSEP and SET RECSEPCHAR
SET RECSEP EACH SET RECSEPCHAR _ SELECT empno, ename, job, mgr, sal FROM emp WHERE ename='BLAKE' /

EMPNO ENAME JOB MGR SAL --------- ---------- --------- --------- --------7839 KING PRESIDENT 5000 __________________________________________________ 7782 CLARK MANAGER 7839 2450 __________________________________________________ 7934 MILLER CLERK 7782 1300 __________________________________________________
1-32
Copyright Oracle Corporation, 1998. All rights reserved.

Using SET Command Variables


SET SPACE and SET UNDERLINE
SET SPACE 2 SET UNDERLINE = SELECT empno, ename, sal, mgr FROM emp / EMPNO ENAME ========= ========== 7839 KING 7698 BLAKE 7782 CLARK 7566 JONES 7654 MARTIN 14 rows selected.
1-33

SAL ========= 5000 2850 2450 2975 1250

MGR ========= 7839 7839 7839 7698

Copyright Oracle Corporation, 1998. All rights reserved.

Using SET Command Variables


SET NULL
SET NULL Null SELECT empno, ename, sal, mgr, comm FROM emp / EMPNO ENAME SAL MGR COMM --------- ---------- --------- --------- --------7839 KING 5000 Null Null 7698 BLAKE 2850 7839 Null 7782 CLARK 2450 7839 Null 7566 JONES 2975 7839 Null 7654 MARTIN 1250 7698 1400 7499 ALLEN 1600 7698 300 14 rows selected.
1-34
Copyright Oracle Corporation, 1998. All rights reserved.

Using SET Command Variables


SET NEWPAGE
SET NEWPAGE 3 SELECT empno, ename, mgr FROM emp /

EMPNO ENAME SAL MGR --------- ---------- --------- --------7839 KING 5000 7698 BLAKE 2850 7839 7782 CLARK 2450 7839 ... 14 rows selected.
1-35
Copyright Oracle Corporation, 1998. All rights reserved.

The TTITLE and BTITLE Commands


Display page headers and footers
TTI[TLE] [printspec [text|variable]] [OFF|ON]

Print specification:
COL n S[KIP] [n]

Variable: SQL.LNO SQL.PNO SQL.USER SQL.RELEASE

TAB n
BOLD FORMAT
1-36

LE[FT], CE[NTER], R[IGHT] SQL.CODE

Copyright Oracle Corporation, 1998. All rights reserved.

Using the TTITLE Command


SQL> TTITLE 'Salary|Report' SQL> SELECT empno, ename, sal, mgr 2 FROM emp; Mon Feb 16 Salary Report page 1

EMPNO ENAME SAL MGR --------- ---------- --------- --------7839 KING 5000 Null 7698 BLAKE 2850 7839 7782 CLARK 2450 7839 14 rows selected.

1-37

Copyright Oracle Corporation, 1998. All rights reserved.

Using the BTITLE Command


SQL> BTITLE 'Confidential' SQL> SELECT empno, ename, sal, mgr 2 FROM emp; EMPNO --------7839 ... 7876 7934 ENAME SAL MGR ---------- --------- --------KING 5000 Null

ADAMS MILLER

1100 1300

7788 7782

Confidential 14 rows selected.

1-38

Copyright Oracle Corporation, 1998. All rights reserved.

Additional COLUMN Command Options


Control display of columns and headings
COL[UMN] [{column|alias} [option]]

NEW_VALUE Prints data in the title NOPRINT CLEAR display attributes


1-39

Excludes data from output Resets column

Copyright Oracle Corporation, 1998. All rights reserved.

Using the NEW_VALUE Command


COLUMN deptno new_value deptnum FORMAT 99 TTITLE SKIP 1 CENTER 'Report for Dept:' deptnum SKIP 2 CENTER BREAK on deptno SKIP PAGE ON deptno SELECT ename, mgr, deptno, sal FROM emp ORDER BY deptno /

1-40

Copyright Oracle Corporation, 1998. All rights reserved.

Using the NOPRINT Command


COLUMN deptno NOPRINT new_value deptnum FORMAT 99 TTITLE SKIP 1 CENTER 'Report for Dept:' deptnum SKIP 2 CENTER BREAK ON deptno SKIP PAGE ON deptno SELECT ename, mgr, deptno, sal FROM emp ORDER BY deptno /

1-41

Copyright Oracle Corporation, 1998. All rights reserved.

Using the CLEAR Command


Use the CLEAR command to reset the display attributes for columns and headings to the default values.
SQL> COLUMN deptno CLEAR SQL> COLUMN dname CLEAR SQL> CLEAR BREAK

1-42

Copyright Oracle Corporation, 1998. All rights reserved.

The COMPUTE Command


Calculates and displays summary lines
COMP[UTE] [function [LABEL labelname] OF {expr|column|alias} ON {expr|column|alias|REPORT|FORM}]

Uses various standard computations, including:


AVG

COUNT
MAXIMUM MINIMUM
1-43
Copyright Oracle Corporation, 1998. All rights reserved.

Using the COMPUTE Command


BREAK ON JOB SKIP 1 COMPUTE SUM OF sal ON job SELECT job, ename, sal FROM emp WHERE job IN ('CLERK', 'ANALYST', 'SALESMAN') ORDER BY job, sal / JOB ENAME SAL --------- ---------- --------ANALYST FORD 3000 SCOTT 3000 ********* --------sum 6000 CLERK SMITH 10 rows selected.
1-44

800

Copyright Oracle Corporation, 1998. All rights reserved.

Using BREAK with COMPUTE


BREAK ON deptno SKIP 2 COMPUTE MAX OF sal ON deptno SELECT deptno, ename, sal FROM emp WHERE job IN ('CLERK', 'ANALYST', 'SALESMAN') ORDER BY deptno, sal /

DEPTNO ENAME SAL --------- ---------- --------10 MILLER 1300 ********* --------maximum 1300

20 SMITH ADAMS 10 rows selected.


1-45

800 1100

Copyright Oracle Corporation, 1998. All rights reserved.

Using LABEL with COMPUTE


BREAK ON deptno SKIP 2 COMPUTE MAX LABEL Max_Sal OF sal ON deptno SELECT deptno, ename, sal FROM emp WHERE job IN ('CLERK', 'ANALYST', 'SALESMAN') ORDER BY deptno, sal / DEPTNO --------10 ********* Max_Sal ENAME ---------MILLER SAL --------1300 --------1300

20

SMITH

800

10 rows selected.
1-46
Copyright Oracle Corporation, 1998. All rights reserved.

Example of Creating a Report Script


1 COLUMN job NOPRINT NEW_VALUE jobname FORMAT A9 2 TTITLE SKIP 1 CENTER 'Salaries for' SKIP 1 CENTER jobname SKIP 2 3 BREAK on job SKIP PAGE COMPUTE AVG LABEL '' OF sal ON job 4 5 BTITLE 'Top Secret' SELECT job, ename, hiredate, sal 6 FROM emp ORDER BY job, sal /

1-47

Copyright Oracle Corporation, 1998. All rights reserved.

Output of Report Script


1
Salaries for ANALYST ENAME ---------FORD SCOTT HIREDATE SAL --------- --------03-DEC-81 3000 09-DEC-82 3000 --------3000 Top Secret

4 3

Salaries for CLERK

ENAME HIREDATE SAL ---------- --------- --------SMITH 17-DEC-80 800 14 rows selected.
1-48
Copyright Oracle Corporation, 1998. All rights reserved.

Summary
Use the SET commands to format report output.

Use TTITLE and BTITLE commands to format page header and footer.
Calculate and print summary lines by using the COMPUTE command.

1-49

Copyright Oracle Corporation, 1998. All rights reserved.

Practice Overview
Identify various SQL*Plus commands Produce more readable output Aggregate data

1-50

Copyright Oracle Corporation, 1998. All rights reserved.

Objectives
After completing this lesson, you should be able to do the following:

Describe the SET operators


Use a SET operator to combine multiple queries into a single query

Control the order of rows returned

1-51

Copyright Oracle Corporation, 1998. All rights reserved.

The Set Operators


A B

Intersect
A B A B

Union / Union All


A B

Minus
1-52
Copyright Oracle Corporation, 1998. All rights reserved.

EMP
EMPNO DEPTNO --------7839 10 7698 30 7782 10 7566 20 7654 30 7499 30 7844 30 7900 30 7521 30 7902 20 1-53 7369 20

Tables Used in this Lesson


ENAME JOB MGR HIREDATE SAL COMM ---------- --------- --------- --------- --------- --------- -------KING BLAKE CLARK JONES MARTIN PRESIDENT MANAGER MANAGER MANAGER SALESMAN 17-NOV-81 7839 01-MAY-81 7839 09-JUN-81 7839 02-APR-81 5000 2850 1500 2975 DATE_OUT --------- -------27-NOV-81 17-JAN-81

7698NAME 28-SEP-81 1250 TITLE 1400 EMPID DEPTID ALLEN SALESMAN --------7698-------------------20-FEB-81 1600 --------300 TURNER SALESMAN 7698SPENCER 08-SEP-81 1500 OPERATOR 0 6087 20 EMP_HISTORY JAMES CLERK 7698VANDYKE 03-DEC-81 950 MANAGER 6185 10 WARD SALESMAN 7698BALFORD 22-FEB-81 1250 CLERK 500 6235 20 FORD ANALYST 7566SCOTT 03-DEC-81 3000 ANALYST 7788 20 Copyright Oracle Corporation, 1998. All rights800 reserved. SMITH CLERK 7902 17-DEC-80 7001 JEWELL ANALYST 30

22-FEB-80
05-MAY-81 10-JUN-81

Using the UNION Operator


Display the name, job title, and department of all employees. A B
SQL> 2 3 4 5 SELECT ename, job, deptno FROM emp UNION SELECT name, title, deptid FROM emp_history;

ENAME JOB DEPTNO ---------- --------- --------ADAMS CLERK 30 ALLEN SALESMAN 30 ALLEN SALESMAN 20 BALFORD CLERK 20 BLAKE MANAGER 30 ... 20 rows selected.
1-54
Copyright Oracle Corporation, 1998. All rights reserved.

Using the UNION ALL Operator


Display the names, employee numbers, and job titles of all employees.
SQL> 2 3 4 5 SELECT ename, empno, job FROM emp UNION ALL SELECT name, empid, title FROM emp_history; JOB --------PRESIDENT MANAGER MANAGER MANAGER SALESMAN A B

1-55

ENAME EMPNO ---------- --------KING 7839 BLAKE 7698 CLARK 7782 CLARK 7782 MARTIN 7654 ... 23 rows selected.

Copyright Oracle Corporation, 1998. All rights reserved.

Using the INTERSECT Operator


Display the distinct names, employee numbers, and job titles of employees found in both the EMP and EMP_HISTORY tables.
SQL> 2 3 4 5 SELECT ename, empno, job FROM emp INTERSECT SELECT name, empid, title FROM emp_history; A B

ENAME EMPNO JOB ---------- --------- --------ALLEN 7499 SALESMAN CLARK 7782 MANAGER SCOTT 7788 ANALYST
1-56
Copyright Oracle Corporation, 1998. All rights reserved.

MINUS
Display the names, employee numbers, and job titles for all employees who have left the company.
SQL> 2 3 4 5 SELECT FROM MINUS SELECT FROM name, empid, title emp_history A B

ename, empno, job emp;

NAME EMPID TITLE ---------- --------- --------BALFORD 6235 CLERK BRIGGS 7225 PAY CLERK JEWELL 7001 ANALYST SPENCER 6087 OPERATOR ... 1-57 6 rows selected. Copyright Oracle Corporation, 1998. All rights reserved.

SET Operator Rules


The expressions in the SELECT lists must match in number and datatype.

Duplicate rows are automatically eliminated except in UNION ALL.


Column names from the first query appear in the result. The output is sorted in ascending order by default except in UNION ALL.

Parentheses can be used to alter the sequence of execution.


1-58
Copyright Oracle Corporation, 1998. All rights reserved.

Matching the SELECT Statement


Display the department number, location, and hiredate for all employees.
SQL> 2 3 4 5 SELECT FROM UNION SELECT FROM deptno, TO_CHAR(null) location, hiredate emp
deptno, loc, TO_DATE(null) dept;

1-59

Copyright Oracle Corporation, 1998. All rights reserved.

Controlling the Order of Rows


Produce an English sentence using two UNION operators.
SQL> SQL> 2 3 4 5 6 7 8 9 COLUMN a_dummy NOPRINT SELECT 'to sing' "My dream", 3 a_dummy FROM dual UNION SELECT 'I''d like to teach', 1 FROM dual UNION SELECT 'the world', 2 FROM dual ORDER BY 2;

My dream ------------------------I'd like to teach the world to sing


1-60

Copyright Oracle Corporation, 1998. All rights reserved.

Summary
UNION returns all distinct rows. UNION ALL returns all rows including duplicates. INTERSECT returns all rows that both queries share. MINUS returns all distinct rows selected by the first query but not the second. ORDER BY can only appear at the very end of the statement.
1-61
Copyright Oracle Corporation, 1998. All rights reserved.

Practice Overview
In this practice you will write queries using the SET operators. Discovering alternative join methods Writing compound queries as a kind of if statement

1-62

Copyright Oracle Corporation, 1998. All rights reserved.

S-ar putea să vă placă și