sql avanzado y sql plus 41022

62
Copyright Oracle Corporation, 1998. All rights reserved. 1 1 Using SET Operators

Upload: ivan-de-la-paz

Post on 22-Oct-2015

51 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: SQL Avanzado y SQL Plus 41022

Copyright Oracle Corporation, 1998. All rights reserved.

11

Using SET OperatorsUsing SET Operators

Page 2: SQL Avanzado y SQL Plus 41022

Copyright Oracle Corporation, 1998. All rights reserved.

11

Writing Correlated Subqueries

Writing Correlated Subqueries

Page 3: SQL Avanzado y SQL Plus 41022

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

ObjectivesObjectivesAfter completing this lesson, you should After completing this lesson, you should be able to do the following: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

After completing this lesson, you should After completing this lesson, you should be able to do the following: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

Page 4: SQL Avanzado y SQL Plus 41022

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

What Is a Subquery?What Is a Subquery?

A subquery is a SELECT statement A subquery is a SELECT statement embedded in a clause of another SQL embedded in a clause of another SQL statement.statement.

A subquery is a SELECT statement A subquery is a SELECT statement embedded in a clause of another SQL embedded in a clause of another SQL statement.statement.

SELECT . . . FROM . . .WHERE . . .

(SELECT . . .FROM . . .WHERE . . .)

MainMainQueryQuery

SubquerySubquery

Page 5: SQL Avanzado y SQL Plus 41022

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

SubqueriesSubqueries

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

• The result of the subquery is used by the main query (outer query).

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

• The result of the subquery is used by the main query (outer query).SELECT select_listFROM tableWHERE expr operator (SELECT select_list

FROM table);

Page 6: SQL Avanzado y SQL Plus 41022

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

2975

SQL> SELECT ename 2 FROM emp 3 WHERE sal > 4 (SELECT sal 5 FROM emp 6 WHERE empno = 7566);

Using a SubqueryUsing a Subquery

ENAME ---------- KING FORD SCOTT

Page 7: SQL Avanzado y SQL Plus 41022

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

Correlated SubqueriesCorrelated Subqueries

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

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

GETcandidate row

EXECUTEinner query using candidate row value

USEvalue(s) from inner query to qualify

candidate row

Page 8: SQL Avanzado y SQL Plus 41022

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

Correlated SubqueriesCorrelated 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 subquery references a column from a table in the parent query.a table in the parent query.The subquery references a column from subquery references a column from a table in the parent query.a table in the parent query.

Page 9: SQL Avanzado y SQL Plus 41022

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

Using Correlated SubqueriesUsing Correlated Subqueries

Each time the outer queryis processed the

inner query is evaluated.

SQL> SELECT empno, sal, deptno 2 FROM emp outer 3 WHERE sal > (SELECT AVG(sal) 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.

Find all employees who make more than Find all employees who make more than the average salary in their department.the average salary in their department.Find all employees who make more than Find all employees who make more than the average salary in their department.the average salary in their department.

Page 10: SQL Avanzado y SQL Plus 41022

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

Using the EXISTS OperatorUsing 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.

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

Page 11: SQL Avanzado y SQL Plus 41022

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

Find employees who have at least one person reporting to them.

Using the EXISTS OperatorUsing the EXISTS Operator

EMPNO ENAME JOB DEPTNO--------- ---------- --------- --------- 7839 KING PRESIDENT 10 7698 BLAKE MANAGER 30 7782 CLARK MANAGER 10 7566 JONES MANAGER 20...6 rows selected.

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);

Page 12: SQL Avanzado y SQL Plus 41022

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

Find all departments that do not have any employees.

Using the NOT EXISTS OperatorUsing the NOT EXISTS Operator

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

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

SQL> SELECT deptno, dname 2 FROM dept d 3 WHERE NOT EXISTS (SELECT '1' 4 FROM emp e 5 WHERE d.deptno = e.deptno);

