Вы находитесь на странице: 1из 76

Introduction to Oracle9i: SQL

Additional Practices •Volume 3

40049GC10

Production 1.0

June 2001

D33053

Introduction to Oracle9 i : SQL Additional Practices •Volume 3 40049GC10 Production 1.0 June 2001 D33053

Authors

Nancy Greenberg

Priya Nathan

Technical Contributors and Reviewers

Josephine Turner Martin Alvarez Anna Atkinson Don Bates Marco Berbeek Andrew Brannigan Michael Gerlach Sharon Gray Rosita Hanoman Mozhe Jalali Sarah Jones Charbel Khouri Christopher Lawless Diana Lorentz Nina Minchen Cuong Nguyen Daphne Nougier Patrick Odell Laura Pezzini Stacey Procter Maribel Renau Bryan Roberts Helen Robertson Sunshine Salmon Casa Sharif Bernard Soleillant Craig Spoonemore Ruediger Steffan Karla Villasenor Andree Wheeley Lachlan Williams

Publisher

Sheryl Domingue

Copyright © Oracle Corporation, 2000, 2001. All rights reserved.

This documentation contains proprietary information of Oracle Corporation. It is provided under a license agreement containing restrictions on use and disclosure and is also protected by copyright law. Reverse engineering of the software is prohibited. If this documentation is delivered to a U.S. Government Agency of the Department of Defense, then it is delivered with Restricted Rights and the following legend is applicable:

Restricted Rights Legend

Use, duplication or disclosure by the Government is subject to restrictions for commercial computer software and shall be deemed to be Restricted Rights software under Federal law, as set forth in subparagraph (c)(1)(ii) of DFARS 252.227-7013, Rights in Technical Data and Computer Software (October 1988).

This material or any portion of it may not be copied in any form or by any means without the express prior written permission of Oracle Corporation. Any other copying is a violation of copyright law and may result in civil and/or criminal penalties.

If this documentation is delivered to a U.S. Government Agency not within the Department of Defense, then it is delivered with “Restricted Rights,”as defined in FAR 52.227-14, Rights in Data-General, including Alternate III (June 1987).

The information in this document is subject to change without notice. If you find any problems in the documentation, please report them in writing to Education Products, Oracle Corporation, 500 Oracle Parkway, Box SB-6, Redwood Shores, CA 94065. Oracle Corporation does not warrant that this document is error-free.

Oracle and all references to Oracle products are trademarks or registered trademarks of Oracle Corporation.

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

Contents

Preface Curriculum Map

Introduction

Objectives I-2

Oracle9i I-3

Oracle9i Application Server

Oracle9i Database

Oracle9i: Object Relational Database Management System

Oracle Internet Platform

System Development Life Cycle

Data Storage on Different Media

Relational Database Concept

Definition of a Relational Database

Data Models

Entity Relationship Model

Entity Relationship Modeling Conventions

Relating Multiple Tables

Relational Database Terminology

Relational Database Properties

Communicating with a RDBMS Using SQL

Relational Database Management System

SQL Statements

Tables Used in the Course Summary I-26

I-16

I-5

I-6

I-9

I-10

I-12

I-13

I-14

I-15

I-17

I-19

I-20

I-21

I-22

I-23

I-24

I-25

I-8

1 Writing Basic SQL SELECT Statements Objectives 1-2

Capabilities of SQL SELECT Statements

Basic SELECT Statement

1-4

iii

1-3

Selecting All Columns

Selecting Specific Columns

Writing SQL Statements Column Heading Defaults

Arithmetic Expressions

Using Arithmetic Operators

Operator Precedence Using Parentheses Defining a Null Value

Null Values in Arithmetic Expressions

Defining a Column Alias Using Column Aliases Concatenation Operator

Using the Concatenation Operator

Literal Character Strings

Using Literal Character Strings

Duplicate Rows

Eliminating Duplicate Rows

SQL and iSQL*Plus Interaction

SQL Statements versus iSQL*Plus Commands

Overview of iSQL*Plus Logging In to iSQL*Plus

1-5

1-6

1-7

1-8

1-9

1-11

1-10

1-13

1-14

1-15

1-16

1-17

1-18

1-20

1-19

1-21

1-22

1-23

1-24

1-26

1-27

1-25

The iSQL*Plus Environment

1-28

Displaying Table Structure

1-29

Interacting with Script Files

1-31

Summary 1-34 Practice 1 Overview

1-35

iv

2 Restricting and Sorting Data

Objectives

2-2

Limiting Rows Using a Selection

2-3

Limiting the Rows Selected

2-4

Using the WHERE Clause

2-5

Character Strings and Dates

2-6

Comparison Conditions

2-7

Using Comparison Conditions

2-8

Other Comparison Conditions

2-9

Using the BETWEEN Condition

Using the IN Condition

2-11

2-10

Using the LIKE Condition

2-12

Using the NULL Conditions

2-14

Logical Conditions

2-15

Using the AND Operator

Using the OR Operator

Using the NOT Operator

2-16

2-17

2-18

Rules of Precedence

2-19

ORDER BY Clause

2-22

Sorting in Descending Order

2-23

Sorting by Column Alias

2-24

Sorting by Multiple Columns

Summary

2-26

Practice 2 Overview

2-27

2-25

3 Single-Row Functions

Objectives

3-2

SQL Functions

3-3

Two Types of SQL Functions

3-4

Single-Row Functions

3-5

Character Functions

3-7

Case Manipulation Functions

3-9

Using Case Manipulation Functions

Character-Manipulation Functions

3-10

3-11

Using the Character-Manipulation Functions

Number Functions

3-13

3-12

Using the ROUND Function

3-14

Using the TRUNC Function

3-15

Using the MOD Function

3-16

Working with Dates

Arithmetic with Dates

3-17

3-19

Using Arithmetic Operators with Dates

Date Functions

3-21

Using Date Functions

3-22

Practice 3, Part 1 Overview

Conversion Functions

3-25

3-24

3-20

Implicit Data-Type Conversion

3-26

Explicit Data-Type Conversion

3-28

Using the TO_CHAR Function with Dates

3-31

Elements of the Date Format Model

3-32

Using the TO_CHAR Function with Dates

3-36

Using the TO_CHAR Function with Numbers

3-37

Using the TO_NUMBER and TO_DATE Functions

RR Date Format

3-40

Example of RR Date Format

3-41

Nesting Functions

3-42

General Functions

3-44

NVL Function

3-45

Using the NVL Function

3-46

Using the NVL2 Function

3-47

Using the NULLIF Function

3-48

Using the COALESCE Function

Conditional Expressions

3-51

3-49

The CASE Expression

3-52

Using the CASE Expression

The DECODE Function

3-54

3-53

Using the DECODE Function

Summary

3-57

Practice 3, Part 2 Overview

3-55

3-58

3-39

4 Displaying Data from Multiple Tables

Objectives

4-2

Obtaining Data from Multiple Tables

4-3

Cartesian Products

4-4

Generating a Cartesian Product

4-5

Types of Joins

4-6

Joining Tables Using Oracle Syntax

4-7

vii

What Is an Equijoin?

