Oracle SQL 9i
Oracle SQL 9i
Oracle SQL 9i
40049GC10
Production 1.0
June 2001
D33053
Authors Copyright Oracle Corporation, 2000, 2001. All rights reserved.
Publisher
Sheryl Domingue
Contents
Preface
Curriculum Map
Introduction
Objectives I-2
Oracle9i I-3
Oracle9i Application Server I-5
Oracle9i Database I-6
Oracle9i: Object Relational Database Management System I-8
Oracle Internet Platform I-9
System Development Life Cycle I-10
Data Storage on Different Media I-12
Relational Database Concept I-13
Definition of a Relational Database I-14
Data Models I-15
Entity Relationship Model I-16
Entity Relationship Modeling Conventions I-17
Relating Multiple Tables I-19
Relational Database Terminology I-20
Relational Database Properties I-21
Communicating with a RDBMS Using SQL I-22
Relational Database Management System I-23
SQL Statements I-24
Tables Used in the Course I-25
Summary I-26
iii
Selecting All Columns 1-5
Selecting Specific Columns 1-6
Writing SQL Statements 1-7
Column Heading Defaults 1-8
Arithmetic Expressions 1-9
Using Arithmetic Operators 1-10
Operator Precedence 1-11
Using Parentheses 1-13
Defining a Null Value 1-14
Null Values in Arithmetic Expressions 1-15
Defining a Column Alias 1-16
Using Column Aliases 1-17
Concatenation Operator 1-18
Using the Concatenation Operator 1-19
Literal Character Strings 1-20
Using Literal Character Strings 1-21
Duplicate Rows 1-22
Eliminating Duplicate Rows 1-23
SQL and iSQL*Plus Interaction 1-24
SQL Statements versus iSQL*Plus Commands 1-25
Overview of iSQL*Plus 1-26
Logging In to iSQL*Plus 1-27
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
Summary 2-26
v
3 Single-Row Functions
Objectives 3-2
vi
Using the TO_CHAR Function with Numbers 3-37
Summary 3-57
Objectives 4-2
Nonequijoins 4-14
viii
FULL OUTER JOIN 4-34
Summary 4-36
Objectives 5-2
Summary 5-26
Objectives 6-2
Summary 6-18
Objectives 7-2
x
Defining Substitution Variables 7-10
Summary 7-26
8 Manipulating Data
Objectives 8-2
xi
Creating a Script 8-10
Locking 8-45
Summary 8-47
Objectives 9-2
xiii
Creating a Table by Using a Subquery 9-19
Summary 9-31
10 Including Constraints
Objectives 10-2
Summary 10-26
11 Creating Views
Objectives 11-2
xv
Example of Top-n Analysis 11-24
Summary 11-25
Objectives 12-2
Synonyms 12-23
xvi
Creating and Removing Synonyms 12-24
Summary 12-25
Objectives 13-2
Privileges 13-4
Summary 13-21
Objectives 15-2
Summary 15-21
Objectives 16-2
CURRENT_DATE 16-6
CURRENT_TIMESTAMP 16-7
LOCALTIMESTAMP 16-8
xviii
EXTRACT 16-10
FROM_TZ 16-11
TO_YMINTERVAL 16-13
TZ_OFFSET 16-14
Summary 16-16
Objectives 17-2
xix
Concatenated Groupings Example 17-22
Summary 17-23
18 Advanced Subqueries
Objectives 18-2
Subqueries 18-4
Summary 18-29
xx
19 Hierarchical Retrieval
Objectives 19-2
Summary 19-14
Objectives 20-2
xxi
Creating an External Table 20-19
Summary 20-25
A Practice Solutions
Index
Additional Practices
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.
2. Show the last name, job, salary, and commission of those employees who earn commission. Sort
the data by the salary in descending order.
3. Show the employees that have no commission with a 10% raise in their salary (round off the
salaries).
6. Show all employees, and indicate with Yes or No whether they receive a commission.
8. How many employees have a name that ends with an n? Create two possible solutions.
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.
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 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).
13. Show the names, salaries, and the number of dollars (in thousands) that all employees earn.
16. Show the department numbers, names, and locations of the departments where no sales
representatives work.
17. Show the department number, department name, and the number of employees working in each
department that:
a. Includes fewer than 3 employees:
19. Show all employees who were hired on the day of the week on whic h the highest number of
employees has been hired.
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.
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.
Chile/EasterIsland
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.
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 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.
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 located
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
28. Write a query to display the top three earners in the EMPLOYEES table. Display their last names
and salaries.
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.
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:
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
33. Write a SQL statement to display employee number, last name, start date, and salary,
showing:
a. De Haans direct reports
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.
Note: The output shown is only a sample. All the rows from the actual output are not included here.
37. Query the SPECIAL_SAL, SAL_HISTORY and the MGR_HISTORY tables to view the inserted
records.
SPECIAL_SAL Table
SAL_HISTORY Table
MGR_HISTORY Table
39. Query the USER_INDEXES table to display the INDEX_NAME for the
LOCATIONS_NAMED_INDEX table.
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.
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.
3. Show the employees that have no commission with a 10% raise intheir salary (round off the
salaries).
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,
TRUNC(MONTHS_BETWEEN(SYSDATE, hire_date) / 12) YEARS,
TRUNC(MOD(MONTHS_BETWEEN(SYSDATE, hire_date), 12)) MONTH S
FROM employees;
SELECT last_name
FROM employees
WHERE SUBSTR(last_name, 1,1) IN ('J', 'K', 'L', 'M');
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.
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.
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 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).
13. Show the names, salaries, and the number of dollars (in thousands) that all employees earn.
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.
BREAK ON department_id -
ON department_name ON employees ON avg_sal SKIP 1
CLEAR BREAKS
16. Show the department number and the lowest salary of the department with the highest average
salary.
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:
19. Show the employee number, last name, salary, department number, and the average salary in their
department for all employees.
20. Show all employees who were hired on the day of the week on whic h the highest number of
employees has been hired.
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.
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';
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';
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 zone 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.
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 located
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
29. Write a query to display the top three earners in the EMPLOYEES table. Display their last names
and salaries.
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.
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.
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 Haans direct reports
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.
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.
40. Query the USER_INDEXES table to display the INDEX_NAME for the LOCATIONS_NAMED_INDEX
table.
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.
SPOOL dropall.sql
SPOOL off
DESCRIBE countries
DESCRIBE departments
DESCRIBE employees
DESCRIBE jobs
DESCRIBE job_grades
DESCRIBE job_history
DESCRIBE locations
DESCRIBE regions