Page 13: SQL Avanzado y SQL Plus 41022

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

Correlated UPDATECorrelated UPDATE

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

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

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

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

Page 14: SQL Avanzado y SQL Plus 41022

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

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

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

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

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

Correlated DELETECorrelated DELETE

Page 15: SQL Avanzado y SQL Plus 41022

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

SummarySummary

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

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

Page 16: SQL Avanzado y SQL Plus 41022

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

Practice OverviewPractice Overview

• Writing correlated subqueries

• Using the EXISTS operator

• Writing correlated subqueries

• Using the EXISTS operator

Page 17: SQL Avanzado y SQL Plus 41022

Copyright Oracle Corporation, 1998. All rights reserved.

11

Generating Scripts to Generate Scripts

Generating Scripts to Generate Scripts

Page 18: SQL Avanzado y SQL Plus 41022

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

ObjectivesObjectives

After completing this lesson, you should After completing this lesson, you should be able to do the following: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

After completing this lesson, you should After completing this lesson, you should be able to do the following: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

Page 19: SQL Avanzado y SQL Plus 41022

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

Using SQL to Generate SQLUsing SQL to Generate SQL

SQLSQL

Data

Data

Dictio

nary

Dictio

nary

SQL ScriptSQL Script

Page 20: SQL Avanzado y SQL Plus 41022

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

Creating a Basic ScriptCreating a Basic Script

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

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

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

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

Page 21: SQL Avanzado y SQL Plus 41022

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

Controlling the EnvironmentControlling the Environment

SET ECHO OFF SET FEEDBACK OFFSET PAGESIZE 0

SPOOL droptab.sql

SPOOL OFF

SET ECHO ONSET FEEDBACK ONSET PAGESIZE 24

SET ECHO OFF SET FEEDBACK OFFSET PAGESIZE 0

SPOOL droptab.sql

SPOOL OFF

SET ECHO ONSET FEEDBACK ONSET PAGESIZE 24

Set system variables to Set system variables to appropriate valuesappropriate values

Set system variables back to Set system variables back to default valuedefault value

SQL STATEMENT

Page 22: SQL Avanzado y SQL Plus 41022

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

The Complete PictureThe Complete Picture

SET ECHO OFF SET FEEDBACK OFFSET PAGESIZE 0

SPOOL dropem.sql

SELECT 'DROP TABLE ' || object_name || ';'FROM user_objectsWHERE object_type = 'TABLE';

SPOOL OFF

SET ECHO ONSET FEEDBACK ONSET PAGESIZE 24

SET ECHO OFF SET FEEDBACK OFFSET PAGESIZE 0

SPOOL dropem.sql

SELECT 'DROP TABLE ' || object_name || ';'FROM user_objectsWHERE object_type = 'TABLE';

SPOOL OFF

SET ECHO ONSET FEEDBACK ONSET PAGESIZE 24

Page 23: SQL Avanzado y SQL Plus 41022

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

Dumping the Contents of a Table to a File

Dumping the Contents of a Table to a File

SET HEADING OFF ECHO OFF FEEDBACK OFFSET PAGESIZE 0

SPOOL data.sql

SELECT 'INSERT INTO dept VALUES ('|| deptno||','|| ''''||dname||''''||','|| ''''||loc||''''||');'FROM dept;

SPOOL OFF

SET HEADING ON ECHO OFF FEEDBACK ONSET PAGESIZE 24

SET HEADING OFF ECHO OFF FEEDBACK OFFSET PAGESIZE 0

SPOOL data.sql

SELECT 'INSERT INTO dept VALUES ('|| deptno||','|| ''''||dname||''''||','|| ''''||loc||''''||');'FROM dept;

SPOOL OFF

SET HEADING ON ECHO OFF FEEDBACK ONSET PAGESIZE 24

Page 24: SQL Avanzado y SQL Plus 41022

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

Dumping the Contents of a Table to a File