4-8

Retrieving Records with Equijoins

4-9

Additional Search Conditions Using the AND Operator

Qualifying Ambiguous Column Names

Using Table Aliases

4-12

Joining More than Two Tables

Nonequijoins

4-14

4-13

Retrieving Records with Nonequijoins

Outer Joins

4-16

Outer Joins Syntax

Using Outer Joins

Self Joins

4-19

4-17

4-18

Joining a Table to Itself

4-20

Practice 4, Part 1 Overview

4-21

Joining Tables Using SQL: 1999 Syntax

Creating Cross Joins

Creating Natural Joins

4-23

4-24

4-11

4-15

4-22

4-10

Retrieving Records with Natural Joins

4-25

Creating Joins with the USING Clause

4-26

Retrieving Records with the USING Clause

4-27

Creating Joins with the ON Clause

4-28

Retrieving Records with the ON Clause

4-29

Creating Three-Way Joins with the ON Clause

INNER versus OUTER Joins

4-31

4-30

LEFT OUTER JOIN

RIGHT OUTER JOIN

4-32

4-33

viii

FULL OUTER JOIN

4-34

Additional Conditions

Summary

4-36

4-35

Practice 4, Part 2 Overview

4-37

5 Aggregating Data Using Group Functions

Objectives

5-2

What Are Group Functions?

5-3

Types of Group Functions

5-4

Group Functions Syntax

5-5

Using the AVG and SUM Functions

5-6

Using the MIN and MAX Functions

5-7

Using the COUNT Function

5-8

Using the DISTINCT Keyword

5-10

Group Functions and Null Values

5-11

Using the NVL Function with Group Functions

Creating Groups of Data

5-13

5-12

Creating Groups of Data: GROUP BY Clause Syntax

Using the GROUP BY Clause

5-15

Grouping by More Than One Column

5-17

Using the GROUP BY Clause on Multiple Columns

Illegal Queries Using Group Functions

Excluding Group Results

5-21

5-19

Excluding Group Results: The HAVING Clause

Using the HAVING Clause

Nesting Group Functions

Summary

5-26

Practice 5 Overview

5-27

5-23

5-25

ix

5-22

5-14

5-18

6 Subqueries

Objectives

6-2

Using a Subquery to Solve a Problem

6-3

Subquery Syntax

6-4

Using a Subquery

6-5

Guidelines for Using Subqueries

6-6

Types of Subqueries

6-7

 

Single-Row Subqueries

6-8

Executing Single-Row Subqueries

6-9

Using Group Functions in a Subquery

6-10

The HAVING Clause with Subqueries

6-11

What Is Wrong with This Statement?

6-12

Will This Statement Return Rows?

Multiple-Row Subqueries

6-14

6-13

Using the ANY Operator in Multiple-Row Subqueries

Using the ALL Operator in Multiple-Row Subqueries

Null Values in a Subquery

Summary

6-18

Practice 6 Overview

6-19

6-17

6-15

6-16

7 Producing Readable Output with iSQL*Plus

Objectives

7-2

Substitution Variables

7-3

Using the & Substitution Variable

7-5

Character and Date Values with Substitution Variables

Specifying Column Names, Expressions, and Text

x

7-8

7-7

Defining Substitution Variables

7-10

DEFINE and UNDEFINE Commands

7-11

Using the DEFINE Command with & Substitution Variable

Using the VERIFY Command

7-14

Customizing the iSQL*Plus Environment

SET Command Variables

7-16

iSQL*Plus Format Commands

The COLUMN Command

7-18

Using the COLUMN Command

COLUMN Format Models

7-20

7-17

7-19

7-15

Using the BREAK Command

7-21

Using the TTITLE and BTITLE Commands

Creating a Script File to Run a Report

Sample Report

Summary

7-26

7-25

Practice 7 Overview

7-27

7-23

7-22

8 Manipulating Data

Objectives

8-2

Data Manipulation Language

Adding a New Row to a Table

8-3

8-4

The INSERT Statement Syntax

8-5

Inserting New Rows

8-6

Inserting Rows with Null Values

8-7

Inserting Special Values

8-8

Inserting Specific Date Values

8-9

xi

7-12

Creating a Script

8-10

Copying Rows from Another Table

Changing Data in a Table

8-12

8-11

The UPDATE Statement Syntax

8-13

Updating Rows in a Table

8-14

Updating Two Columns with a Subquery

8-15

Updating Rows Based on Another Table

8-16

Updating Rows: Integrity Constraint Error

Removing a Row from a Table

The DELETE Statement

8-19

8-18

8-17

Deleting Rows from a Table

8-20

Deleting Rows Based on Another Table

8-21

Deleting Rows: Integrity Constraint Error

8-22

Using a Subquery in an INSERT Statement

8-23

Using the WITH CHECK OPTION Keyword on DML Statements

Overview of the Explict Default Feature

Using Explicit Default Values

The MERGE Statement

8-28

8-27

8-26

MERGE Statement Syntax

8-29

Merging Rows

8-30

Database Transactions

8-32

Advantages of COMMIT and ROLLBACK Statements

Controlling Transactions

8-35

Rolling Back Changes to a Marker

8-36

8-34

Implicit Transaction Processing

8-37

State of the Data Before COMMIT or ROLLBACK

8-38

8-25

Committing Data

8-40

State of the Data After ROLLBACK

Statement-Level Rollback

8-42

8-41

Read Consistency

8-43

Implementation of Read Consistency

Locking

8-45

Implicit Locking

Summary

8-47

8-46

Practice 8 Overview

8-48

8-44

9 Creating and Managing Tables

Objectives

9-2

Database Objects

Naming Rules

9-4

9-3

The CREATE TABLE Statement

9-5

Referencing Another User’s Tables

The DEFAULT Option

Creating Tables

9-8

9-7

9-6

Tables in the Oracle Database

9-9

Querying the Data Dictionary

9-10

Data Types

9-11

Datetime Data Types

9-13

TIMESTAMP WITH TIME ZONE Data Type

TIMESTAMP WITH LOCAL TIME Data Type

9-15

9-16

INTERVAL YEAR TO MONTH Data Type

9-17

Creating a Table by Using a Subquery Syntax

9 -18

xiii

Creating a Table by Using a Subquery

9-19

The ALTER TABLE Statement

Adding a Column

9-22

9-20

Modifying a Column

9-24

Dropping a Column

9-25

The SET UNUSED Option

9-26

Dropping a Table

9-27

Changing the Name of an Object

9-28

Truncating a Table

9-29

Adding Comments to a Table

Summary

9-31

Practice 9 Overview

9-32

9-30

10 Including Constraints

Objectives

10-2

What Are Constraints?

10-3

Constraint Guidelines

10-4

Defining Constraints

10-5

The NOT NULL Constraint

10-7

The UNIQUE Constraint

10-9

The PRIMARY KEY Constraint

10-11

The FOREIGN KEY Constraint

10-13

FOREIGN KEY Constraint Keywords

The CHECK Constraint

10-16

Adding a Constraint Syntax

Adding a Constraint

10-18

10-17

Dropping a Constraint

10-19

10-15

Disabling Constraints

