Oracle Database 12c: SQL Workshop I: D80190GC10 Edition 1.0 August 2013 D83124
Oracle Database 12c: SQL Workshop I: D80190GC10 Edition 1.0 August 2013 D83124
Oracle Database 12c: SQL Workshop I: D80190GC10 Edition 1.0 August 2013 D83124
D83124
Edition 1.0
August 2013
D80190GC10
Activity Guide
Workshop I
Oracle Database 12c: SQL
Disclaimer
This document contains proprietary information and is protected by copyright and other intellectual property laws. You may copy and
print this document solely for your own use in an Oracle training course. The document may not be modified or altered in any way.
Except where your use constitutes "fair use" under copyright law, you may not use, share, download, upload, copy, print, display,
perform, reproduce, publish, license, post, transmit, or distribute this document in whole or in part without the express authorization
of Oracle.
If this documentation is delivered to the United States Government or anyone using the documentation on behalf of the United
States Government, the following notice is applicable:
Trademark Notice
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective
owners.
Author
Dimpi Rani Sarmah
Table of Contents
Practices for Lesson 1: Introduction ........................................................................................................ 1-1
Practices for Lesson 1: Overview............................................................................................................. 1-2
Practice 1-1: Introduction......................................................................................................................... 1-3
Solution 1-1: Introduction......................................................................................................................... 1-5
Practice Overview
In this practice, you start SQL Developer, create a new database connection, and browse your
HR tables. You also set some SQL Developer preferences.
Note
• All written practices use Oracle SQL Developer as the development environment.
Although it is recommended that you use Oracle SQL Developer, you can also use
SQL*Plus that is available in this course.
• For any query, the sequence of rows retrieved from the database may differ from
the screenshots shown.
Overview
This is the first of many practices in this course. The solutions (if you require them) can be found
at the end of this practice. The practices are intended to cover most of the topics that are
presented in the corresponding lesson.
Tasks
1. Starting Oracle SQL Developer Using the SQL Developer Desktop Icon
2. Creating a New Oracle SQL Developer Database Connection
a. To create a new database connection, in the Connections Navigator, right-click
Connections and select New Connection from the context menu. The New/Select
Database Connection dialog box appears.
b. Create a database connection using the following information:
Connection Name: myconnection
Username: ora1
Password: ora1
Hostname: localhost
Port: 1521
SID: ORCL
Ensure that you select the Save Password check box.
3. Testing the Oracle SQL Developer Database Connection and Connecting to the
Database
a. Test the new connection.
b. If the status is Success, connect to the database using this new connection.
4. Browsing the Tables in the Connections Navigator
a. In the Connections Navigator, view the objects that are available to you in the
Tables node. Verify that the following tables are present:
COUNTRIES
DEPARTMENTS
EMPLOYEES
JOB_GRADES
JOB_HISTORY
JOBS
LOCATIONS
REGIONS
3. Testing and Connecting Using the Oracle SQL Developer Database Connection
a. Test the new connection.
When you create a connection, a SQL Worksheet for that connection opens automatically.
Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Practice Overview
This practice covers the following topics:
• Selecting all data from different tables
Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 2
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Overview
In this practice, you write simple SELECT queries. The queries cover most of the SELECT
clauses and operations that you learned in this lesson.
True/False
True/False
3. There are four coding errors in the following statement. Can you identify them?
SELECT employee_id, last_name
sal x 12 ANNUAL SALARY
FROM employees;
Task 2
Note the following points before you begin with the practices:
• Save all your practice files at the following location:
/home/oracle/labs/sql1/labs
• Enter your SQL statements in a SQL Worksheet. To save a script in SQL Developer,
make sure that the required SQL Worksheet is active, and then from the File menu,
select Save As to save your SQL statement as a lab_<lessonno>_<stepno>.sql
script. When you are modifying an existing script, make sure that you use Save As to
save it with a different file name.
• To run the query, click the Execute Statement icon in the SQL Worksheet.
Alternatively, you can press F9. For DML and DDL statements, use the Run Script icon
or press F5.
• After you have executed the query, make sure that you do not enter your next query in
the same worksheet. Open a new worksheet.
You have been hired as a SQL programmer for Acme Corporation. Your first task is to create
some reports based on the data from the Human Resources tables.
Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
1. Your first task is to determine the structure of the DEPARTMENTS table and its contents.
b. The HR department wants a query to display the last name, job ID, hire date, and
employee ID for each employee, with the employee ID appearing first. Provide an alias
STARTDATE for the HIRE_DATE column. Save your SQL statement to a file named
lab_02_05.sql so that you can dispatch this file to the HR department. Test your
query in the lab_02_05.sql file to ensure that it runs correctly.
Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 4
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Note: After you have executed the query, make sure that you do not enter your next query
in the same worksheet. Open a new worksheet.
Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 5
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Task 3
If you have time, complete the following exercises:
1. The HR department wants more descriptive column headings for its report on employees.
Copy the statement from lab_02_05.sql to a new SQL Worksheet. Name the columns
Emp #, Employee, Job, and Hire Date, respectively. Then run the query again.
Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 6
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 7
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Task 1
Test your knowledge:
1. The following SELECT statement executes successfully:
True/False
True/False
3. There are four coding errors in the following statement. Can you identify them?
SELECT employee_id, last_name
sal x 12 ANNUAL SALARY
FROM employees;
• The EMPLOYEES table does not contain a column called sal. The column is called
SALARY.
• The multiplication operator is *, not x, as shown in line 2.
• The ANNUAL SALARY alias cannot include spaces. The alias should read
ANNUAL_SALARY or should be enclosed within double quotation marks.
• A comma is missing after the LAST_NAME column.
Task 2
You have been hired as a SQL programmer for Acme Corporation. Your first task is to create
some reports based on the data from the Human Resources tables.
1. Your first task is to determine the structure of the DEPARTMENTS table and its contents.
a. To determine the DEPARTMENTS table structure:
DESCRIBE departments
b. To view the data contained in the DEPARTMENTS table:
SELECT *
FROM departments;
2. Your task is to determine the structure of the DEPARTMENTS table and its contents.
Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 8
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
b. The HR department wants a query to display the last name, job ID, hire date, and
employee ID for each employee, with the employee ID appearing first. Provide an alias
STARTDATE for the HIRE_DATE column. Save your SQL statement to a file named
lab_02_05.sql so that you can dispatch this file to the HR department. Test your
query in the lab_02_05.sql file to ensure that it runs correctly.
SELECT employee_id, last_name, job_id, hire_date StartDate
3. The HR department wants a query to display all unique job IDs from the EMPLOYEES table.
SELECT DISTINCT job_id
FROM employees;
Task 3
If you have time, complete the following exercises:
1. The HR department wants more descriptive column headings for its report on employees.
Copy the statement from lab_02_05.sql to a new SQL Worksheet. Name the columns
Emp #, Employee, Job, and Hire Date, respectively. Then run the query again.
SELECT employee_id "Emp #", last_name "Employee",
job_id "Job", hire_date "Hire Date"
FROM employees;
2. The HR department has requested a report of all employees and their job IDs. Display the
last name concatenated with the job ID (separated by a comma and space) and name the
column Employee and Title.
SELECT last_name||', '||job_id "Employee and Title"
FROM employees;
Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 9
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
3. To familiarize yourself with the data in the EMPLOYEES table, create a query to display all
the data from that table. Separate each column output by a comma. Name the column
THE_OUTPUT.
Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 10
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Practices Overview
This practice covers the following topics:
• Selecting data and changing the order of the rows that are displayed
Overview
In this practice, you build more reports by using statements that use the WHERE clause and the
ORDER BY clause. You make the SQL statements more reusable and generic by including the
ampersand substitution.
2. Open a new SQL Worksheet. Create a report that displays the last name and department
number for employee number 176. Run the query.
4. Create a report to display the last name, job ID, and hire date for employees with the last
names of Matos and Taylor. Order the query in ascending order by hire date.
6. Modify lab_03_03.sql to display the last name and salary of employees who earn
between $5,000 and $12,000, and are in department 20 or 50. Label the columns
Employee and Monthly Salary, respectively. Save lab_03_03.sql as
lab_03_06.sql again. Run the statement in lab_03_06.sql.
7. The HR department needs a report that displays the last name and hire date of all
employees who were hired in 2006.
8. Create a report to display the last name and job title of all employees who do not have a
manager.
9. Create a report to display the last name, salary, and commission of all employees who earn
commissions. Sort the data in descending order of salary and commissions.
Use the column’s numeric position in the ORDER BY clause.
11. The HR department wants to run reports based on a manager. Create a query that prompts
the user for a manager ID, and generates the employee ID, last name, salary, and
department for that manager’s employees. The HR department wants the ability to sort the
report on a selected column. You can test the data with the following values:
15. Modify lab_03_06.sql to display the last name, salary, and commission for all
employees whose commission is 20%. Save lab_03_06.sql as lab_03_15.sql again.
Rerun the statement in lab_03_15.sql.
7. The HR department needs a report that displays the last name and hire date of all
employees who were hired in 2006.
SELECT last_name, hire_date
FROM employees
WHERE hire_date >= '01-JAN-06' AND hire_date < '01-JAN-07';
11. The HR department wants to run reports based on a manager. Create a query that prompts
the user for a manager ID, and generates the employee ID, last name, salary, and
department for that manager’s employees. The HR department wants the ability to sort the
report on a selected column. You can test the data with the following values:
manager _id = 103, sorted by last_name
manager_id = 201, sorted by salary
Practice Overview
This practice covers the following topics:
• Writing a query that displays the current date
2. The HR department needs a report to display the employee number, last name, salary, and
salary increased by 15.5% (expressed as a whole number) for each employee. Label the
column New Salary. Save your SQL statement in a file named lab_04_02.sql.
3. Run your query in the lab_04_02.sql file.
4. Modify your query in the lab_04_02.sql to add a column that subtracts the old salary
from the new salary. Label the column Increase. Save the contents of the file as
lab_04_04.sql. Run the revised query.
b. Rewrite the query so that the user is prompted to enter a letter that the last name starts
with. For example, if the user enters “H” (capitalized) when prompted for a letter, the
output should show all employees whose last name starts with the letter “H.”
Note: Because this query depends on the date when it was executed, the values in the
MONTHS_WORKED column will differ for you.
7. Create a query to display the last name and salary for all employees. Format the salary to
be 15 characters long, left-padded with the $ symbol. Label the column SALARY.
8. Create a query that displays the first eight characters of the employees’ last names, and
indicates the amounts of their salaries with asterisks. Each asterisk signifies a thousand
dollars. Sort the data in descending order of salary. Label the column
EMPLOYEES_AND_THEIR_SALARIES.
2. The HR department needs a report to display the employee number, last name, salary, and
salary increased by 15.5% (expressed as a whole number) for each employee. Label the
column New Salary. Save your SQL statement in a file named lab_04_02.sql.
SELECT employee_id, last_name, salary,
ROUND(salary * 1.155, 0) "New Salary"
FROM employees;
4. Modify your query in the lab_04_02.sql to add a column that subtracts the old salary
from the new salary. Label the column Increase. Save the contents of the file as
lab_04_04.sql. Run the revised query.
SELECT employee_id, last_name, salary,
ROUND(salary * 1.155, 0) "New Salary",
ROUND(salary * 1.155, 0) - salary "Increase"
FROM employees;
b. Rewrite the query so that the user is prompted to enter a letter that starts the last
name. For example, if the user enters H (capitalized) when prompted for a letter, the
output should show all employees whose last name starts with the letter “H.”
SELECT INITCAP(last_name) "Name",
LENGTH(last_name) "Length"
FROM employees
8. Create a query that displays the first eight characters of the employees’ last names, and
indicates the amounts of their salaries with asterisks. Each asterisk signifies a thousand
dollars. Sort the data in descending order of salary. Label the column
EMPLOYEES_AND_THEIR_SALARIES.
9. Create a query to display the last name and the number of weeks employed for all
employees in department 90. Label the number of weeks column as TENURE. Truncate the
number of weeks value to 0 decimal places. Show the records in descending order of the
employee’s tenure.
Note: The TENURE value will differ because it depends on the date when you run the query.
SELECT last_name, trunc((SYSDATE-hire_date)/7) AS TENURE
FROM employees
WHERE department_id = 90
ORDER BY TENURE DESC;
Chapter 4 - Page 12
Practices for Lesson 4: Using Single-Row Functions to Customize Output
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
Oracle University and Rumos Formacao e Comunicacao (Portugal) use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Practice Overview
This practice covers the following topics:
• Creating queries that use TO_CHAR, and TO_DATE functions.
Overview
This practice provides a variety of exercises using the TO_CHAR and TO_DATE functions, and
conditional expressions such as DECODE and CASE.
2. Display each employee’s last name, hire date, and salary review date, which is the first
Monday after six months of service. Label the column REVIEW. Format the dates to
appear in a format that is similar to “Monday, the Thirty-First of July, 2000.”
3. Create a query that displays employees’ last names and commission amounts. If an
employee does not earn commission, show “No Commission.” Label the column COMM.
Chapter 5 - Page 6
Practices for Lesson 5: Using Conversion Functions and Conditional Expressions
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
Oracle University and Rumos Formacao e Comunicacao (Portugal) use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
5. Rewrite the statement in the preceding exercise by using the CASE syntax.
4. Using the DECODE function, write a query that displays the grade of all employees based on
the value of the JOB_ID column, using the following data:
Job Grade
AD_PRES A
ST_MAN B
IT_PROG C
SA_REP D
ST_CLERK E
None of the above 0
5. Rewrite the statement in the preceding exercise by using the CASE syntax.
SELECT job_id, CASE job_id
WHEN 'ST_CLERK' THEN 'E'
WHEN 'SA_REP' THEN 'D'
WHEN 'IT_PROG' THEN 'C'
WHEN 'ST_MAN' THEN 'B'
WHEN 'AD_PRES' THEN 'A'
ELSE '0' END GRADE
FROM employees;
Chapter 5 - Page 10
Practices for Lesson 5: Using Conversion Functions and Conditional Expressions
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
Oracle University and Rumos Formacao e Comunicacao (Portugal) use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Practice Overview
This practice covers the following topics:
• Writing queries that use the group functions
Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 2
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Overview
After completing this practice, you should be familiar with using group functions and selecting
groups of data.
5. Modify the query in lab_06_04.sql to display the minimum, maximum, sum, and
average salary for each job type. Save lab_06_04.sql as lab_06_05.sql again.
Run the statement in lab_06_05.sql.
Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
6. Write a query to display the number of people with the same job.
7. Determine the number of managers without listing them. Label the column Number of
Managers.
Hint: Use the MANAGER_ID column to determine the number of managers.
8. Find the difference between the highest and lowest salaries. Label the column
DIFFERENCE.
Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 4
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 5
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
5. Modify the query in lab_06_04.sql to display the minimum, maximum, sum, and average
salary for each job type. Save lab_06_04.sql as lab_06_05.sql again. Run the
statement in lab_06_05.sql.
SELECT job_id, ROUND(MAX(salary),0) "Maximum",
ROUND(MIN(salary),0) "Minimum",
ROUND(SUM(salary),0) "Sum",
ROUND(AVG(salary),0) "Average"
FROM employees
GROUP BY job_id;
6. Write a query to display the number of people with the same job.
SELECT job_id, COUNT(*)
FROM employees
GROUP BY job_id;
Generalize the query so that the user in the HR department is prompted for a job title.
Save the script to a file named lab_06_06.sql. Run the query. Enter IT_PROG when
prompted and click OK.
Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 6
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
7. Determine the number of managers without listing them. Label the column Number of
8. Find the difference between the highest and lowest salaries. Label the column
DIFFERENCE.
SELECT MAX(salary) - MIN(salary) DIFFERENCE
FROM employees;
10. Create a query that displays the total number of employees and, of that total, the number of
employees hired in 2005, 2006, 2007, and 2008. Create appropriate column headings.
SELECT COUNT(*) total,
SUM(DECODE(TO_CHAR(hire_date, 'YYYY'),2005,1,0))"2005",
SUM(DECODE(TO_CHAR(hire_date, 'YYYY'),2006,1,0))"2006",
SUM(DECODE(TO_CHAR(hire_date, 'YYYY'),2007,1,0))"2007",
SUM(DECODE(TO_CHAR(hire_date, 'YYYY'),2008,1,0))"2008"
FROM employees;
Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 7
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
11. Create a matrix query to display the job, the salary for that job based on the department
number, and the total salary for that job, for departments 20, 50, 80, and 90, giving each
column an appropriate heading.
SELECT job_id "Job",
SUM(DECODE(department_id , 20, salary)) "Dept 20",
SUM(DECODE(department_id , 50, salary)) "Dept 50",
Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 8
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Practice Overview
This practice covers the following topics:
• Joining tables using an equijoin
Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 2
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Overview
This practice is intended to give you experience in extracting data from multiple tables using the
SQL:1999–compliant joins.
2. The HR department needs a report of all employees with corresponding departments. Write
a query to display the last name, department number, and department name for these
employees.
3. The HR department needs a report of employees in Toronto. Display the last name, job,
department number, and the department name for all employees who work in Toronto.
Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
4. Create a report to display employees’ last names and employee numbers along with their
managers’ last names and manager numbers. Label the columns Employee, Emp#,
Manager, and Mgr#, respectively. Save your SQL statement as lab_07_04.sql. Run the
query.
Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 4
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
6. Create a report for the HR department that displays employee last names, department
numbers, and all the employees who work in the same department as a given employee.
Give each column an appropriate label. Save the script to a file named lab_07_06.sql.
7. The HR department needs a report on job grades and salaries. To familiarize yourself with
the JOB_GRADES table, first show the structure of the JOB_GRADES table. Then create a
query that displays the name, job, department name, salary, and grade for all employees.
Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 5
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 6
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
9. The HR department needs to find the names and hire dates of all employees who were
hired before their managers, along with their managers’ names and hire dates. Save the
script to a file named lab_07_09.sql.
Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 7
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 8
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
6. Create a report for the HR department that displays employee last names, department
numbers, and all employees who work in the same department as a given employee. Give
each column an appropriate label. Save the script to a file named lab_07_06.sql. Run
the query.
SELECT e.department_id department, e.last_name employee,
c.last_name colleague
Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 9
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 7 - Page 10
Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
Oracle University and Rumos Formacao e Comunicacao (Portugal) use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Practice Overview
This practice covers the following topics:
• Creating subqueries to query values based on unknown criteria
2. Create a report that displays the employee number, last name, and salary of all employees
who earn more than the average salary. Sort the results in ascending order by salary.
3. Write a query that displays the employee number and last name of all employees who work
in a department with any employee whose last name contains the letter “u.” Save your SQL
statement as lab_08_03.sql. Run your query.
Modify the query so that the user is prompted for a location ID. Save this to a file named
lab_08_04.sql.
5. Create a report for HR that displays the last name and salary of every employee who
reports to King.
6. Create a report for HR that displays the department number, last name, and job ID for every
employee in the Executive department.
7. Create a report that displays a list of all employees whose salary is more than the salary of
any employee from department 60.
UNDEFINE Enter_name
3. Write a query that displays the employee number and last name of all employees who work
in a department with any employee whose last name contains the letter “u.” Save your SQL
statement as lab_08_03.sql. Run your query.
SELECT employee_id, last_name
FROM employees
WHERE department_id IN (SELECT department_id
FROM employees
WHERE last_name like '%u%');
4. The HR department needs a report that displays the last name, department number, and
job ID of all employees whose department location ID is 1700.
Modify the query so that the user is prompted for a location ID. Save this to a file named
lab_08_04.sql.
SELECT last_name, department_id, job_id
FROM employees
WHERE department_id IN (SELECT department_id
FROM departments
WHERE location_id =
&Enter_location);
5. Create a report for HR that displays the last name and salary of every employee who
reports to King.
SELECT last_name, salary
FROM employees
WHERE manager_id = (SELECT employee_id
FROM employees
WHERE last_name = 'King');
6. Create a report for HR that displays the department number, last name, and job ID for every
employee in the Executive department.
SELECT department_id, last_name, job_id
FROM employees
WHERE department_id IN (SELECT department_id
FROM departments
WHERE department_name =
'Executive');
7. Create a report that displays a list of all employees whose salary is more than the salary of
any employee from department 60.
SELECT last_name FROM employees
WHERE salary > ANY (SELECT salary
FROM employees
WHERE department_id=60);
Practice Overview
In this practice, you create reports by using the following:
• UNION operator
2. The HR department needs a list of countries that have no departments located in them.
Display the country IDs and the names of the countries. Use the set operators to create this
report.
3. Produce a list of jobs for departments 10, 50, and 20, in that order. Display the job ID and
department ID by using the set operators.
4. Create a report that lists the employee IDs and job IDs of those employees who currently
have a job title that is the same as their previous one (that is, they changed jobs but have
now gone back to doing the same job they did previously).
Chapter 9 - Page 4
Copyright © 2013, Oracle and/or its affiliates. All rights reserved.
Oracle University and Rumos Formacao e Comunicacao (Portugal) use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Lesson Overview
This practice covers the following topics:
• Inserting rows into tables
Tasks
Insert data into the MY_EMPLOYEE table.
1. Run the statement in the lab_10_01.sql script to build the MY_EMPLOYEE table used in
this practice.
2. Describe the structure of the MY_EMPLOYEE table to identify the column names.
3. Create an INSERT statement to add the first row of data to the MY_EMPLOYEE table from
the following sample data. Do not list the columns in the INSERT clause. Do not enter all
rows yet.
4. Populate the MY_EMPLOYEE table with the second row of the sample data from the
preceding list. This time, list the columns explicitly in the INSERT clause.
5. Confirm your addition to the table.
6. Write an INSERT statement in a dynamic reusable script file to load the remaining rows into
the MY_EMPLOYEE table. The script should prompt for all the columns (ID, LAST_NAME,
FIRST_NAME, USERID, and SALARY). Save this script to a lab_10_06.sql file.
7. Populate the table with the next two rows of the sample data listed in step 3 by running the
INSERT statement in the script that you created.
8. Confirm your additions to the table.
26. Confirm that the new row was added with the correct USERID.
3. Create an INSERT statement to add the first row of data to the MY_EMPLOYEE table from
the following sample data. Do not list the columns in the INSERT clause.
4. Populate the MY_EMPLOYEE table with the second row of the sample data from the
preceding list. This time, list the columns explicitly in the INSERT clause.
INSERT INTO my_employee (id, last_name, first_name,
userid, salary)
VALUES (2, 'Dancs', 'Betty', 'bdancs', 860);
6. Write an INSERT statement in a dynamic reusable script file to load the remaining rows into
the MY_EMPLOYEE table. The script should prompt for all the columns (ID, LAST_NAME,
FIRST_NAME, USERID, and SALARY). Save this script to a file named lab_10_06.sql.
INSERT INTO my_employee
VALUES (&p_id, '&p_last_name', '&p_first_name',
7. Populate the table with the next two rows of the sample data listed in step 3 by running the
INSERT statement in the script that you created.
INSERT INTO my_employee
VALUES (&p_id, '&p_last_name', '&p_first_name',
'&p_userid', &p_salary);
11. Change the salary to $1,000 for all employees with a salary less than $900.
UPDATE my_employee
SET salary = 1000
WHERE salary < 900;
SET VERIFY ON
SET ECHO ON
UNDEFINE p_first_name
UNDEFINE p_last_name
26. Confirm that the new row was added with the correct USERID.
SELECT *
FROM my_employee
WHERE ID='6';
Lesson Overview
This practice covers the following topics:
• Creating new tables
2. Create the EMP table based on the following table instance chart. Save the statement in a
script called lab_11_02.sql, and then execute the statement in the script to create the
table. Confirm that the table is created.
3. Modify the EMP table. Add a COMMISSION column of the NUMBER data type, with precision 2
and scale 2. Confirm your modification.
4. Modify the EMP table to allow for longer employee last names. Confirm your modification.
5. Drop the FIRST_NAME column from the EMP table. Confirm your modification by checking
the description of the table.
2. Create the EMP table based on the following table instance chart. Save the statement in a
script called lab_11_02.sql, and then execute the statement in the script to create the
table. Confirm that the table is created.
To confirm that the table was created and to view its structure:
DESCRIBE emp
3. Modify the EMP table. Add a COMMISSION column of the NUMBER data type, with precision 2
and scale 2. Confirm your modification.
DESCRIBE emp
4. Modify the EMP table to allow for longer employee last names. Confirm your modification.
ALTER TABLE emp
MODIFY (last_name VARCHAR2(50));
DESCRIBE emp
5. Drop the FIRST_NAME column from the EMP table. Confirm your modification by checking
the description of the table.
ALTER TABLE emp
DROP COLUMN first_name;
DESCRIBE emp
6. In the EMP table, mark the DEPT_ID column as UNUSED. Confirm your modification by
checking the description of the table.
DESCRIBE emp
8. Create the EMPLOYEES2 table based on the structure of the EMPLOYEES table. Include only
the EMPLOYEE_ID, FIRST_NAME, LAST_NAME, SALARY, and DEPARTMENT_ID columns.
Name the columns in your new table ID, FIRST_NAME, LAST_NAME, SALARY, and
DEPT_ID, respectively. Confirm that the table is created.
CREATE TABLE employees2 AS
SELECT employee_id id, first_name, last_name, salary,
11. Revert the EMPLOYEES2 table to the read/write status. Now try to add the same column
again.
Now, because the table is assigned a READ WRITE status, you will be allowed to add a
column to the table.
ALTER TABLE employees2 READ WRITE;
Practices Overview
In these practices, you will be working on extra exercises that are based on the following topics:
• Basic SQL SELECT statement
Overview
In this practice, exercises have been designed to be worked on after you have discussed the
following topics: basic SQL SELECT statement, basic SQL Developer commands, and SQL
functions.
2. The HR department needs a report of employees who earn a commission. Show the last
name, job, salary, and commission of these employees. Sort the data by salary in
descending order.
3. For budgeting purposes, the HR department needs a report on projected raises. The report
should display those employees who have no commission, but who have a 10% raise in
salary (round off the salaries).
4. Create a report of employees and their duration of employment. Show the last names of all
the employees together with the number of years and the number of completed months that
they have been employed. Order the report by the duration of their employment. The
employee who has been employed the longest should appear at the top of the list.
6. Create a report that displays all employees, and indicate with the words Yes or No whether
they receive a commission. Use the DECODE expression in your query.
8. Find the number of employees who have a last name that ends with the letter “n.” Create
two possible solutions.
9. Create a report that shows the name, location, and number of employees for each
department. Make sure that the report also includes department_IDs without employees.
11. Create a report that displays the jobs that are found in the Administration and Executive
departments. Also display the number of employees for these jobs. Show the job with the
highest number of employees first.
These exercises can be used for extra practice after you have discussed the following
topics: basic SQL SELECT statements, basic SQL Developer commands, SQL functions,
joins, group functions, and subqueries.
12. Show all the employees who were hired in the first half of the month (before the 16th of the
month, irrespective of the year).
13. Create a report that displays the following for all employees: last name, salary, and salary
expressed in terms of thousands of dollars.
15. Show the department number, name, number of employees, and average salary of all the
departments, together with the names, salaries, and jobs of the employees working in each
department.
17. Create a report that displays departments where no sales representatives work. Include the
department number, department name, manager ID, and location in the output.
18. Create the following statistical reports for the HR department. Include the department
number, department name, and the number of employees working in each department that:
a. Employs fewer than three employees:
19. Create a report that displays the employee number, last name, salary, department number,
and the average salary in their department for all employees.
20. Create an anniversary overview based on the hire date of the employees. Sort the
anniversaries in ascending order.
Overview
Solutions to the Additional Practice 1-1 are given as follows.
Tasks
2. The HR department needs a report of employees who earn a commission. Show the last
name, job, salary, and commission of these employees. Sort the data by 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. For budgeting purposes, the HR department needs a report on projected raises. The report
should display those employees who do not get a commission but who have a 10% raise in
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. Create a report of employees and the duration of their employment. Show the last names of
all employees, together with the number of years and the number of completed months that
they have been employed. Order the report by the duration of their employment. The
employee who has been employed the longest should appear at the top of the list.
SELECT last_name,
TRUNC(MONTHS_BETWEEN(SYSDATE, hire_date) / 12) YEARS,
TRUNC(MOD(MONTHS_BETWEEN(SYSDATE, hire_date), 12))
MONTHS
FROM employees
ORDER BY years DESC, MONTHS desc;
5. Show those employees who have a last name that starts with the letters “J,” “K,” “L,” or “M.”
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: basic SQL SELECT statement, basic SQL Developer commands, SQL functions,
joins, and group functions.
7. Create a report that displays the department name, location ID, last name, job title, and
salary of those employees who work in a specific location. Prompt the user for a location.
Enter 1800 for location_id when prompted.
SELECT d.department_name, d.location_id, e.last_name, e.job_id,
e.salary
FROM employees e JOIN departments d
ON e.department_id = d.department_id
AND d.location_id = &location_id;
8. Find the number of employees who have a last name that ends with the letter “n.” Create
two possible solutions.
SELECT COUNT(*)
FROM employees
WHERE last_name LIKE '%n';
--or
SELECT COUNT(*)
FROM employees
WHERE SUBSTR(last_name, -1) = 'n';
9. Create a report that shows the name, location, and number of employees for each
department. Make sure that the report also includes department_IDs without employees.
SELECT d.department_id, d.department_name,
d.location_id, COUNT(e.employee_id)
FROM employees e RIGHT OUTER JOIN departments d
ON e.department_id = d.department_id
GROUP BY d.department_id, d.department_name, d.location_id;
10. The HR department needs to find the job titles in departments 10 and 20. Create a report to
display the job IDs for these departments.
SELECT DISTINCT job_id
FROM employees
WHERE department_id IN (10, 20);
These exercises can be used for extra practice after you have discussed the following
topics: basic SQL SELECT statements, basic SQL Developer commands, SQL functions,
joins, group functions, and subqueries.
12. Show all employees who were hired in the first half of the month (before the 16th of the
month, irrespective of the year).
SELECT last_name, hire_date
FROM employees
WHERE TO_CHAR(hire_date, 'DD') < 16;
13. Create a report that displays the following for all employees: last name, salary, and salary
expressed in terms of thousands of dollars.
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 employees e JOIN employees m
ON e.manager_id = m.employee_id
JOIN job_grades j
ON m.salary BETWEEN j.lowest_sal AND j.highest_sal
AND m.salary > 15000;
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.
16. Create a report to display the department number and 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. Create a report that displays the departments where no sales representatives work. Include
the department number, department name, manager ID, and location in the output.
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. Create the following statistical reports for the HR department. Include the department
number, department name, and the number of employees working in each department that:
a. Employs fewer than three employees:
SELECT d.department_id, d.department_name, COUNT(*)
FROM departments d JOIN employees e
19. Create a report that displays 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, e.salary,
AVG(s.salary)
FROM employees e JOIN employees s
ON e.department_id = s.department_id
GROUP BY e.employee_id, e.last_name, e.department_id,
e.salary;
20. Create an anniversary overview based on the hire date of employees. Sort the
anniversaries in ascending order.
Overview
In this case study, you build a set of database tables for an online book store (E-Commerce
Shopping Cart). After you create the tables, you insert, update, and delete records in the book
The following is a diagram of the table and columns for the online book store application:
Note: If you want to build the tables, you can execute the commands in the
Online_Book_Store_Create_Table.sql script in SQL Developer. If you want to drop the
tables, you can execute the commands in the Online_Book_Store_Drop_Tables.sql
script in SQL Developer. Then you can execute the commands in the
<<Online_Book_Store_Populate.sql>> script in SQL Developer to create and populate
the tables.
All the three SQL scripts are present in the /home/oracle/labs/sql1/labs folder.
• If you use the Online_Book_Store_Create_Table.sql script to build the tables,
start with step 2.
• If you use the Online_Book_Store_Drop_Tables.sql script to remove the tables,
start with step 1.
• If you use the Online_Book_Store_Populate.sql script to build and populate the
tables, start with step 6.
Practice 1-2
Overview
In this practice, you create the tables based on the following table instance charts. Select the
appropriate data types and be sure to add integrity constraints.
b. Enter a shopping cart detail for the book details that you just entered in 7(a).
8. Create a report that contains each customer’s history of purchasing books. Be sure to
include the customer name, customer ID, book ID, date of purchase, and shopping cart ID.
Save the commands that generate the report in a script file named lab_apcs_8.sql.
Note: Your results may be different.
Solution 1-2
Overview
The solution to the Practice 1-2 is given as follows.
Tasks
b. BOOKS
CREATE TABLE BOOKS
(
Book_ID VARCHAR2 (10) NOT NULL ,
Book_Name VARCHAR2 (50) ,
Author_ID VARCHAR2 (10) NOT NULL ,
Price NUMBER (10) ,
Publisher_ID VARCHAR2 (10) NOT NULL
)
;
c. CUSTOMER
CREATE TABLE CUSTOMER
(
Customer_ID VARCHAR2 (6) NOT NULL ,
Customer_Name VARCHAR2 (40) ,
d. CREDIT_CARD_DETAILS
CREATE TABLE CREDIT_CARD_DETAILS
(
Credit_Card_Number VARCHAR2 (20) NOT NULL ,
Credit_Card_Type VARCHAR2 (10) ,
Expiry_Date DATE
)
;
e. ORDER_DETAILS
CREATE TABLE ORDER_DETAILS
(
Order_ID VARCHAR2 (6) NOT NULL ,
Customer_ID VARCHAR2 (6) NOT NULL ,
f. PUBLISHER
CREATE TABLE PUBLISHER
(
Publisher_ID VARCHAR2 (10) NOT NULL ,
Publisher_Name VARCHAR2 (50)
)
;
g. PURCHASE_HISTORY
CREATE TABLE PURCHASE_HISTORY
(
Customer_ID VARCHAR2 (6) NOT NULL ,
Order_ID VARCHAR2 (6) NOT NULL
)
;
h. SHIPPING_TYPE
CREATE TABLE SHIPPING_TYPE
(
Shipping_Type VARCHAR2 (10) NOT NULL ,
Shipping_Price NUMBER (6)
i. SHOPPING _CART
CREATE TABLE SHOPPING_CART
(
Shopping_Cart_ID VARCHAR2 (6) NOT NULL ,
Book_ID VARCHAR2 (10) NOT NULL ,
Price NUMBER (10) ,
Shopping_cart_Date DATE ,
Quantity NUMBER (6)
)
;
Shipping_Type
)
REFERENCES SHIPPING_TYPE
(
Shipping_Type
3. Verify that the tables were created properly by checking in the Connections Navigator in
SQL Developer. In the Connections Navigator, expand Connections > myconnection >
Tables.
4. Create a sequence to uniquely identify each row in the ORDER DETAILS table.
a. Start with 100; do not allow caching of the values. Name the sequence ORDER_ID_SEQ.
CREATE SEQUENCE order_id_seq
START WITH 100
NOCACHE;
b. Verify the existence of the sequences in the Connections Navigator in SQL Developer.
In the Connections Navigator, assuming that the myconnection node is expanded,
expand Sequences.
You can alternatively also query the user_sequences data dictionary view:
SELECT * FROM user_sequences;
Publisher_ID Publisher_Name
PN0001 Elsevier
PN0002 Penguin Group
PN0003 Pearson Education
PN0004 Cambridge University Press
PN0005 Dorling Kindersley
c. SHIPPING _TYPE
Shipping_Type Shipping_Price
USPS 200
FedEx 250
DHL 150
d. CUSTOMER
e. CREDIT_CARD_DETAILS
f. BOOKS
Book _ID Book _Name Author _ID Price Publisher _ID
BN0001 Florentine Tragedy AN0002 150 PN0002
BN0002 A Vision AN0002 100 PN0003
BN0003 Citizen of the World AN0001 100 PN0001
i. PURCHASE_HISTORY
Customer _ID Order _ID
CN0001 OD0001
CN0003 OD0002
CN0004 OD0005
SELECT *
FROM customer_details
ORDER BY customer_id;
b. Enter a shopping cart detail for the book details that you just entered in 7(a).
8. Create a report that contains each customer’s history of purchasing books. Be sure to
include the customer name, customer ID, book ID, date of purchase, and shopping cart ID.
Save the commands that generate the report in a script file named lab_apcs_8.sql.
Note: Your results may be different.