Dumping the Contents of a Table to a File

Source

''''X''''

''''

''''||dname||''''

Result

'X'

'

'BOSTON'

Page 25: SQL Avanzado y SQL Plus 41022

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

Generating a Dynamic PredicateGenerating a Dynamic Predicate

Statement 1Statement 1

Statement 2Statement 2

Page 26: SQL Avanzado y SQL Plus 41022

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

SummarySummary

• You can select virtually anything.

• Script files often use the data dictionary.

• You use the SPOOL command to capture output in a file.

• You can select virtually anything.

• Script files often use the data dictionary.

• You use the SPOOL command to capture output in a file.

Page 27: SQL Avanzado y SQL Plus 41022

1-27 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

Page 28: SQL Avanzado y SQL Plus 41022

Copyright Oracle Corporation, 1998. All rights reserved.

11

Reporting Using SQL*PlusReporting Using SQL*Plus

Page 29: SQL Avanzado y SQL Plus 41022

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

ObjectivesObjectives

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

• Format output with the SET commands

• Add header and footer information

• Aggregate data in the output

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

• Format output with the SET commands

• Add header and footer information

• Aggregate data in the output

Page 30: SQL Avanzado y SQL Plus 41022

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

SQL*Plus SET Command Variables

SQL*Plus SET Command Variables

The SET command is a system variable The SET command is a system variable that affects the way SQL*Plus runs that affects the way SQL*Plus runs commands. The following conditions are commands. The following conditions are controlled by system variables: 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

The SET command is a system variable The SET command is a system variable that affects the way SQL*Plus runs that affects the way SQL*Plus runs commands. The following conditions are commands. The following conditions are controlled by system variables: 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

Page 31: SQL Avanzado y SQL Plus 41022

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

Additional SET Command VariablesAdditional SET Command Variables

• RECSEP

• RECSEPCHAR

• SPACE

• UNDERLINE

• WRAP

• NULL

• HEADSEP

• NEWPAGE

• RECSEP

• RECSEPCHAR

• SPACE

• UNDERLINE

• WRAP

• NULL

• HEADSEP

• NEWPAGE

Page 32: SQL Avanzado y SQL Plus 41022

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

Using SET Command VariablesUsing SET Command Variables

SET RECSEP and SET RECSEPCHARSET RECSEP and SET RECSEPCHARSET RECSEP and SET RECSEPCHARSET RECSEP and SET RECSEPCHARSET RECSEP EACHSET RECSEPCHAR _SELECT empno, ename, job, mgr, sal FROM empWHERE ename='BLAKE'/

EMPNO ENAME JOB MGR SAL--------- ---------- --------- --------- --------- 7839 KING PRESIDENT 5000__________________________________________________ 7782 CLARK MANAGER 7839 2450__________________________________________________ 7934 MILLER CLERK 7782 1300__________________________________________________

Page 33: SQL Avanzado y SQL Plus 41022

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

Using SET Command VariablesUsing SET Command Variables

SET SPACE and SET UNDERLINESET SPACE and SET UNDERLINESET SPACE and SET UNDERLINESET SPACE and SET UNDERLINE

EMPNO ENAME SAL MGR========= ========== ========= ========= 7839 KING 5000 7698 BLAKE 2850 7839 7782 CLARK 2450 7839 7566 JONES 2975 7839 7654 MARTIN 1250 7698…14 rows selected.

SET SPACE 2SET UNDERLINE =SELECT empno, ename, sal, mgrFROM emp/

Page 34: SQL Avanzado y SQL Plus 41022

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

Using SET Command VariablesUsing SET Command Variables

SET NULL NullSELECT empno, ename, sal, mgr, commFROM emp/

SET NULLSET NULLSET NULLSET NULL

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.

Page 35: SQL Avanzado y SQL Plus 41022

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

Using SET Command VariablesUsing SET Command Variables

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

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

SET NEWPAGESET NEWPAGESET NEWPAGESET NEWPAGE

Page 36: SQL Avanzado y SQL Plus 41022

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

The TTITLE and BTITLE CommandsThe TTITLE and BTITLE Commands

Display page headers and footersDisplay page headers and footersDisplay page headers and footersDisplay page headers and footers

TTI[TLE] [printspec [text|variable]] [OFF|ON]TTI[TLE] [printspec [text|variable]] [OFF|ON]

Print specification:

• COL n

• S[KIP] [n]

• TAB n

• LE[FT], CE[NTER], R[IGHT]

• BOLD

• FORMAT

Print specification:

• COL n

• S[KIP] [n]

• TAB n

• LE[FT], CE[NTER], R[IGHT]

• BOLD

• FORMAT

Variable:

• SQL.LNO

• SQL.PNO

• SQL.USER

• SQL.CODE

• SQL.RELEASE

Variable:

• SQL.LNO

• SQL.PNO

• SQL.USER

• SQL.CODE

• SQL.RELEASE

Page 37: SQL Avanzado y SQL Plus 41022

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

Using the TTITLE CommandUsing the TTITLE Command

SQL> TTITLE 'Salary|Report'SQL> SELECT empno, ename, sal, mgr 2 FROM emp;

Mon Feb 16 page 1 Salary Report

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

Page 38: SQL Avanzado y SQL Plus 41022

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

Using the BTITLE CommandUsing the BTITLE Command

SQL> BTITLE 'Confidential'SQL> SELECT empno, ename, sal, mgr 2 FROM emp;

EMPNO ENAME SAL MGR--------- ---------- --------- --------- 7839 KING 5000 Null... 7876 ADAMS 1100 7788 7934 MILLER 1300 7782

Confidential

14 rows selected.

Page 39: SQL Avanzado y SQL Plus 41022

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

Additional COLUMN Command Options

Additional COLUMN Command Options

Control display of columns and headingsControl display of columns and headings

• NEW_VALUE Prints data in the title

• NOPRINT Excludes data from output

• CLEAR Resets column display attributes

Control display of columns and headingsControl display of columns and headings

• NEW_VALUE Prints data in the title

• NOPRINT Excludes data from output

• CLEAR Resets column display attributes

COL[UMN] [{column|alias} [option]]COL[UMN] [{column|alias} [option]]

Page 40: SQL Avanzado y SQL Plus 41022

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

Using the NEW_VALUE CommandUsing the NEW_VALUE Command

COLUMN deptno new_value deptnum FORMAT 99TTITLE SKIP 1 CENTER 'Report for Dept:' deptnum -SKIP 2 CENTERBREAK on deptno SKIP PAGE ON deptnoSELECT ename, mgr, deptno, salFROM empORDER BY deptno/

Page 41: SQL Avanzado y SQL Plus 41022

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

Using the NOPRINT CommandUsing the NOPRINT Command

COLUMN deptno NOPRINT new_value deptnum FORMAT 99TTITLE SKIP 1 CENTER 'Report for Dept:' deptnum -SKIP 2 CENTERBREAK ON deptno SKIP PAGE ON deptnoSELECT ename, mgr, deptno, salFROM empORDER BY deptno/

Page 42: SQL Avanzado y SQL Plus 41022

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

Using the CLEAR CommandUsing the CLEAR Command

Use the CLEAR command to reset the Use the CLEAR command to reset the display attributes for columns and display attributes for columns and headings to the default values.headings to the default values.

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

Page 43: SQL Avanzado y SQL Plus 41022

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

The COMPUTE CommandThe COMPUTE Command

• Calculates and displays summary lines

• Uses various standard computations, including:

– AVG

– COUNT

– MAXIMUM

– MINIMUM

• Calculates and displays summary lines

• Uses various standard computations, including:

– AVG

– COUNT

– MAXIMUM

– MINIMUM

COMP[UTE] [function [LABEL labelname] … OF {expr|column|alias} … ON {expr|column|alias|REPORT|FORM}]

COMP[UTE] [function [LABEL labelname] … OF {expr|column|alias} … ON {expr|column|alias|REPORT|FORM}]

Page 44: SQL Avanzado y SQL Plus 41022

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

Using the COMPUTE CommandUsing the COMPUTE Command

BREAK ON JOB SKIP 1COMPUTE SUM OF sal ON jobSELECT job, ename, salFROM empWHERE job IN ('CLERK', 'ANALYST', 'SALESMAN')ORDER BY job, sal/

JOB ENAME SAL--------- ---------- ---------ANALYST FORD 3000 SCOTT 3000********* ---------sum 6000

CLERK SMITH 800…10 rows selected.

Page 45: SQL Avanzado y SQL Plus 41022

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

Using BREAK with COMPUTEUsing BREAK with COMPUTE

BREAK ON deptno SKIP 2COMPUTE MAX OF sal ON deptnoSELECT deptno, ename, salFROM empWHERE job IN ('CLERK', 'ANALYST', 'SALESMAN')ORDER BY deptno, sal/

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

20 SMITH 800 ADAMS 1100…10 rows selected.

Page 46: SQL Avanzado y SQL Plus 41022

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

Using LABEL with COMPUTEUsing LABEL with COMPUTE

BREAK ON deptno SKIP 2COMPUTE MAX LABEL Max_Sal OF sal ON deptnoSELECT deptno, ename, salFROM empWHERE job IN ('CLERK', 'ANALYST', 'SALESMAN')ORDER BY deptno, sal/

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

20 SMITH 800…10 rows selected.

Page 47: SQL Avanzado y SQL Plus 41022

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

Example of Creating a Report Script

Example of Creating a Report Script

COLUMN job NOPRINT NEW_VALUE jobname FORMAT A9TTITLE -SKIP 1 CENTER 'Salaries for' - SKIP 1 CENTER jobname -SKIP 2BREAK on job SKIP PAGE COMPUTE AVG LABEL '' OF sal ON jobBTITLE 'Top Secret'SELECT job, ename, hiredate, salFROM empORDER BY job, sal/

4

6

1

3

2

5

Page 48: SQL Avanzado y SQL Plus 41022

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

Output of Report ScriptOutput of Report Script Salaries for ANALYST

ENAME HIREDATE SAL---------- --------- ---------FORD 03-DEC-81 3000SCOTT 09-DEC-82 3000 --------- 3000

Top Secret

Salaries for CLERK

ENAME HIREDATE SAL---------- --------- ---------SMITH 17-DEC-80 800…14 rows selected.

1

3

2

5

4

6

Page 49: SQL Avanzado y SQL Plus 41022

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

SummarySummary

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

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

Page 50: SQL Avanzado y SQL Plus 41022

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

Practice Overview

• Identify various SQL*Plus commands

• Produce more readable output

• Aggregate data

Page 51: SQL Avanzado y SQL Plus 41022

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

ObjectivesObjectives

After completing this lesson, you should After completing this lesson, you should be able to do the following: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

After completing this lesson, you should After completing this lesson, you should be able to do the following: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

Page 52: SQL Avanzado y SQL Plus 41022

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

The Set OperatorsThe Set Operators

IntersectIntersect

AA BB

AA BB

UnionUnion / Union All/ Union All

AA BB

AA BB

MinusMinus

Page 53: SQL Avanzado y SQL Plus 41022

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

Tables Used in this LessonTables Used in this Lesson EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO--------- ---------- --------- --------- --------- --------- --------- --------- 7839 KING PRESIDENT 17-NOV-81 5000 10 7698 BLAKE MANAGER 7839 01-MAY-81 2850 30 7782 CLARK MANAGER 7839 09-JUN-81 1500 10 7566 JONES MANAGER 7839 02-APR-81 2975 20 7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30 7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30 7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30 7900 JAMES CLERK 7698 03-DEC-81 950 30 7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30 7902 FORD ANALYST 7566 03-DEC-81 3000 20 7369 SMITH CLERK 7902 17-DEC-80 800 20 7788 SCOTT ANALYST 7566 09-DEC-82 3000 20 7876 ADAMS CLERK 7788 12-JAN-83 1100 20 7934 MILLER CLERK 7782 23-JAN-82 1300 10

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO--------- ---------- --------- --------- --------- --------- --------- --------- 7839 KING PRESIDENT 17-NOV-81 5000 10 7698 BLAKE MANAGER 7839 01-MAY-81 2850 30 7782 CLARK MANAGER 7839 09-JUN-81 1500 10 7566 JONES MANAGER 7839 02-APR-81 2975 20 7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30 7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30 7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30 7900 JAMES CLERK 7698 03-DEC-81 950 30 7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30 7902 FORD ANALYST 7566 03-DEC-81 3000 20 7369 SMITH CLERK 7902 17-DEC-80 800 20 7788 SCOTT ANALYST 7566 09-DEC-82 3000 20 7876 ADAMS CLERK 7788 12-JAN-83 1100 20 7934 MILLER CLERK 7782 23-JAN-82 1300 10

EMPEMP

EMP_HISTORYEMP_HISTORY

EMPID NAME TITLE DATE_OUT DEPTID--------- -------------------- --------- --------- --------- 6087 SPENCER OPERATOR 27-NOV-81 20 6185 VANDYKE MANAGER 17-JAN-81 10 6235 BALFORD CLERK 22-FEB-80 20 7788 SCOTT ANALYST 05-MAY-81 20 7001 JEWELL ANALYST 10-JUN-81 30 7499 ALLEN SALESMAN 01-AUG-80 20 7225 BRIGGS PAY CLERK 27-NOV-81 10 7782 CLARK MANAGER 12-FEB-80 10 7356 WILD DIRECTOR 01-NOV-81 10

EMPID NAME TITLE DATE_OUT DEPTID--------- -------------------- --------- --------- --------- 6087 SPENCER OPERATOR 27-NOV-81 20 6185 VANDYKE MANAGER 17-JAN-81 10 6235 BALFORD CLERK 22-FEB-80 20 7788 SCOTT ANALYST 05-MAY-81 20 7001 JEWELL ANALYST 10-JUN-81 30 7499 ALLEN SALESMAN 01-AUG-80 20 7225 BRIGGS PAY CLERK 27-NOV-81 10 7782 CLARK MANAGER 12-FEB-80 10 7356 WILD DIRECTOR 01-NOV-81 10

Page 54: SQL Avanzado y SQL Plus 41022

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

Using the UNION OperatorUsing the UNION OperatorDisplay the name, job title, and department Display the name, job title, and department of all employees.of all employees.Display the name, job title, and department Display the name, job title, and department of all employees.of all employees.

ENAME JOB DEPTNO---------- --------- ---------ADAMS CLERK 30ALLEN SALESMAN 30ALLEN SALESMAN 20BALFORD CLERK 20BLAKE MANAGER 30...20 rows selected.

SQL> SELECT ename, job, deptno 2 FROM emp 3 UNION 4 SELECT name, title, deptid 5 FROM emp_history;

AA BB

Page 55: SQL Avanzado y SQL Plus 41022

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

Using the UNION ALL OperatorUsing the UNION ALL OperatorDisplay the names, employee numbers, and Display the names, employee numbers, and job titles of all employees. job titles of all employees. Display the names, employee numbers, and Display the names, employee numbers, and job titles of all employees. job titles of all employees. SQL> SELECT ename, empno, job 2 FROM emp 3 UNION ALL 4 SELECT name, empid, title 5 FROM emp_history;

ENAME EMPNO JOB---------- --------- ---------KING 7839 PRESIDENTBLAKE 7698 MANAGERCLARK 7782 MANAGERCLARK 7782 MANAGERMARTIN 7654 SALESMAN...23 rows selected.

AA BB

Page 56: SQL Avanzado y SQL Plus 41022

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

Using the INTERSECT OperatorUsing the INTERSECT Operator

Display the distinct names, employee Display the distinct names, employee numbers, and job titles of employees found numbers, and job titles of employees found in both the EMP and EMP_HISTORY tables.in both the EMP and EMP_HISTORY tables.

Display the distinct names, employee Display the distinct names, employee numbers, and job titles of employees found numbers, and job titles of employees found in both the EMP and EMP_HISTORY tables.in both the EMP and EMP_HISTORY tables.

ENAME EMPNO JOB---------- --------- ---------ALLEN 7499 SALESMANCLARK 7782 MANAGERSCOTT 7788 ANALYST

ENAME EMPNO JOB---------- --------- ---------ALLEN 7499 SALESMANCLARK 7782 MANAGERSCOTT 7788 ANALYST

SQL> SELECT ename, empno, job 2 FROM emp 3 INTERSECT 4 SELECT name, empid, title 5 FROM emp_history;

AA BB

Page 57: SQL Avanzado y SQL Plus 41022

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

MINUSMINUS

Display the names, employee numbers, and Display the names, employee numbers, and job titles for all employees who have left the job titles for all employees who have left the company.company.

Display the names, employee numbers, and Display the names, employee numbers, and job titles for all employees who have left the job titles for all employees who have left the company.company.

NAME EMPID TITLE---------- --------- ---------BALFORD 6235 CLERKBRIGGS 7225 PAY CLERKJEWELL 7001 ANALYSTSPENCER 6087 OPERATOR...6 rows selected.

NAME EMPID TITLE---------- --------- ---------BALFORD 6235 CLERKBRIGGS 7225 PAY CLERKJEWELL 7001 ANALYSTSPENCER 6087 OPERATOR...6 rows selected.

SQL> SELECT name, empid, title 2 FROM emp_history 3 MINUS 4 SELECT ename, empno, job 5 FROM emp;

AA BB

Page 58: SQL Avanzado y SQL Plus 41022

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

SET Operator RulesSET 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.

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

Page 59: SQL Avanzado y SQL Plus 41022

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

Matching the SELECTStatement

Matching the SELECTStatement

SQL> SELECT deptno, TO_CHAR(null) location, hiredate 2 FROM emp 3 UNION 4 SELECT deptno, loc, TO_DATE(null) 5 FROM dept;

SQL> SELECT deptno, TO_CHAR(null) location, hiredate 2 FROM emp 3 UNION 4 SELECT deptno, loc, TO_DATE(null) 5 FROM dept;

Display the department number, location, Display the department number, location, and hiredate for all employees.and hiredate for all employees.Display the department number, location, Display the department number, location, and hiredate for all employees.and hiredate for all employees.

Page 60: SQL Avanzado y SQL Plus 41022

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

Controlling the Order of RowsControlling the Order of Rows

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

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

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

SQL> COLUMN a_dummy NOPRINTSQL> SELECT 'to sing' "My dream", 3 a_dummy 2 FROM dual 3 UNION 4 SELECT 'I''d like to teach', 1 5 FROM dual 6 UNION 7 SELECT 'the world', 2 8 FROM dual 9 ORDER BY 2;

Page 61: SQL Avanzado y SQL Plus 41022

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

SummarySummary

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

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

Page 62: SQL Avanzado y SQL Plus 41022

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

Practice OverviewPractice Overview

In this practice you will write queries In this practice you will write queries using the SET operators.using the SET operators.

• Discovering alternative join methods

• Writing compound queries as a kind of if statement

In this practice you will write queries In this practice you will write queries using the SET operators.using the SET operators.

• Discovering alternative join methods

• Writing compound queries as a kind of if statement