10-20

Enabling Constraints

10-21

Cascading Constraints

10-22

Viewing Constraints

10-24

Viewing the Columns Associated with Constraints

10-25

Summary

10-26

Practice 10 Overview

10-27

11 Creating Views

 

Objectives

11-2

Database Objects

11-3

What Is a View?

11-4

Why Use Views?

11-5

Simple Views and Complex Views

11-6

Creating a View

11-7

Retrieving Data from a View

11-10

 

Querying a View

11-11

Modifying a View

11-12

Creating a Complex View

11-13

 

Rules for Performing DML Operations on a View

11-14

Using the WITH CHECK OPTION Clause

Denying DML Operations

Removing a View

Inline Views

11-21

11-20

Top-n Analysis

11-22

Performing Top-n Analysis

11-18

11-23

xv

11-17

Example of Top-n Analysis

Summary

11-25

Practice 11 Overview

11-26

11-24

12 Other Database Objects

Objectives

12-2

Database Objects

12-3

What Is a Sequence?

12-4

The CREATE SEQUENCE Statement Syntax

Creating a Sequence

12-6

12-5

Confirming Sequences

12-7

NEXTVAL and CURRVAL Pseudocolumns

12-8

Using a Sequence

12-10

Modifying a Sequence

12-12

Guidelines for Modifying a Sequence

Removing a Sequence

12-14

What Is an Index?

12-15

How Are Indexes Created?

12-16

12-13

Creating an Index

12-17

When to Create an Index

12-18

When Not to Create an Index

12-19

Confirming Indexes

12-20

Function-Based Indexes

12-21

Removing an Index

Synonyms

12-23

12-22

Creating and Removing Synonyms

Summary

12-25

Practice 12 Overview

12-26

12-24

13 Controlling User Access

Objectives

13-2

Controlling User Access

13-3

Privileges

13-4

System Privileges

13-5

 

Creating Users

13-6

User System Privileges

13-7

Granting System Privileges

What Is a Role?

13-9

13-8

Creating and Granting Privileges to a Role

13-10

Changing Your Password

13-11

Object Privileges

13-12

Granting Object Privileges

13-14

Using the WITH GRANT OPTION and PUBLIC Keywords

Confirming Privileges Granted

13-16

How to Revoke Object Privileges

Revoking Object Privileges

Database Links

13-19

13-18

13-17

Summary

13-21

Practice 13 Overview

13-22

13-15

14 SQL Workshop Workshop Overview

Workshop Overview

14-2

xvii

15 Using SET Operators

Objectives

15-2

The SET Operators

15-3

Tables Used in This Lesson

15-4

The UNION SET Operator

15-7

Using the UNION Operator

15-8

The UNION ALL Operator

15-10

Using the UNION ALL Operator

15-11

The INTERSECT Operator

15-12

Using the INTERSECT Operator

The MINUS Operator

15-14

15-13

SET Operator Guidelines

15-16

The Oracle Server and SET Operators

15-17

Matching the SELECT Statements

15-18

Controlling the Order of Rows

15-20

Summary

15-21

Practice 15 Overview

15-22

16 Oracle 9i Datetime Functions

Objectives

16-2

TIME ZONES

16-3

Oracle 9i Datetime Support

CURRENT_DATE

16-6

CURRENT_TIMESTAMP

LOCALTIMESTAMP

16-8

16-4

16-7

DBTIMEZONE and SESSIONTIMEZONE

16-9

EXTRACT

16-10

FROM_TZ

16-11

TO_TIMESTAMP and TO_TIMESTAMP_TZ

TO_YMINTERVAL

16-13

TZ_OFFSET

16-14

Summary

16-16

Practice 16 Overview

16-17

16-12

17 Enhancements to the GROUP BY Clause

Objectives

17-2

Review of Group Functions

17-3

Review of the GROUP BY Clause

17-4

Review of the HAVING Clause

17-5

GROUP BY with ROLLUP and CUBE Operators

ROLLUP Operator

17-7

ROLLUP Operator Example

17-8

CUBE Operator

17-9

CUBE Operator: Example

17-10

GROUPING Function

17-11

GROUPING Function: Example

GROUPING SETS

17-13

17-12

GROUPING SETS: Example

Composite Columns

17-17

Composite Columns: Example

17-15

17-19

Concatenated Groupings

17-21

xix

17-6

Concatenated Groupings Example

Summary

17-23

Practice 17 Overview

17-24

17-22

18 Advanced Subqueries

Objectives

18-2

What Is a Subquery?

Subqueries

18-4

18-3

Using a Subquery

18-5

Multiple-Column Subqueries

Column Comparisons

18-7

18-6

Pairwise Comparison Subquery

18-8

Nonpairwise Comparison Subquery

18-9

Using a Subquery in the FROM Clause

18-10

Scalar Subquery Expressions

18-11

Correlated Subqueries

18-14

Using Correlated Subqueries

18-16

Using the EXISTS Operator

18-18

Using the NOT EXISTS Operator

18-20

Correlated UPDATE

18-21

Correlated DELETE

18-24

The WITH Clause

18-26

WITH Clause: Example

18-27

Summary

18-29

Practice 18 Overview

18-31

19

Hierarchical Retrieval

Objectives

19-2

Sample Data from the EMPLOYEES Table

Natural Tree Structure

19-4

Hierarchical Queries

19-5

Walking the Tree

19-6

19-3

Walking the Tree: From the Bottom Up

19-8

Walking the Tree: From the Top Down

19-9

Ranking Rows with the LEVEL Pseudocolumn

19-10

Formatting Hierarchical Reports Using LEVEL and LPAD

Pruning Branches

19-13

Summary

19-14

Practice 19 Overview

19-15

19-11

20 Oracle 9i Extensions to DML and DDL Statements

Objectives

20-2

Review of the INSERT Statement

Review of the UPDATE Statement

20-3

20-4

Overview of Multitable INSERT Statements

20-5

Types of Multitable INSERT Statements

Multitable INSERT Statements

20-8

Unconditional INSERT ALL

20-10

Conditional INSERT ALL

20-11

Conditional FIRST INSERT

Pivoting INSERT

External Tables

20-15

20-18

20-13

20-7

xxi

Creating an External Table

20-19

Example of Creating an External Table

Querying External Tables

20-23

20-20

CREATE INDEX with CREATE TABLE Statement

Summary

20-25

Practice 20 Overview

20-26

A Practice Solutions

20-24

B Table Descriptions and Data

C Using SQL* Plus

D Writing Advanced Scripts

E Oracle Architectural Components

Index

Additional Practices

Additional Practice Solutions

Table and Descriptions

xxii

Additional

Practices

These exercises can be used for extra practice after you have discussed the following topics: basic SQL SELECT statement, basic iSQL*Plus commands, and SQL functions.

1. Show all data of the clerks who have been hired after the year 1997.

data of the clerks who have been hired after the year 1997. 2. Show the last

2. Show the last name, job, salary, and commission of those employees who earn commission. Sort the data by the salary in descending order.

commission. Sort the data by the salary in descending order. 3. Show the employees that have

3. Show the employees that have no commission with a 10% raise in their salary (round off the salaries).

with a 10% raise in their salary (round off the salaries). Introduction to Oracle9 i: SQL

Introduction to Oracle9i: SQL Additional Practices-3

4.

Show the last names of all employees together with the number of years and the number of completed months that they have been employed.

the number of completed months that they have been employed. 5. Show those employees that have

5. Show those employees that have a name starting with J, K, L, or M.

that have a name starting with J , K , L , or M . 6.

6. Show all employees, and indicate with “Yes” or “No” whether they receive a commission.

“Yes” or “No” whether they receive a commission. ( Note: results continued on next page) Introduction

(Note: results continued on next page)

Introduction to Oracle9i: SQL Additional Practices-4

These exercises can be used for extra practice after you have discussed the following topics:

These exercises can be used for extra practice after you have discussed the following topics: SQL basic SELECT statement, basic iSQL*Plus commands, SQL functions, joins, and group functions.

7. Show the department names, locations, names, job titles, and salaries of employees who work in location 1800.

titles, and salaries of employees who work in location 1800. 8. How many employees have a

8. How many employees have a name that ends with an “n”? Create two possible solutions.

that ends with an “ n ”? Create two possible solutions. 9. Show the names and

9. Show the names and locations for all departments, and the number of employees working in each department. Make sure that departments without employees are included as well.

sure that departments without employees are included as well. Introduction to Oracle9 i: SQL Additional Practices

Introduction to Oracle9i: SQL Additional Practices-5

10.

Which jobs are found in departments 10 and 20?

10. Which jobs are found in departments 10 and 20? 11. Which jobs are found in

11. Which jobs are found in the Administration and Executive departments, and how many employees do these jobs? Show the job with the highest frequency first.

these jobs? Show the job with the highest frequency first. These exercises can be used for

These exercises can be used for extra practice after you have discussed the following topics: basic SQL SELECT statements, basic iSQL*Plus commands, SQL functions, joins, group functions, subqueries.

12. Show all employees who were hired in the first half of the month (before the 16th of the month).

the first half of the month (before the 16th of the month). 13. Show the names,

13. Show the names, salaries, and the number of dollars (in thousands) that all employees earn.

number of dollars (in thousands) that all employees earn. ( Note: Results continue on the next

(Note: Results continue on the next page)

Introduction to Oracle9i: SQL Additional Practices-6

13. Show all employees who have managers with a salary higher than $ 15,000. Show

13. Show all employees who have managers with a salary higher than $ 15,000. Show the following data: employee name, manager name, manager salary, and salary grade of the manager.

manager name, manager salary, and salary grade of the manager. Introduction to Oracle9 i: SQL Additional

Introduction to Oracle9i: SQL Additional Practices-7

14. Show the department number, name, number of employees, and average salary of all departments, together with the names, salaries, and jobs of the employees working in each department.

salaries, and jobs of the employees working in each department. Introduction to Oracle9 i: SQL Additional

Introduction to Oracle9i: SQL Additional Practices-8

15.

Show the department number and the lowest salary of the department with the highest average salary.

15. Show the department number and the lowest salary of the department with the highest average

16. Show the department numbers, names, and locations of the departments where no sales representatives work.

of the departments where no sales representatives work. 17. Show the department number, department name, and

17. Show the department number, department name, and the number of employees working in each department that:

a. Includes fewer than 3 employees:

in each department that: a. Includes fewer than 3 employees: b. Has the highest number of

b. Has the highest number of employees:

than 3 employees: b. Has the highest number of employees: c. Has the lowest number of

c. Has the lowest number of employees:

number of employees: c. Has the lowest number of employees: Introduction to Oracle9 i: SQL Additional

Introduction to Oracle9i: SQL Additional Practices-9

18.

Show the employee number, last name, salary, department number, and the average salary in their department for all employees.

the average salary in their department for all employees. 19. Show all employees who were hired

19. Show all employees who were hired on the day of the week on whic h the highest number of employees has been hired.

week on whic h the highest number of employees has been hired. Introduction to Oracle9 i:

Introduction to Oracle9i: SQL Additional Practices-10

20. Create an anniversary overview based on the hire date of the employees. Sort the anniveraries in ascending order.

date of the employees. Sort the anniveraries in ascending order. Introduction to Oracle9 i: SQL Additional

Introduction to Oracle9i: SQL Additional Practices-11

These exercises can be used for extra practice after you have discussed using SET operators in Lesson 15.

21. Find the job that was filled in the first half of 1990 and the same job that was filled during the same period in 1991.

the same job that was filled during the same period in 1991. 22. Write a compound

22. Write a compound query to produce a list of employees showing raise percentages, employee IDs, and old and new salaries. Employees in departments 10, 50, and 110 are given a 5% raise, employees in department 60 are given a 10% raise, employees in departments 20 and 80 are given a 15% raise, and employees in department 90 are not given a raise.

15% raise, and employees in department 90 are not given a raise. Introduction to Oracle9 i:

Introduction to Oracle9i: SQL Additional Practices-12

These exercises can be used for extra practice after you have discussed Oracle9i single row functions in Lesson 16.

23. Alter the session to set the NLS_DATE_FORMAT to DD-MON-YYYY HH24:MI:SS.

24. a. Write queries to display the time zone offsets (TZ_OFFSET) for the following time zones.

–Australia/Sydney

) for the following time zones. –Australia/Sydney –Chile/EasterIsland b. Alter the session to set the

–Chile/EasterIsland

time zones. –Australia/Sydney –Chile/EasterIsland b. Alter the session to set the TIME_ZONE parameter value

b. Alter the session to set the TIME_ZONE parameter value to the time zone offset of Australia/Sydney.

c. Display the SYSDATE, CURRENT_DATE, CURRENT_TIMESTAMP, and LOCALTIMESTAMP for this session. Note: The output might be different based on the date when the command is executed.

be different based on the date when the command is executed. d. Alter the session to

d. Alter the session to set the TIME_ZONE parameter value to the time zone offset of Chile/EasterIsland.

Note: The results of the preceding question are based on a different date and in some cases they will not match the actual results that the students get. Also the time zo ne offset of the various countries might differ based on daylight savings time.

Introduction to Oracle9i: SQL Additional Practices-13

e. Display the SYSDATE, CURRENT_DATE, CURRENT_TIMESTAMP, and LOCALTIMESTAMP for this session. Note: The output might be different based on the date when the command is executed.

be different based on the date when the command is executed. Note : Observe in the

Note: Observe in the preceding question that CURRENT_DATE, CURRENT_TIMESTAMP, and LOCALTIMESTAMP are all sensitive to the session time zone. Observe that SYSDATE is not sensitive to the session time zone.

Note: The results of the preceding question are based on a different date, and in some cases they will not match the actual results that the students get. Also th e time zone offset of the various countries might differ based on daylight savings time.

25. Write a query to display the last names, month of the date of join, and hire date of those employees who have joined in the month of January, irrespective of the year of join.

in the month of January, irrespective of the year of join. Introduction to Oracle9 i: SQL

Introduction to Oracle9i: SQL Additional Practices-14

These exercises can be used for extra practice after you have discussed enhacements to the GROUP BY clause in Lesson 17.

26. Write a query to display the following for those departments whose department ID is greater than 80 :

– The total salary for every job within a department

– The total salary

– The total salary for those cities in which the departments are l ocated

– The total salary for every job, irrespective of the department

– The total salary for every department irrespective of the city

– The total salary of the cities in which the departments are located

– Total salary for the departments, irrespective of job titles and cities

for the departments, irrespective of job titles and cities Introduction to Oracle9 i: SQL Additional Practices

Introduction to Oracle9i: SQL Additional Practices-15

27. Write a query to display the following groupings :

– Department ID, Job ID

– Job ID, Manager ID

The query should calculate the maximum and minimum salaries for each of these groups.

the maximum and minimum salaries for each of these groups. Introduction to Oracle9 i: SQL Additional

Introduction to Oracle9i: SQL Additional Practices-16

These exercises can be used for extra practice after you have discussed advanced subqueries in Lesson 18.

28. Write a query to display the top three earners in the EMPLOYEES table. Display their last names and salaries.

EMPLOYEES table. Display their last names and salaries. 29. Write a query to display the employee

29. Write a query to display the employee ID and last names of the employees who work in the state of California.

Hint: Use scalar subqueries.

in the state of California. Hint : Use scalar subqueries. 30. Write a query to delete

30. Write a query to delete the oldest JOB_HISTORY row of an employee by looking up the JOB_HISTORY table for the MIN(START_DATE) for the employee. Delete the records of only those employees who have changed at least 2 jobs. If your query has executed correctly, you will get the feedback:

query has executed correctly, you will get the feedback: Hint : Use a correlated DELETE .

Hint: Use a correlated DELETE.

31. Rollback the transaction.

32. Write a query to display the job ids of those jobs whose maximum salary is above half the maximum salary in the whole company. Use the WITH clause to write this query. Name the query as MAX_SAL_CALC.

JOB_TITLE

----------------------------------- ----------

JOB_TOTAL

President

24000

Administration Vice President

17000

Marketing Manager

13000

Introduction to Oracle9i: SQL Additional Practices-17

These exercises can be used for extra practice after you have discussed hierarchial retrieval in Lesson 19.

33. Write a SQL statement to display employee number, last name, start date, and salary, showing:

a. De Haan’s direct reports

date, and salary, showing: a. De Haan’s direct reports b. The organization tree under De Haan’s

b. The organization tree under De Haan’s (employee number 102)

organization tree under De Haan’s (employee number 102) 34. Write a hierarchical query to display the

34. Write a hierarchical query to display the employee number, manager number, and employee last name for all employees who are two levels below employee De Haan (employee number 102). Also display the level of the employee.

(employee number 102). Also display the level of the employee. Introduction to Oracle9 i: SQL Additional

Introduction to Oracle9i: SQL Additional Practices-18

35. Produce a hierarchical report to display the employee number, manager number, the LEVEL pseudocolumn, and employee last name. For every row in the EMPLOYEES table, you should print a tree structure showing the employee, the employee’s manager, then the manager’s manager, and so on. Use indentations for the NAME column.

manager, and so on. Use indentations for the NAME column. Note: The output shown is only

Note: The output shown is only a sample. All the rows from the actual output are not included here.

Introduction to Oracle9i: SQL Additional Practices-19

These exercises can be used for extra practice after you have discussed Oracle 9i extensions to DML and DDL statements in Lesson 20.

36. Write a query to do the following:

– Retrieve the details of the employee ID, hire date, salary, and manager ID of those employees whose employee ID is more than or equal to 200 from the EMPLOYEES table.

– If the salary is less than $5,000, insert the details of employee ID and salary into the SPECIAL_SAL table.

– Insert the details of employee ID, hire date, and salary into the SAL_HISTORY table.

– Insert the details of employee ID, manager ID, and salary into the MGR_HISTORY table.

37. Query the SPECIAL_SAL, SAL_HISTORY and the MGR_HISTORY tables to view the inserted records.

SPECIAL_SAL Table

tables to view the inserted records. SPECIAL_SAL Table SAL_HISTORY Table MGR_HISTORY Table Introduction to

SAL_HISTORY Table

the inserted records. SPECIAL_SAL Table SAL_HISTORY Table MGR_HISTORY Table Introduction to Oracle9 i: SQL

MGR_HISTORY Table

SPECIAL_SAL Table SAL_HISTORY Table MGR_HISTORY Table Introduction to Oracle9 i: SQL Additional Practices - 20

Introduction to Oracle9i: SQL Additional Practices-20

38. Create the LOCATIONS_NAMED_INDEX table based on the following table instance chart. Name the index for the PRIMARY KEY column as LOCATIONS_PK_IDX.

COLUMN Name

Deptno

Dname

Primary Key

Yes

 

Datatype

Number

VARCHAR2

Length

4

30

39. Query the USER_INDEXES table to display the INDEX_NAME for the LOCATIONS_NAMED_INDEX table.

display the INDEX_NAME for the LOCATIONS_NAMED_INDEX table. Introduction to Oracle9 i: SQL Additional Practices - 21

Introduction to Oracle9i: SQL Additional Practices-21

This exercise can be used for extra practice after you have discussed writing advanced scripts in Appendix

D.

Appendix D Additional Practice

Write a SQL script file to drop all objects (tables, views, indexes, sequences, synonyms, and so on) that you own. The output shown is only a guideline.

and so on) that you own. The output shown is only a guideline. Introduction to Oracle9

Introduction to Oracle9i: SQL Additional Practices-22

Additional

Practice

Solutions

These exercises can be used for extra practice after you have discussed the following topics: basic SQL SELECT statement, basic iSQL*Plus commands, and SQL functions.

1. Show all data of the clerks who have been hired after the year 1997. SELECT * FROM employees WHERE job_id = 'ST_CLERK' AND hire_date > '31-DEC-1997';

2. Show the last name, job, salary, and commission of those employees who earn commission. Sort the data by the salary in descending order.

SELECT last_name, job_id, salary, commission_pct FROM employees WHERE commission_pct IS NOT NULL ORDER BY salary DESC;

3. Show the employees that have no commission with a 10% raise intheir salary (round off the salaries).

SELECT 'The salary of '||last_name||' after a 10% raise is ' || ROUND(salary*1.10) "New salary" FROM employees WHERE commission_pct IS NULL;

4. Show the last names of all employees together with the number of years and the number of completed months that they have been employed.

SELECT last_name,

FROM

TRUNC(MONTHS_BETWEEN(SYSDATE, hire_date) / 12) YEARS, TRUNC(MOD(MONTHS_BETWEEN(SYSDATE, hire_date), 12)) MONTH S employees;

5. Show those employees that have a name starting with J, K, L, or M.

SELECT last_name FROM employees WHERE SUBSTR(last_name, 1,1) IN ('J', 'K', 'L', 'M');

Introduction to Oracle9i: SQL Additional Practice Solutions-3

6.

Show all employees, and indicate with “Yes” or “No” whether they receive a commission.

SELECT last_name, salary, decode(commission_pct, NULL, 'No', 'Yes') commissio n FROM employees;

These exercises can be used for extra practice after you have discussed the following topics: SQL basic SELECT statement, basic iSQL*Plus commands, SQL functions, joins, and group functions.

7. Show the department names, locations, names, job titles, and salaries of employees who work in location 1800.

SELECT d.department_name, d.location_id, e.last_name, e.job_id, e.salary

FROM

employees e, departments d

WHERE

e.department_id = d.department_id

AND

d.location_id = 1800;

8. How many employees have a name that ends with an n? Create two possible solutions.

SELECT COUNT(*) FROM employees WHERE last_name LIKE '%n';

SELECT COUNT(*) FROM employees WHERE SUBSTR(last_name, -1) = 'n';

9. Show the names and locations for all departments and the number of employees working in each department. Make sure that departments without employees are included, as well.

SELECT d.department_id, d.department_name,

 

d.location_id,

COUNT(e.employee_id)

FROM

employees e, departments d

WHERE

e.department_id(+) = d.department_id

GROUP BY d.department_id, d.department_name, d.location_id ;

Introduction to Oracle9i: SQL Additional Practice Solutions-4

10.

Which jobs are found in departments 10 and 20?

SELECT DISTINCT job_id FROM employees WHERE department_id IN (10, 20);

11. Which jobs are found in the Administration and Executive departments, and how many employees do these jobs? Show the job with the highest frequency first.

SELECT e.job_id, count(e.job_id) FREQUENCY

FROM

WHERE e.department_id = d.department_id

AND

GROUP BY e.job_id ORDER BY FREQUENCY DESC;

employees e, departments d

d.department_name IN ('Administration', 'Executive')

These exercises can be used for extra practice after you have discussed the following topics: basic SQL SELECT statements, basic iSQL*Plus commands, SQL functions, joins, group functions, subqueries.

12. Show all employees who were hired in the first half of the month (before the 16th of the month).

SELECT last_name, hire_date FROM employees WHERE TO_CHAR(hire_date, 'DD') < 16;

13. Show the names, salaries, and the number of dollars (in thousands) that all employees earn.

SELECT last_name, salary, TRUNC(salary, -3)/1000 Thousands FROM employees;

14. Show all employees who have managers with a salary higher than $ 15,000. Show the following data: employee name, manager name, manager salary, and salary grade of the manager.

SELECT e.last_name, m.last_name manager, m.salary, j.grade_level

FROM

WHERE e.manager_id = m.employee_id

employees e, employees m, job_grades j

AND

m.salary BETWEEN j.lowest_sal AND j.highest_sal

AND

m.salary > 15000;

Introduction to Oracle9i: SQL Additional Practice Solutions-5

15.

Show the department number, name, number of employees, and average salary of all departments, together with the names, salaries, and jobs of the employees working in each department.

BREAK ON department_id - ON department_name ON employees ON avg_sal SKIP 1

SELECT d.department_id, d.department_name, count(e1.employee_id) employees, NVL(TO_CHAR(AVG(e1.salary), '99999.99'), 'No average' ) avg_sal, e2.last_name, e2.salary, e2.job_id

FROM

departments d, employees e1, employees e2

WHERE

d.department_id = e1.department_id(+)

AND

d.department_id = e2.department_id(+)

GROUP BY d.department_id, d.department_name,

e2.last_name,

e2.salary, e2.job_id

ORDER BY d.department_id, employees;

CLEAR BREAKS

16. Show the department number and the lowest salary of the department with the highest average salary.

SELECT department_id, MIN(salary) FROM employees GROUP BY department_id HAVING AVG(salary) = (SELECT MAX(AVG(salary)) FROM employees GROUP BY department_id);

17. Show the department numbers, names, and locations of the departments where no sales representatives work.

SELECT * FROM departments WHERE department_id NOT IN(SELECT department_id FROM employees WHERE job_id = 'SA_REP' AND department_id IS NOT NULL);

18. Show the department number, department name, and the number of employees working in each that:

a. Includes fewer than 3 employees:

SELECT d.department_id, d.department_name, COUNT(*)

FROM

WHERE d.department_id = e.department_id GROUP BY d.department_id, d.department_name HAVING COUNT(*) < 3;

departments d, employees e

Introduction to Oracle9i: SQL Additional Practice Solutions-6

b. Has the highest number of employees:

SELECT d.department_id, d.department_name, COUNT(*)

FROM

WHERE d.department_id = e.department_id GROUP BY d.department_id, d.department_name HAVING COUNT(*) = (SELECT MAX(COUNT(*)) FROM employees

departments d, employees e

GROUP BY department_id);

c. Has the lowest number of employees:

SELECT d.department_id, d.department_name, COUNT(*)

FROM

WHERE d.department_id = e.department_id GROUP BY d.department_id, d.department_name HAVING COUNT(*) = (SELECT MIN(COUNT(*)) FROM employees GROUP BY department_id);

departments d, employees e

19. Show the employee number, last name, salary, department number, and the average salary in their department for all employees.

SELECT e.employee_id, e.last_name,

e.department_id,

AVG(s.salary)

FROM

employees e, employees s

WHERE

e.department_id = s.department_id

GROUP BY e.employee_id, e.last_name, e.department_id;

20. Show all employees who were hired on the day of the week on whic h the highest number of employees has been hired.

SELECT last_name, TO_CHAR(hire_date, 'DAY') day FROM employees WHERE TO_CHAR(hire_date, 'Day') = (SELECT TO_CHAR(hire_date, 'Day') FROM employees GROUP BY TO_CHAR(hire_date, 'Day') HAVING COUNT(*) = (SELECT MAX(COUNT(*)) FROM employees GROUP BY TO_CHAR(hire_date, 'Day') ));

Introduction to Oracle9i: SQL Additional Practice Solutions-7

21. Create an anniversary overview based on the hire date of the employees. Sort the anniveraries in ascending order.

SELECT last_name, TO_CHAR(hire_date, 'Month DD') BIRTHDAY FROM employees ORDER BY TO_CHAR(hire_date, 'DDD');

Introduction to Oracle9i: SQL Additional Practice Solutions-8

These exercises can be used for extra practice after you have discussed using SET operators in Lesson 15.

22. Find the job that was filled in the first half of 1990 and the same job that was filled during the same period in 1991.

SELECT job_id FROM employees WHERE hire_date BETWEEN '01-JAN-1990' AND '30-JUN-1990' INTERSECT SELECT job_id FROM employees WHERE hire_date BETWEEN '01-JAN-1991' AND '30-JUN-1991';

23. Write a compound query to produce a list of employees showing raise percentages, employee IDs, and old and new salaries. Employees in departments 10, 50, and 110 are given a 5% raise, employees in department 60 are given a 10% raise, employees in departments 20 and 80 are given a 15% raise, and employees in department 90 are not given a raise.

SELECT '05% raise' raise, employee_id, salary, salary *.05 new_salary FROM employees WHERE department_id IN (10,50, 110) UNION SELECT '10% raise', employee_id, salary, salary * .10 FROM employees WHERE department_id = 60 UNION SELECT '15% raise', employee_id, salary, salary * .15 FROM employees WHERE department_id IN (20, 80) UNION SELECT 'no raise', employee_id, salary, salary FROM employees WHERE department_id = 90;

Introduction to Oracle9i: SQL Additional Practice Solutions-9

These exercises can be used for extra practice after you have discussed Oracle9i single row functions in Lesson

16.

24. Alter the session to set the NLS_DATE_FORMAT to DD-MON-YYYY HH24:MI:SS.

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';

25. a. Write queries to display the time zone offsets (TZ_OFFSET), for the following time zones.

–Australia/Sydney

TZ_OFFS

-------

+11:00

SELECT TZ_OFFSET ('Australia/Sydney') from dual;

–Chile/EasterIsland

TZ_OFFS

-------

-05:00

SELECT TZ_OFFSET ('Chile/EasterIsland') from dual;

b. Alter the session to set the TIME_ZONE parameter value to the time zone offset of Australia/Sydney.

ALTER SESSION SET TIME_ZONE = '+11:00';

c. Display the SYSDATE, CURRENT_DATE, CURRENT_TIMESTAMP, and LOCALTIMESTAMP for this session. Note: The output might be different based on the date when the command is executed.

SELECT SYSDATE,CURRENT_DATE, CURRENT_TIMESTAMP, LOCALTIMESTAMP FROM DUAL;

d. Alter the session to set the TIME_ZONE parameter value to the time zone offset of Chile/EasterIsland.

ALTER SESSION SET TIME_ZONE = ' -05:00';

Introduction to Oracle9i: SQL Additional Practice Solutions-10

e. Display the SYSDATE, CURRENT_DATE, CURRENT_TIMESTAMP, and LOCALTIMESTAMP for this session. Note: The output might be different based on the date when the command is executed.

SELECT SYSDATE,CURRENT_DATE, CURRENT_TIMESTAMP, LOCALTIMESTAMP FROM DUAL;

Note: Observe in the preceding question that CURRENT_DATE, CURRENT_TIMESTAMP, and LOCALTIMESTAMP are all sensitive to the session time zone. Observe that SYSDATE is not sensitive to the session time zone.

Note: The results of the preceding question are based on a different date, and in some cases they will not match the actual results that the students get. Also the time zo ne offset of the various countries might differ based on daylight savings time.

26. Write a query to display the last names, month of the date of join, and hire date of those employees who have joined in the month of January, irrespective of the year of join.

SELECT last_name, EXTRACT (MONTH FROM HIRE_DATE),HIRE_DAT E FROM employees WHERE EXTRACT (MONTH FROM HIRE_DATE) = 1;

Introduction to Oracle9i: SQL Additional Practice Solutions-11

These exercises can be used for extra practice after you have discussed enhacements to the GROUP BY clause in Lesson 17.

27. Write a query to display the following for those departments whose department ID is greater than 80:

– The total salary for every job within a department

– The total salary

– The total salary for those cities in which the departments are l ocated

– The total salary for every job, irrespective of the department

– The total salary for every department irrespective of the city

– The total salary of the cities in which the departments are located

– Total salary for the departments, irrespective of job titles and cities

COLUMN city FORMAT A25 Heading CITY COLUMN department_name FORMAT A15 Heading DNAME COLUMN job_id FORMAT A10 Heading JOB COLUMN SUM(salary) FORMAT $99,99,999.00 Heading SUM(SALA RY)

SELECT

FROM countries,locations,employees,departments

city,department_name, job_id, SUM(salary)

WHERE

departments.location_id = locations.location_id

AND

employees.department_id = departments.department _id

AND

employees.department_id > 80

GROUP

BY CUBE( city,department_name, job_id);

Introduction to Oracle9i: SQL Additional Practice Solutions-12

28.

Write a query to display the following groupings :

– Department ID, Job ID

– Job ID, Manager ID

The query should calculate the maximum and minimum salaries for each of these groups.

SELECT department_id, job_id, manager_id,max(salary),min(s alary) FROM employees GROUP BY GROUPING SETS ((department_id,job_id), (job_id,manager_id));

Introduction to Oracle9i: SQL Additional Practice Solutions-13

These exercises can be used for extra practice after you have discussed advanced subqueries in Lesson 18.

29. Write a query to display the top three earners in the EMPLOYEES table. Display their last names and salaries.

SELECT last_name, salary

FROM

WHERE 3 > (SELECT COUNT(*)

employees e

FROM employees WHERE e.salary < salary);

30. Write a query to display the employee ID and last names of the employees who work in the state of California.

Hint: Use scalar subqueries.

SELECT employee_id, last_name FROM employees e WHERE ((SELECT location_id FROM departments d

WHERE e.department_id = d.department_id )

IN

(SELECT location_id FROM locations l WHERE STATE_province = 'California'));

31. Write a query to delete the oldest JOB_HISTORY row of an employee by looking up the JOB_HISTORY table for the MIN(START_DATE) for the employee. Delete the records of only those employees who have changed at least 2 jobs. If your query has executed correctly, you will get the following feedback:

Hint: Use a correlated DELETE.

DELETE FROM job_history JH WHERE employee_id = (SELECT employee_id FROM employees E WHERE JH.employee_id = E.employee_id AND START_DATE = (SELECT MIN(start_date ) FROM job_history JH WHERE JH.employee_id = E.employee_id) AND 3 > (SELECT COUNT(*) FROM job_history JH WHERE JH.employee_id = E.employee_id GROUP BY EMPLOYEE_ID HAVING COUNT(*) >= 2));

32. Rollback the transaction. ROLLBACK;

Introduction to Oracle9i: SQL Additional Practice Solutions-14

33.

Write a query to display the job IDs of those jobs whose maximum salary is above half the maximum salary in the whole company. Use the WITH clause to write this query. Name the query as MAX_SAL_CALC.

WITH MAX_SAL_CALC AS ( SELECT job_title, MAX(salary) AS job_total FROM employees, jobs WHERE employees.job_id = jobs.job_id GROUP BY job_title) SELECT job_title, job_total FROM MAX_SAL_CALC WHERE job_total > (SELECT MAX(job_total) * 1/2 FROM MAX_SAL_CALC) ORDER BY job_total DESC;

These exercises can be used for extra practice after you have discussed hierarchial retrieval in Lesson 19.

34. Write a SQL statement to display employee number, last name, start date, and salary, showing:

a. De Haan’s direct reports

SELECT employee_id, last_name, hire_date, salary FROM employees WHERE manager_id = (SELECT employee_id FROM employees WHERE last_name = 'De Haan');

b. The organization tree under De Haan’s (employee number 102)

SELECT employee_id, last_name, hire_date, salary FROM employees WHERE employee_id != 102 CONNECT BY manager_id = PRIOR employee_id START WITH employee_id = 102;

35. Write a hierarchical query to display the employee number, manager number, and mployee last name for all employees who are two levels below employee De Haan (employee number 102). Also display the level of the employee.

SELECT employee_id, manager_id, level, last_name FROM employees WHERE LEVEL = 3 CONNECT BY manager_id = PRIOR employee_id START WITH employee_id= 102;

Introduction to Oracle9i: SQL Additional Practice Solutions-15

36. Produce a hierarchical report to display employee number, manager number, the LEVEL pseudocolumn, and

employee last name. For every row in the EMPLOYEES table, you should print a tree structure

employee, the employee’s manager, then the manager’s manager, and so on. Use indentations for the NAME

column.

showing the

COLUMN name FORMAT A25 SELECT employee_id, manager_id, LEVEL, LPAD(last_name, LENGTH(last_name)+(LEVEL*2) -2,'_') FROM employees CONNECT BY employee_id = PRIOR manager_id; COLUMN name CLEAR

Introduction to Oracle9i: SQL Additional Practice Solutions-16

These exercises can be used for extra practice after you have discussed Oracle 9i extensions to DML and DDL statements in Lesson 20.

37. Write a query to do the following:

– Retrieve the details of the employee ID, hire date, salary, and manager ID of those employees whose employee ID is more than or equal to 200 from the EMPLOYEES table.

– If the salary is less than $5,000, insert the details of employee ID and salary into the SPECIAL_SAL table.

– Insert the details of employee ID, hire date, and salary into the SAL_HISTORY table.

– Insert the details of employee ID, manager ID, and salary into the MGR_HISTORY table.

INSERT ALL WHEN SAL < 5000 THEN INTO special_sal VALUES (EMPID, SAL) ELSE INTO sal_history VALUES(EMPID,HIREDATE,SAL) INTO mgr_history VALUES(EMPID,MGR,SAL) SELECT employee_id EMPID, hire_date HIREDATE, salary SAL, manager_id MGR FROM employees WHERE employee_id >=200;

38. Query the SPECIAL_SAL, SAL_HISTORY and the MGR_HISTORY tables to view the inserted records.

SELECT * FROM special_sal; SELECT * FROM sal_history; SELECT * FROM mgr_history;

Introduction to Oracle9i: SQL Additional Practice Solutions-17

39.

Create the LOCATIONS_NAMED_INDEX table based on the following table instance chart. Name the index for the PRIMARY KEY column as LOCATIONS_PK_IDX.

CREATE TABLE LOCATIONS_NAMED_INDEX (location_id NUMBER(4) PRIMARY KEY USING INDEX (CREATE INDEX locations_pk_idx ON LOCATIONS_NAMED_INDEX(location_id)), location_name VARCHAR2(20));

40. Query the USER_INDEXES table to display the INDEX_NAME for the LOCATIONS_NAMED_INDEX table.

SELECT INDEX_NAME, TABLE_NAME FROM USER_INDEXES WHERE TABLE_NAME = 'LOCATIONS_NAMED_INDEX';

Introduction to Oracle9i: SQL Additional Practice Solutions-18

This exercise can be used for extra practice after you have discussed writing advanced scripts in Appendix D.

Appendix D Additional Practice

Write a SQL script file to drop all objects (tables, views, indexes, sequences, synonyms, and so on) that you own. The output shown is only a guideline.

SET HEADING OFF ECHO OFF FEEDBACK OFF TERMOUT OFF SET PAGESIZE 0

SPOOL dropall.sql

SELECT

FROM user_objects

ORDER BY object_type

/

'DROP ' || object_type || ' ' || object_name || '; '

SPOOL off

SET HEADING ON ECHO ON FEEDBACK ON TERMOUT ON SET PAGESIZE 24

Introduction to Oracle9i: SQL Additional Practice Solutions-19

Introduction to Oracle9i: SQL Additional Practice Solutions-20

Table Descriptions and Data

COUNTRIES Table

DESCRIBE countries

COUNTRIES Table DESCRIBE countries SELECT * FROM countries; Introduction Oracle9 i : SQL Additional Practice Table

SELECT * FROM countries;

COUNTRIES Table DESCRIBE countries SELECT * FROM countries; Introduction Oracle9 i : SQL Additional Practice Table

Introduction Oracle9i: SQL Additional Practice Table Descriptions-3

DEPARTMENTS Table

DESCRIBE departments

DEPARTMENTS Table DESCRIBE departments SELECT * FROM departments; Introduction Oracle9 i : SQL Additional Practice Table

SELECT * FROM departments;

Table DESCRIBE departments SELECT * FROM departments; Introduction Oracle9 i : SQL Additional Practice Table

Introduction Oracle9i: SQL Additional Practice Table Descriptions-4

EMPLOYEES Table

DESCRIBE employees

EMPLOYEES Table DESCRIBE employees SELECT * FROM employees; Continued on next page Introduction Oracle9i: SQL Additional

SELECT * FROM employees;

Continued on next page Introduction Oracle9i: SQL Additional Practice Table Descriptions-5
Continued on next page
Introduction Oracle9i: SQL Additional Practice Table Descriptions-5

EMPLOYEES Table (continued)

EMPLOYEES Table (continued) Introduction Oracle9 i : SQL Additional Practice Table Descriptions - 6

Introduction Oracle9i: SQL Additional Practice Table Descriptions-6

JOBS Table

DESCRIBE jobs

JOBS Table DESCRIBE jobs SELECT * FROM jobs; Introduction Oracle9 i : SQL Additional Practice Table

SELECT * FROM jobs;

JOBS Table DESCRIBE jobs SELECT * FROM jobs; Introduction Oracle9 i : SQL Additional Practice Table

Introduction Oracle9i: SQL Additional Practice Table Descriptions-7

JOB_GRADES Table

DESCRIBE job_grades

JOB_GRADES Table DESCRIBE job_grades SELECT * FROM job_grades; Introduction Oracle9 i : SQL Additional Practice Table

SELECT * FROM job_grades;

Table DESCRIBE job_grades SELECT * FROM job_grades; Introduction Oracle9 i : SQL Additional Practice Table

Introduction Oracle9i: SQL Additional Practice Table Descriptions-8

JOB_HISTORY Table

DESCRIBE job_history

JOB_HISTORY Table DESCRIBE job_history SELECT * FROM job_history; Introduction Oracle9 i : SQL Additional Practice Table

SELECT * FROM job_history;

Table DESCRIBE job_history SELECT * FROM job_history; Introduction Oracle9 i : SQL Additional Practice Table

Introduction Oracle9i: SQL Additional Practice Table Descriptions-9

LOCATIONS Table

DESCRIBE locations

LOCATIONS Table DESCRIBE locations SELECT * FROM locations; Introduction Oracle9 i : SQL Additional Practice Table

SELECT * FROM locations;

LOCATIONS Table DESCRIBE locations SELECT * FROM locations; Introduction Oracle9 i : SQL Additional Practice Table

Introduction Oracle9i: SQL Additional Practice Table Descriptions-10

REGIONS Table

DESCRIBE regions

REGIONS Table DESCRIBE regions SELECT * FROM regions; Introduction Oracle9 i : SQL Additional Practice Table

SELECT * FROM regions;

REGIONS Table DESCRIBE regions SELECT * FROM regions; Introduction Oracle9 i : SQL Additional Practice Table

Introduction Oracle9i: SQL Additional Practice Table Descriptions-11

Introduction Oracle9i: SQL Additional Practice Table Descriptions-12