Professional Documents
Culture Documents
s a
co) ha
u ฺ ฺ
Oracle Database a ฺ ed 12c: i d eSQL
s e n G u
Workshop i
m Iden t
@
ila s Stu
c h
( g e thi Guide
ar Activity
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
D80190GC11
Edition 1.1
July 2014
D87242
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
The information contained in this document is subject to change without notice. If you find any problems in the document, please
report them in writing to: Oracle University, 500 Oracle Parkway, Redwood Shores, California 94065 USA. This document is not
warranted to be error-free.
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:
Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement........................................... 2-1
Practices for Lesson 2: Overview............................................................................................................. 2-2
Practice 2-1: Retrieving Data Using the SQL SELECT Statement ............................................................. 2-3
Solution 2-1: Retrieving Data Using the SQL SELECT Statement ............................................................. 2-8
Practices for Lesson 3: Restricting and Sorting Data .............................................................................. 3-1
Practices for Lesson 3: Overview............................................................................................................. 3-2
Practice 3-1: Restricting and Sorting Data................................................................................................ 3-3
Solution 3-1: Restricting and Sorting Data................................................................................................ 3-7
Practices for Lesson 4: Using Single-Row Functions to Customize Output ........................................... 4-1 s a
) ha
Practices for Lesson 4: Overview............................................................................................................. 4-2
co
Practice 4-1: Using Single-Row Functions to Customize Output................................................................ 4-3
u ฺ
ฺ ed ideฺ
Solution 4-1: Using Single-Row Functions to Customize Output................................................................ 4-9
a
Practices for Lesson 5: Using Conversion Functions and Conditional Expressions
s e G u 5-1
n .............................
m den i t
Practices for Lesson 5: Overview............................................................................................................. 5-2
Practice 5-1: Using Conversion Functions and Conditional Expressions @ tu
ila ....................................................
.................................................... 5-3
Solution 5-1: Using Conversion Functions and Conditional Expressions
r c h is S 5-9
Practices for Lesson 6: Reporting Aggregated Data(Using the Group g a t h
e Functions................................... 6-1
r o n u s
l d
a by Using t o
Practices for Lesson 6: Overview............................................................................................................. 6-2
G uData
Practice 6-1: Reporting Aggregated Data
bye n se Group Functions......................................................... 6-3
Solution 6-1: Reporting Aggregated
ila e lifrom c Using Group Functions......................................................... 6-6
Practices for Lessonc 7:h
DisplayinglData Multiple Tables Using Joins ............................................ 7-1
A r 7: Overview
r a b
o
Practices for Lesson
s f e ............................................................................................................. 7-2
i l l erm
Practice
t r a n Data
7-1: Displaying Data from Multiple Tables by Using Joins............................................................ 7-3
u on-
Solution
GPractices
7-1: Displaying from Multiple Tables by Using Joins............................................................ 7-8
n for Lesson 8: Using Subqueries to Solve Queries ................................................................... 8-1
Practices for Lesson 8: Overview............................................................................................................. 8-2
Practice 8-1: Using Subqueries to Solve Queries ..................................................................................... 8-3
Solution 8-1: Using Subqueries to Solve Queries ..................................................................................... 8-6
Practices for Lesson 9: Using the Set Operators ..................................................................................... 9-1
Practices for Lesson 9: Overview............................................................................................................. 9-2
Practice 9-1: Using Set Operators ........................................................................................................... 9-3
Solution 9-1: Using Set Operators ........................................................................................................... 9-5
Practices for Lesson 10: Manipulating Data............................................................................................. 10-1
Practices for Lesson 10: Overview ........................................................................................................... 10-2
Practice 10-1: Managing Tables by Using DML Statements ...................................................................... 10-3
Solution 10-1: Managing Tables by Using DML Statements ...................................................................... 10-7
Practices for Lesson 11: Using DDL Statements to Create and Manage Tables ..................................... 11-1
Practices for Lesson 11: Overview ........................................................................................................... 11-2
Practice 11-1: Introduction to Data Definition Language ........................................................................... 11-3
Solution 11-1: Introduction to Data Definition Language ........................................................................... 11-7
Additional Practices and Solutions .......................................................................................................... 12-1
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
s a
co ) ha
u ฺ
a ฺ ed ideฺ
Practices for i s en t G1:u
Lesson
@ m den
c h ila s Stu
Introduction
( g ar e1 thi
Chapter
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
In some of the practices, there may be exercises that are prefaced with the phrases “If you have
time” or “If you want an extra challenge.” Work on these exercises only if you have completed all
other exercises within the allocated time, and would like an additional challenge to your skills.
Perform the practices slowly and precisely. You can experiment with saving and running
command files. If you have any questions at any time, ask your instructor.
Notes
• 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
s a
) ha
SQL*Plus that is available in this course.
• co
For any query, the sequence of rows retrieved from the database may differ from
u ฺ
the screenshots shown.
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
@ m den
b. Create a database connection by using the following information:
Connection Name: myconnection c h ila s Stu
Username: ora1 ( g ar e thi
Password: ora1
l d ron to us
ua ense
Hostname: localhost
G
i la le lic
Port: 1521
h
A rcORCLrab
SID:
r m o that you
Ensure n s fe
select the Save Password check box.
l l e
i 3. Testing r a
t the Oracle SQL Developer Database Connection and Connecting to the
on-
Gu nDatabase
a. Test the new connection.
b. If the status is Success, connect to the database by 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
b. Browse the structure of the EMPLOYEES table.
c. View the data of the DEPARTMENTS table.
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
b. Create a database connection by using the following
d e n
m information:
i. Connection Name: myconnection
@
ila s Stu
c h
ii. Username: ora1
( g ar e thi
iii. Password: ora1on
d r t o us
iv. Hostname: l
ualocalhost se
G e n
v. Port:
h i l a 1521 e l ic
rc vi. SID: a l
bORCL
A
o Ensure r
fethat you select the Save Password check box.
e r m n s
u ill n-tra
G no
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
tu
ila s bySusing
hdatabase
a c
b. If the status is Success, connect to rthe
t h i this new connection.
n ( g s e
o
dr e to u
a l
u ens
G
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
When you create a connection, a SQL Worksheet for that connection opens automatically.
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
4. Browsing the Tables in the Connections Navigator
h i la Stu
c
a. In the Connections Navigator, viewrthe objectsis
a tables tharethat are available to you in the
( g
Tables node. Verify that the following e present:
COUNTRIES
l d ron to us
DEPARTMENTS ua se
EMPLOYEES G e n
h i
JOB_GRADESla le lic
A rc rab
JOB_HISTORY
r m o JOBSsfe
u
e an
ill n-trLOCATIONS
G no REGIONS
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
c. View the data of the DEPARTMENTS table. @
m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
s a
co ) ha
u ฺ
a ฺ ed ideฺ
Practices for i s en t G2:u
Lesson
@ m den
Retrieving
h ila sData
S tu Using the
c
ar SELECT
SQL thi Statement
( g e
d t o us 2
ron Chapter
l
ua ense
G
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 1
Practices for Lesson 2: Overview
Practice Overview
This practice covers the following topics:
• Selecting all data from different tables
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 2
Practice 2-1: Retrieving Data Using the SQL SELECT Statement
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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
Task 1
Test your knowledge:
1. The following SELECT statement executes successfully:
SELECT last_name, job_id, salary AS Sal
FROM employees;
True/False
s a
2. The following SELECT statement executes successfully:
co ) ha
u ฺ
SELECT *
a ฺ ed ideฺ
FROM job_grades;
i s en t Gu
@ m den
True/False
c h ila s Stu
( g ar e thi
3. There are four coding errors in thero
d following
t o us Can you identify them?
n statement.
l
ua enlast_name
se
SELECT
G
employee_id,
a e SALARY
sal x 12 ilANNUAL
h l lic
FROM rc
o rab
A feemployees;
Task 2rm
e a n s
l l r
ui theofollowing
-t points before you begin with the practices:
GNote n n
• 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 modify 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
4. Your first task is to determine the structure of the DEPARTMENTS table and its contents.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
m andditse n
5. Your task is to determine the structure of the EMPLOYEES
i @
la Stu contents.
table
a. Determine the structure of the EMPLOYEES
h
rctable. this
( g a e
o n u s
a l dr e to
G u ens
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 4
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_5b.sql so that you can dispatch this file to the HR department. Test your
query in the lab_02_5b.sql file to ensure that it runs correctly.
Note: After you have executed the query, make sure that you do not enter your next query
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 5
6. The HR department wants a query to display all unique job IDs from the EMPLOYEES table.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
s a
co ) ha
u ฺ
Task 3 a ฺ ed ideฺ
s e n G u
If you have time, complete the following exercises: i
m den t
7. The HR department wants more descriptive columnila @ tuits report on employees.
headings for
c h
Copy the statement from lab_02_5b.sql tora new SQLis
S
Worksheet. Name the columns
Emp #, Employee, Job, and Hire Date, ( g a e thThen
respectively. run the query again.
o n u s
a l dr e to
G u ens
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 6
8. 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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
… s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
If you want an extra challenge, complete the following exercise:
Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 7
Solution 2-1: Retrieving Data Using the SQL SELECT Statement
Task 1
Test your knowledge:
1. The following SELECT statement executes successfully:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
True/False
ฺ c o
True/False u
ed ideฺ
a ฺ
i s en t Gu
3. There are four coding errors in the following statement. Can
d e n them?
myou identify
@
ila s Stu
c h
thi
SELECT employee_id, last_name
sal x 12 ANNUAL SALARY (ga
r
employees; ron us e
FROM
l d t o
The EMPLOYEES table does
G ua not e n se a column called sal. The column is called
contain
SALARY.
h i la le lic
rc raoperator
The multiplication
A b is *, not x, as shown in line 2.
rThe
o
m ANNUAL f e
sSALARY alias cannot include spaces. The alias should read
l l e r
i ANNUAL_SALARYa n
n-t
Gu nAocomma
or should be enclosed within double quotation marks.
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.
4. 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;
Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 8
5. Your task is to determine the structure of the EMPLOYEES table and its contents.
a. Determine the structure of the EMPLOYEES table.
DESCRIBE employees
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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
STARTDATE for the HIRE_DATE column. Save your SQL statement to a file named
lab_02_5b.sql so that you can dispatch this file to the HR department. Test your
query in the lab_02_5b.sql file to ensure that it runs correctly.
SELECT employee_id, last_name, job_id, hire_date StartDate
FROM employees;
6. The HR department wants a query to display all unique job IDs from the EMPLOYEES table. a
s
SELECT DISTINCT job_id
co ) ha
FROM employees;
u ฺ
a ฺ ed ideฺ
Task 3 i s en t Gu
@ m den
If you have time, complete the following exercises:
h i la Stu
7. The HR department wants more descriptive column c thisWorksheet.
atora neweheadings for its report on employees.
Copy the statement from lab_02_5b.sql ( g SQL
s Then run the query
n respectively. Name the columns
Emp #, Employee, Job, and Hirero
d Date,
t o u again.
l
ua"Emp se last_name "Employee",
SELECT employee_id G e n#",
h i la "Job",
job_id
l e lichire_date "Hire Date"
FROM Arc
o f e rab
employees;
l l e rm rans
i HR t
-department
G8.u The n o n 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
If you want an extra challenge, complete the following exercise:
9. 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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 10
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
s a
co ) ha
u ฺ
a ฺ ed ideฺ
Practices for i s en t G3:u
Lesson
@ m den
Restricting
h tu Sorting Data
ila s and
S
c
ar 3 thi
( g
Chapter e
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practices Overview
This practice covers the following topics:
• Selecting data and changing the order of the rows that are displayed
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
ampersand substitution.
Task
The HR department needs your assistance in creating some queries.
1. Because of budget issues, the HR department needs a report that displays the last name
and salary of employees who earn more than $12,000. Save your SQL statement as a file
named lab_03_01.sql. Run your query.
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
2. Open a new SQL Worksheet. Create a report ( g e thi the last name and department
arthat displays
number for employee number 176.
d t o us
n the query.
roRun
l
ua ense
G
h i la le lic
A rc rab
r m o
n s fe
e tra to needs
3. illThe HR department
- to find high-salary and low-salary employees. Modify
u
G no n
lab_03_01.sql display the last name and salary for any employee whose salary is not
in the range $5,000 through $12,000. Save your SQL statement as lab_03_03.sql.
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
6. Modify lab_03_03.sql to display the last name and @
m den who earn
u the columns
salary of employees
ila20 ors50.StLabel
between $5,000 and $12,000, and are in department
c h
Employee and Monthly Salary, respectively.
( g ar Savee hi
tlab_03_03.sql as
s
ron toin ulab_03_06.sql.
lab_03_06.sql again. Run the statement
l d
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
illThe HR - tra
u
7.
G employees
o n department needs a report that displays the last name and hire date of all
n 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.
10. Members of the HR department want to have more flexibility with the queries that you are
writing. They would like a report that displays the last name and salary of employees who
earn more than an amount that the user specifies after a prompt. Save this query to a file
named lab_03_10.sql. (You can use the query created in Task 1 and modify it.) If you
enter 12000 when prompted, the report displays the following results: s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d r on to us
11. The HR department wants toarun reports ebased on a manager. Create a query that prompts
the user for a manager ID,G uand generates
e n s the employee ID, last name, salary, and
department for thati l a l
manager’s i c
employees. The HR department wants the ability to sort the
c h l e
Ar fercolumn.
report on a selected
o ab You can test the data with the following values:
e rm ra=n103, s sorted by last_name:
i l l
manager_id
t
Gu non-
13. Display the last names of all employees who have both an “a” and an “e” in their last name.
s a
co ) ha
u ฺ
If you want an extra challenge, complete the following exercises:
a ฺ ed ideฺ
14. Display the last name, job, and salary for all employees whosesjobsenare either
G uthat of a
i
mnot equal
sales representative or a stock clerk, and whose salaries are e t
nto $2,500, $3,500,
@ d
or $7,000.
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
rmolab_03_06.sql
n s fe
e
15. llModify
i employees
- t r a to display the last name, salary, and commission for all
u
G non whose commission is 20%. Save lab_03_06.sql as lab_03_15.sql again.
Rerun the statement in lab_03_15.sql.
8. Create a report to display the last name and job title of all employees who do not have a
manager.
SELECT last_name, job_id
FROM employees
WHERE manager_id IS NULL;
9. Create a report to display the last name, salary, and commission for all employees who
earn commissions. Sort data in descending order of salary and commissions. Use the
column’s numeric position in the ORDER BY clause. a
s
SELECT last_name, salary, commission_pct
co ) ha
FROM employees
u ฺ
WHERE commission_pct IS NOT NULL
a ฺ ed ideฺ
ORDER BY 2 DESC, 3 DESC;
i s en t Gu
mwith the
d e n
10. Members of the HR department want to have more flexibility @
ilanames and
queries that you are
tusalary of employees who
writing. They would like a report that displays thehlast
c S
(
created in Task 1 and modify it.) Save this
ar toafter
earn more than an amount that the user specifies
gquery s e tha iprompt. (You can use the query
a file named lab_03_10.sql.
Enter 12000 when prompted: l d ron to u
G ua ense
c
h ble i
l a l
SELECT last_name, salary
i
FROM rcemployees
o
WHERE A salary
f e ra > &sal_amt;
erm12000 s
anwhen prompted for a value in a dialog box. Click OK.
u i l l
Enter
- t r
G non
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
s a
co ) ha
u ฺ
a ฺ ed ideฺ
Practices for i s en t G4:u Using
Lesson
@ m den
Single-Row
h tu
ila s SFunctions to
c
ar e thi Output
Customize
( g
d t o us 4
ron Chapter
l
ua ense
G
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practice Overview
This practice covers the following topics:
• Writing a query that displays the current date
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
• Creating queries that require the use of numeric, character, and date functions
• Performing calculations of years and months of service for an employee
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Tasks
1. Write a query to display the system date. Label the column Date.
Note: If your database is remotely located in a different time zone, the output will be the
date for the operating system on which the database resides.
2. The HR department needs a report to display the employee number, last name, salary, and s a
salary increased by 15.5% (expressed as a whole number) for each employee. Label the
co ) ha
ฺ
column New Salary. Save your SQL statement in a file named lab_04_02.sql.
u
3. Run your query in the lab_04_02.sql file. a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
illPerform- trafollowing tasks:
u
5.
G no n the
a. Write a query that displays the last name (with the first letter in uppercase and all the
other letters in lowercase) and the length of the last name for all employees whose
name starts with the letters “J,” “A,” or “M.” Give each column an appropriate label. Sort
the results by the employees’ last names.
c. Modify the query such that the case of the letter that is entered does not affect the
output. The entered letter must be capitalized before being processed by the SELECT
query.
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
c atheb following exercises:
If you have time, rcomplete
A
m
6. The s er wants to find the duration of employment for each employee. For
oHR department
f
r an display the last name and calculate the number of months between
u ille each- t r
employee,
G ntoday on and the date on which the employee was hired. Label the column as
MONTHS_WORKED. Order your results by the number of months employed. The number
of months must be rounded to the closest whole number.
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
8. A rc rab
r m o
n s fe
e
ill n-tra
u
G no
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G 9. nCreate
o 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 on which you run the
query.
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"
s a
) ha
FROM employees;
u ฺ co
3. Run your query in the file lab_04_02.sql.
a ฺ ed ideฺ
SELECT employee_id, last_name, salary, i s en t Gu
ROUND(salary * 1.155, 0) "New Salary"
@ m den
FROM employees;
c h ila s Stu
( g ar e thi
4. Modify your query in the lab_04_02.sql
d ron ttooaddusa column that subtracts the old salary
from the new salary. Label the
u l
a column s e
Increase. Save the contents of the file as
G
lab_04_04.sql. Run the revised n
cequery.
i l a l i
h ble last_name, salary,
SELECTrcemployee_id,
o A f e ra
ROUND(salary * 1.155, 0) "New Salary",
r m
e -tran s
i l l ROUND(salary * 1.155, 0) - salary "Increase"
Gu noFROM n employees;
a c
each employee, display the last name and calculate
rwas hired.
t h iLabel the column between
months
n g
today and the date on which the employee
(by the number
s e of months employed. The number
MONTHS_WORKED. Order your resultso
drthe closest u
towhole number.
of months must be roundeda lto e
u enonsthe date when it was executed, the values in the
Note: Because this query G depends
ic for you.
h i la lwill
column e ldiffer
MONTHS_WORKED
A rc rab
m o last_name,
SELECT
s f e ROUND(MONTHS_BETWEEN(
r anSYSDATE,
u ille FROM - t r hire_date)) MONTHS_WORKED
G non employees
ORDER BY months_worked;
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.
SELECT last_name,
LPAD(salary, 15, '$') SALARY
FROM employees;
SELECT last_name,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
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.
s a
a
) hquery.
Note: The TENURE value will differ because it depends on the date when you run the
c
ฺ ฺ o
SELECT last_name, trunc((SYSDATE-hire_date)/7) AS TENURE d u
FROM employees n a ฺe uide
WHERE department_id = 90
m ise ent G
ORDER BY TENURE DESC;
h i la@ Stud
g a rc this
n ( s e
o
dr e to u
a
u ens l
G
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
s a
co ) ha
u ฺ
a ฺ ed ideฺ
Practices for i s en t G5:u Using
Lesson
@ m den
Conversion
h tu
ila s SFunctions and
c
ar e thi Expressions
Conditional
( g
d t o us 5
ron Chapter
l
ua ense
G
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practice Overview
This practice covers the following topics:
• Creating queries that use the TO_CHAR and TO_DATE functions.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
• Creating queries that use conditional expressions such as CASE , SEARCHED CASE, and
DECODE
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Tasks
1. Create a report that produces the following for each employee:
<employee last name> earns <salary> monthly but wants <3 times salary.>.
Label the column Dream Salaries.
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
IT_PROG C
SA_REP D
ST_CLERK E
None of the above 0
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
A rc rab
value of the JOB_ID using the following data:
Job o
r m n s fe Grade
l e
ilAD_PRES - tra A
u
G ST_MAN n
no 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 searched CASE syntax.
SELECT job_id, CASE
WHEN job_id = 'ST_CLERK' THEN 'E'
s a
) ha
WHEN job_id = 'SA_REP' THEN 'D'
co
WHEN job_id = 'IT_PROG' THEN 'C'
u ฺ
ed ideฺ
WHEN job_id = 'ST_MAN' THEN 'B'
a ฺ
en t Gu
WHEN job_id = 'AD_PRES' THEN 'A'
ELSE '0' END i
m densGRADE
FROM employees; @
ila s Stu
c h
( g
6. Rewrite the statement in the preceding exercise thithe searched DECODE syntax.
ar by eusing
l d ron to us
G ua (job_id,
e n se
lic
SELECT job_id, decode
h i la le'ST_CLERK',
r c b
A fera 'SA_REP', 'D',
'E',
o
rm rans
i l l e t
'IT_PROG', 'C',
Gu non- 'ST_MAN',
'AD_PRES',
'B',
'A',
'0')GRADE
FROM employees;
s a
co ) ha
u ฺ
a ฺ ed ideฺ
Practices for i s en t G6:u
Lesson
@ m den
Reporting
h S tu
ila sAggregated Data
c
ar ethe
Using thi Group Functions
( g
d t o us 6
ron Chapter
l
ua ense
G
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 1
Practices for Lesson 6: Overview
Practice Overview
This practice covers the following topics:
• Writing queries that use group functions
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 2
Practice 6-1: Reporting Aggregated Data by Using Group Functions
Overview
After completing this practice, you should be familiar with using the group functions and
selecting groups of data.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
Tasks
Determine the validity of the following statements. Circle either True or False.
1. Group functions work across many rows to produce one result per group.
True/False
2. Group functions include nulls in calculations.
True/False
3. The WHERE clause restricts rows before inclusion in a group calculation. s a
True/False
co ) ha
u ฺ
The HR department needs the following reports: a ฺ ed ideฺ
s e n G u
4. Find the highest, lowest, sum, and average salary of all i
employees.
mRound e t
nresults
Label the columns
Maximum, Minimum, Sum, and Average, respectively. @ tu dyour
la as lab_06_04.sql. to the
nearest whole number. Save your SQL statementh i
c this S Run the query.
a r
n (g se
l d ro to u
G ua ense to display the minimum, maximum, sum, and
5. Modify the query in lab_06_04.sql
h
average salaryi a eachejoblictype. Save lab_06_04.sql as lab_06_05.sql again.
lfor l
rc rainblab_06_05.sql.
o A
Run the statement
fe
e r m n s
u ill n-tra
G no
Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 3
6. Write a query to display the number of people with the same job.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
s a
co ) ha
u ฺ
Generalize the query so that the user in the HR department is prompted for a job title.
ฺ ed ideฺ
Save the script to a file named lab_06_06.sql. Run the query. Enter IT_PROG when
a
prompted.
i s en t Gu
@ m den
c h ila s Stu
ar listing i
ththem.
n g
7. Determine the number of managers(without
s e Label the column Number of
Managers. o
dr e to u
a l
u column
Hint: Use the MANAGER_ID
G c e ns to determine the number of managers.
c h ila le li
o Ar ferab
l e r m ans
u l
i 8. Find n - r difference between the highest and lowest salaries. Label the column
tthe
G noDIFFERENCE.
Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 4
If you want an extra challenge, complete the following exercises:
10. Create a query to display the total number of employees and, of that total, the number
of employees hired in 2005, 2006, 2007, and 2008. Create appropriate column
headings.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
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.
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 5
Solution 6-1: Reporting Aggregated Data by Using Group Functions
Determine the validity of the following statements. Circle either True or False.
1. Group functions work across many rows to produce one result per group.
True/False
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
e rm
SELECT n
a s
job_id, ROUND(MAX(salary),0) "Maximum",
i l l t r
Gu non-
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
SELECT job_id, COUNT(*)
FROM employees
WHERE job_id = '&job_title'
GROUP BY job_id;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
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.
SELECT COUNT(DISTINCT manager_id) "Number of Managers"
FROM employees;
8. Find the difference between the highest and lowest salaries. Label the column
DIFFERENCE.
s a
SELECT MAX(salary) - MIN(salary) DIFFERENCE
co ) ha
FROM employees; u ฺ
a ฺ ed ideฺ
s e n G u
If you have time, complete the following exercises: i
m den t
9. Create a report to display the manager number andilthe @
a salarySoftuthe lowest-paid employee
for that manager. Exclude anyone whose managerr c h is s Exclude any groups where
notiknown.
the minimum salary is $6,000 or less. Sortg a
( the output t h
e in descending order of salary.
r o n u s
SELECT manager_id,ldMIN(salary)
a e to
FROM
G
employeesu ens
WHERE
h la le licIS NOT NULL
manager_id
i
GROUP BY
A rc MIN(salary)
rab
manager_id
o
HAVING
s f e > 6000
i l l ermORDER BY
t r a n MIN(salary) DESC;
Gu non-
If you want an extra challenge, complete the following exercises:
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
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",
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 8
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
s a
co ) ha
u ฺ
a ฺ ed ideฺ
Practices for i s en t G7:u
Lesson
@ m den
Displaying
h tu from Multiple
ila s Data
S
c hi Joins
ar e tUsing
Tables
( g
d t o us 7
ron Chapter
l
ua ense
G
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 1
Practices for Lesson 7: Overview
Practice Overview
This practice covers the following topics:
• Joining tables using an equijoin
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 2
Practice 7-1: Displaying Data from Multiple Tables by Using Joins
Overview
This practice is intended to give you experience in extracting data from multiple tables using the
SQL:1999–compliant joins.
Tasks
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
1. Write a query for the HR department to produce the addresses of all the departments.
Use the LOCATIONS and COUNTRIES tables. Show the location ID, street address, city,
state or province, and country in the output. Use a NATURAL JOIN to produce the
results.
s a
c o ) ha
u ฺ
a
a query to display the last name, department number, and departmentฺname eฺ Write
ed foridthese
2. The HR department needs a report of all employees with corresponding departments.
employees. i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 3
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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
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.
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
5. Modify lab_07_04.sql to display all employees, including King, who has no manager.
Order the results by employee number. Save your SQL statement as lab_07_05.sql.
Run the query in lab_07_05.sql.
Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 4
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
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.
s a
co ) ha
u ฺ
a ฺ ed ideฺ
… i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rneeds
7. The HR department ab a report on job grades and salaries. To familiarize yourself with
o f e
m ans table, first show the structure of the JOB_GRADES table. Then create a
therJOB_GRADES
l l e
i querynthat
- trdisplays the name, job, department name, salary, and grade for all employees.
u
G no
Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 5
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
g
If you want an extra challenge, complete the (following e thi
ar exercises:
d us of all employees who were hired after
ron thetonames
l
8. The HR department wants to determine
ua ethensname
e and hire date of any employee hired after
Davies. Create a query G
to display
employee Davies.ila
h l e lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 6
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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 7
Solution 7-1: Displaying Data from Multiple Tables by Using Joins
1. Write a query for the HR department to produce the addresses of all the departments. Use
the LOCATIONS and COUNTRIES tables. Show the location ID, street address, city, state or
province, and country in the output. Use a NATURAL JOIN to produce the results.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 8
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,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
c.last_name colleague
FROM employees e JOIN employees c
ON (e.department_id = c.department_id)
WHERE e.employee_id <> c.employee_id
ORDER BY e.department_id, e.last_name, c.last_name;
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.
s a
) ha
DESC JOB_GRADES
/
u ฺ co
SELECT e.last_name, e.job_id, d.department_name,
a ฺ ed ideฺ
en t Gu
e.salary, j.grade_level
FROM employees e JOIN departments d i
m dens
ON (e.department_id = d.department_id) @
ila s Stu
c h
ar e thi
JOIN job_grades j
ON ( g
(e.salary BETWEEN j.lowest_sal AND j.highest_sal);
If you want an extra challenge, completed
n following
rothe t o usexercises:
l
utoadetermine
sethe names of all employees who were hired after
8. The HR department wants G e n
i
Davies. Create a query
h e lic the name and hire date of any employee hired after
la toldisplay
rc rab
employee Davies.
A
r m
SELECT
n s fe
o e.last_name, e.hire_date
l l e r a
i FROMt employees e JOIN employees davies
Gu noONn- (davies.last_name = 'Davies')
WHERE davies.hire_date < e.hire_date;
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.
SELECT w.last_name, w.hire_date, m.last_name, m.hire_date
FROM employees w JOIN employees m
ON (w.manager_id = m.employee_id)
WHERE w.hire_date < m.hire_date;
Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 9
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 10
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
s a
co ) ha
u ฺ
a ฺ ed ideฺ
Practices for i s en t G8:u Using
Lesson
@ m den
c h ila s StotuSolve Queries
Subqueries
( g ar 8 thi
Chapter e
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practice Overview
This practice covers the following topics:
• Creating subqueries to query values based on unknown criteria
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
• Using subqueries to find values that exist in one set of data and not in another
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
produces the data that you anticipate before you code the outer query.
Tasks
1. The HR department needs a query that prompts the user for an employee’s last name. The
query then displays the last name and hire date of any employee in the same department
as the employee whose name the user supplies (excluding that employee). For example, if
the user enters Zlotkey, find all employees who work with Zlotkey (excluding Zlotkey).
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i ladisplays
l e licemployee number, last name, and salary of all employees
2. Create a report
A rcthan rthe
who earn more
that the
abaverage salary. Sort the results in ascending order by salary.
o f e
l l e rm rans
i t
Gu non-
s a
4. The HR department needs a report that displays the last name, department number, and
co ) ha
job ID of all employees whose department location ID is 1700. u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
Modify theA rc so that
query r abthe user is prompted for a location ID. Save this to a file named
o f e
l l e rm rans
lab_08_04.sql.
i -t
G5.u Create o n
n a report for HR that displays the last name and salary of every employee who
reports to King.
7. Create a report that displays a list of all employees whose salary is more than the salary of
any employee from department 60.
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r
If youehave m o
n sfe the following exercise:
time,acomplete
u illModifynthe
- trquery in lab_08_03.sql to display the employee number, last name, and
G no
8.
salary of all employees who earn more than the average salary, and who work in a
department with any employee whose last name contains the letter “u.” Save
lab_08_03.sql as lab_08_08.sql again. Run the statement in lab_08_08.sql.
UNDEFINE Enter_name
FROM departments
WHERE location_id = 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
s a
) ha
WHERE department_id IN (SELECT department_id
co
FROM departments
u ฺ
ed ideฺ
WHERE location_id =
a ฺ
en t Gu
&Enter_location);
i
m den s
@
ila salary
5. Create a report for HR that displays the last name and oftuevery employee who
c h S
reports to King.
( g ar e this
ro to us
SELECT last_name, salaryn
l d
ua= (SELECT
FROM employees
WHERE manager_id G e n se employee_id
h i la le licFROM employees
A rc rab WHERE last_name = 'King');
o s f e
i l l erm -tran
G6.u Create
nona 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);
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
s a
co ) ha
u ฺ
a ฺ ed ideฺ
Practices for i s en t G9:u Using
Lesson
@ m den
the Set
h tu
ilaOperators
S
c
ar 9 this
( g
Chapter e
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practice Overview
In this practice, you create reports by using the following:
• UNION operator
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
• INTERSECT operator
• MINUS operator
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
1. The HR department needs a list of department IDs for departments that do not contain the
job ID ST_CLERK. Use the set operators to create this report.
s a
co ) ha
u ฺ
d deฺ
2. The HR department needs a list of countries that have no departments a ฺ elocated i them.
in
e n G u
report. m is ent
Display the country IDs and the names of the countries. Use the set operators to create this
h i la@ Stud
g a rc this
n ( s e
o
dr whoework u
toin departments 50 and 80. Display the
a l
3. Produce a list of all the employees
u ensID by using the set operators.
employee ID, job ID, and Gdepartment
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
4. Create a report that lists the detail of all employees who are sales representatives and are
currently working in the sales department.
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
FROM departments
MINUS
SELECT department_id
FROM employees
WHERE job_id = 'ST_CLERK';
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.
s a
) ha
SELECT country_id,country_name
FROM countries
u ฺ co
MINUS
a ฺ ed ideฺ
SELECT l.country_id,c.country_name
i s en t Gu
FROM locations l JOIN countries c
@ m den
ON (l.country_id = c.country_id)
c h ila s Stu
JOIN departments d
( g ar e thi
ON d.location_id=l.location_id;
s
n work inudepartments
rowho
a l d
3. Produce a list of all the employees
e t o 50 and 80. Display the
G u ens
employee ID, job ID, and department ID by using the set operators.
h i la le licjob_id, department_id
SELECT employee_id,
FROM A rc rab
EMPLOYEES
r m
WHERE n fe
o department_id=50
s
e
ill UNION - traALL
u n
G noSELECT employee_id, job_id, department_id
FROM EMPLOYEES
WHERE department_id=80;
4. Create a report that lists the detail of all employees who are sales representatives and are
currently working in the sales department.
SELECT EMPLOYEE_ID
FROM EMPLOYEES
WHERE JOB_ID='SA_REP'
INTERSECT
SELECT EMPLOYEE_ID
FROM EMPLOYEES
WHERE DEPARTMENT_ID=80;
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
s a
co ) ha
u ฺ
a ฺ ed ideฺ
s en t G10:u
Practices for i Lesson
m den
@
Manipulating u
ila s StData
c h
( g ar 10 thi
Chapter e
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Lesson Overview
This practice covers the following topics:
• Inserting rows into tables
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Notes
• For all the DML statements, use the Run Script icon (or press F5) to execute the query.
Thus, you get to see the feedback messages on the Script Output tabbed page. For
SELECT queries, continue to use the Execute Statement icon or press F9 to get the
formatted output on the Results tabbed page.
• Execute cleanup_10.sql script from /home/oracle/labs/sql1/code_ex
/cleanup_scripts/ before performing the following tasks.
s a
Tasks co ) ha
u ฺ
1. Create a table called MY_EMPLOYEE.
a ฺ ed ideฺ
s n names.
ecolumn G u
2. Describe the structure of the MY_EMPLOYEE table to identify the
i
m den t
@
ila s Stu
c h
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
s a
4 Newman Chad cnewman
co
750 ) ha
u ฺ
d deฺ
a ฺ e1550 i
5 Ropeburn Audrey aropebur
e n G u
m is ent
h i la@ Stud
4. Populate the MY_EMPLOYEE table with the second
g a rc rowthofisthe sample data from the
preceding list. This time, list the columns( explicitly in
e the INSERT clause.
o n u s
5. Confirm your addition to the table.
a l dr e to
G u ens
h i la le lic
A rc rab
r m o
n s fe
6. e ra statement in a dynamic reusable script file to load the remaining rows into
illWrite nan-tINSERT
u
G thenoMY_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.
s a
co ) ha
u ฺ
15. Commit all pending changes.
a ฺ ed ideฺ
i s en t Gu
Control the data transaction to the MY_EMPLOYEE table.
@ m den
ila listed
16. Populate the table with the last row of the samplehdata S u
in tstep 3 by using the
c
ar 6. eRunththeisstatements in the script.
statements in the script that you created in step
( g s
n sessionuonly.
Note: Perform the steps (17-23) in o
l d r one t o
17. Confirm your addition to the a nse
utable.
a G i ce
i l l
A rch rable
r m o
n s fe
e
ill n-tra
u
G no
18. Mark an intermediate point in the processing of the transaction.
19. Delete all the rows from the MY_EMPLOYEE table.
20. Confirm that the table is empty.
21. Discard the most recent DELETE operation without discarding the earlier INSERT operation.
22. Confirm that the new row is still intact.
26. Confirm that the new row was added with the correct USERID.
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
2. Describe the structure of the MY_EMPLOYEE table to identify the column names.
s a
) ha
DESCRIBE my_employee
u ฺ co
3. Create an INSERT statement to add the first row of data to the MY_EMPLOYEE
ฺ e d table d e ฺ
from
a
en t Gu
the following sample data. Do not list the columns in the INSERT clause. i
i s
m den
FIRST_NAME ila USERID@ tu
ID LAST_NAME
c h S SALARY
( g ar e this
1 Patel
l d on to us
rRalph rpatel 895
G ua ense
2
i
Dancs
h la le lic Betty bdancs 860
A rc rab
r m3o
n s fe
Biri Ben bbiri 1100
i l l e t r a
Gu non- 4 Newman Chad cnewman 750
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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
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',
'&p_userid', &p_salary);
7. Populate the table with the next two rows of the sample data listed in step 3 by running the
s a
) ha
INSERT statement in the script that you created.
INSERT INTO my_employee
u ฺ co
VALUES (&p_id, '&p_last_name', '&p_first_name',
a ฺ ed ideฺ
'&p_userid', &p_salary);
i s en t Gu
@ m den
8. Confirm your additions to the table.
c h ila s Stu
( g ar e thi
ron to us
SELECT *
FROM my_employee;
l d
G ua ense
i
9. Make the data additions
h l e lic
la permanent.
A rc rab
r m o
COMMIT;
n s fe
e
ill n-tra
u
GUpdatenand
o delete data in the MY_EMPLOYEE table.
10. Change the last name of employee 3 to Drexler.
UPDATE my_employee
SET last_name = 'Drexler'
WHERE id = 3;
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;
DELETE
FROM my_employee
WHERE last_name = 'Dancs';
u ฺ co
15. Commit all pending changes.
a ฺ ed ideฺ
COMMIT;
i s en t Gu
@ m den
Control the data transaction to the MY_EMPLOYEE table. c h ila s Stu
a r t h i
( g e
16. Populate the table with the last row of the samplesdata listed in step 3 by using the
ron intstep
statements in the script that youdcreated
l o u6. Run the statements in the script.
G ua ense
INSERT INTO
h i l e lic
lamy_employee
A
VALUES rc(&p_id,rab'&p_last_name', '&p_first_name',
o s f e
l l e rm '&p_userid',
r a n &p_salary);
i t
Gu non-
Note: Perform the steps (17-23) in one session only.
ROLLBACK TO step_17;
s a
) ha
23. Make the data addition permanent.
COMMIT;
u ฺ co
a ฺ ed ideฺ
If you have time, complete the following exercise: i s en t Gu
mgenerated
d e n
24. Modify the lab_10_06.sql script such that the USERID
i @ is
lafirst seventucharacters
automatically by
concatenating the first letter of the first name andhthe
rc tThe S of the last
isscript should, therefore,
name. The generated USERID must be inglowercase.
( a e h not
s lab_10_24.sql.
ron to taofileunamed
prompt for the USERID. Save this script
l d
SET ECHO OFF
G ua ense
i
SET VERIFY OFF
h l a e lic
INSERTrc b l
INTO my_employee
a
A
o (&p_id, f er '&&p_last_name', '&&p_first_name',
r
VALUES
m s
u ran
ille n-lower(substr('&p_first_name',
tsubstr('&p_last_name', 1, 1) ||
G no 1, 7)), &p_salary);
SET VERIFY ON
SET ECHO ON
UNDEFINE p_first_name
UNDEFINE p_last_name
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
s a
co ) ha
u ฺ
a ฺ ed ideฺ
s en t G11:u
Practices for i
m denLesson
Usingila @ tu
DDL Statements to
c h S
( ar e and
Create
g this Manage Tables
d t o us 11
ron Chapter
l
ua ense
G
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practices for Lesson 11: Using DDL Statements to Create and Manage Tables
Chapter 11 - Page 1
Practices for Lesson 11: Overview
Lesson Overview
This practice covers the following topics:
• Creating new tables
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
u ฺ co
Note: Before starting this practice, execute the
a ฺ ed ideฺ
/home/oracle/labs/sql1/code_ex/cleanup_scripts/cleanup_11.sql
i s en t Guscript.
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practices for Lesson 11: Using DDL Statements to Create and Manage Tables
Chapter 11 - Page 2
Practice 11-1: Introduction to Data Definition Language
Overview
In this practice, you create new tables by using the CREATE TABLE statement. Confirm that the
new table was added to the database. You also learn to set the status of a table as READ ONLY,
and then revert to READ/WRITE. You use the ALTER TABLE command to modify table columns.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
Notes
• For all the DDL and DML statements, click the Run Script icon (or press F5) to execute
the query in SQL Developer. Thus, you get to see the feedback messages on the Script
Output tabbed page. For SELECT queries, continue to click the Execute Statement icon
or press F9 to get the formatted output on the Results tabbed page.
• Execute the cleanup_11.sql script from
/home/oracle/labs/sql1/code_ex/cleanup_scripts/cleanup_11.sql
before performing the following tasks. s a
Tasks
c o ) ha
u ฺ
a ฺedto create
1. Create the DEPT table based on the following table instance chart. Save the
the lab_11_01.sql script, and then execute the statement in thenscript i d etheฺ in
statement
s e G u
table. Confirm that the table is created. i
m den t
Column Name ID @ tu
ila s SNAME
c h
Key Type Primary keyar
( g e thi
Nulls/Unique
l d ron to us
FK Table
G ua ense
FK Column
h i la le lic
Data typeA rc rab NUMBER VARCHAR2
o f e
l l e rm rans
Length 7 25
i t
Gu non-
Practices for Lesson 11: Using DDL Statements to Create and Manage Tables
Chapter 11 - Page 3
2. Create the EMP table based on the following table instance chart. Save the statement in the
lab_11_02.sql script, and then execute the statement in the script to create the table.
Confirm that the table is created.
Key Type
Nulls/Unique
FK Table DEPT
FK Column ID
Data type NUMBER VARCHAR2 VARCHAR2 NUMBER
Length 7 25 25 7
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
a nse column of the NUMBER data type, with precision 2
3. Modify the EMP table. Add auCOMMISSION
G i ce
and scale 2. Confirmayour modification.
i l l
A rch rable
r m o
n s fe
e
ill n-tra
u
G no
4. Modify the EMP table to allow for longer employee last names. Confirm your modification.
Practices for Lesson 11: Using DDL Statements to Create and Manage Tables
Chapter 11 - Page 4
5. Drop the FIRST_NAME column from the EMP table. Confirm your modification by checking
the description of the table.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
6. In the EMP table, mark the DEPT_ID column as UNUSED. Confirm your modification by
checking the description of the table.
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
7. Drop all the UNUSED columns from thenEMP table. s
u
dro onethetostructure
8. Create the EMPLOYEES2 tableabased l
u eLAST_NAME,
s of the EMPLOYEES table. Include only
G
the EMPLOYEE_ID, FIRST_NAME, n SALARY, and DEPARTMENT_ID columns.
c ID, FIRST_NAME, LAST_NAME, SALARY, and
Name the columns h i linayour lnew
e litable
A rc rab
DEPT_ID, respectively.
r m o
n s fe
e
ill n-tra
u
G no
Practices for Lesson 11: Using DDL Statements to Create and Manage Tables
Chapter 11 - Page 5
10. Try to add a column JOB_ID in the EMPLOYEES2 table.
Note: You will get the “Update operation not allowed on table” error message. You will not
be allowed to add any column to the table because it is assigned a read-only status.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
11. Revert the EMPLOYEES2 table to read/write status. Now try to add the same column again. s a
co
Now, because the table is assigned a READ WRITE status, you will be allowed to add a ) ha
u ฺ
column to the table.
a ฺ ed ideฺ
You should get the following messages:
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
12. Drop the EMP, DEPT, and EMPLOYEES2 table.
Practices for Lesson 11: Using DDL Statements to Create and Manage Tables
Chapter 11 - Page 6
Solution 11-1: Introduction to Data Definition Language
1. Create the DEPT table based on the following table instance chart. Save the statement in a
script called lab_11_01.sql, and then execute the statement in the script to create the
table. Confirm that the table is created.
Column Name
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
ID NAME
Key Type Primary key
Nulls/Unique
FK Table
FK Column
Data type NUMBER VARCHAR2
Length 7 25
s a
co ) ha
u ฺ
a ฺ ed ideฺ
CREATE TABLE dept
s n
ePRIMARY G u
(id NUMBER(7)CONSTRAINT department_id_pk i
m den t KEY,
name VARCHAR2(25));
i @
la Stu
c h
To confirm that the table was created and to view
( g this issue the following command:
ar itsestructure,
DESCRIBE dept;
l d ron to us
uona the n se table instance chart. Save the statement in a
2. Create the EMP table based G e following
i la le licand then execute the statement in the script to create the
script called lab_11_02.sql,
h
table. Confirm
A rcthat the b is created.
ratable
o s f e
l l e rm r a n
u i Column n - t Name ID LAST_NAME FIRST_NAME DEPT_ID
G noKey Type
Nulls/Unique
FK Table DEPT
FK Column ID
Data type NUMBER VARCHAR2 VARCHAR2 NUMBER
Length 7 25 25 7
Practices for Lesson 11: Using DDL Statements to Create and Manage Tables
Chapter 11 - Page 7
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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
DESCRIBE emp
4. Modify the EMP table to allow for longer employee last names. Confirm your modification. a
s
ALTER TABLE emp
co ) ha
MODIFY (last_name VARCHAR2(50));
u ฺ
a ฺ ed ideฺ
DESCRIBE emp
i s en t Gu
@ m den
c h ila s Stu
( g r
atable. e thi your modification by checking
ron to us
5. Drop the FIRST_NAME column from the EMP Confirm
the description of the table. d
l
ua ense
ALTER TABLE emp G
lic
la lefirst_name;
DROPhiCOLUMN
A
DESCRIBErc emprab
r m o
n s fe
e
ilInl the EMP
- a
trtable,
u
G no
6. n mark the DEPT_ID column as UNUSED. Confirm your modification by
checking the description of the table.
DESCRIBE emp
Practices for Lesson 11: Using DDL Statements to Create and Manage Tables
Chapter 11 - Page 8
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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
s a
10. Try to add a column JOB_ID in the EMPLOYEES2 table.
co ) ha
u ฺ
a ฺ ed ideฺ
Note: You will get the “Update operation not allowed on table” error message. You will not
be allowed to add any column to the table because it is assigned a read-only status.
i s en t Gu
ALTER TABLE employees2
@ m den
ADD job_id VARCHAR2(9);
c h ila s Stu
( g a r
e t hi
11. Revert the EMPLOYEES2 table to the read/write
r o n u s Now try to add the same column
status.
again.
a ld se t o
Now, because the table G u
is assigned ena READ WRITE status, you will be allowed to add a
l a l i c
r c hi ble
column to the table.
o
ALTER ATABLE f e a
remployees2 READ WRITE;
erm n s
aTABLE
u i l l - t r
G non ALTER employees2
ADD job_id VARCHAR2(9);
DESCRIBE employees2
Practices for Lesson 11: Using DDL Statements to Create and Manage Tables
Chapter 11 - Page 9
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practices for Lesson 11: Using DDL Statements to Create and Manage Tables
Chapter 11 - Page 10
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
s a
co ) ha
u ฺ
a ฺ ed ideฺ
n u
Additionalm ise ent G
Practices and
Solutions
h i la@ Stud
g a rc this
n ( Chapterse12
d r o t o u
l
ua ense
G
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Practices Overview
In these practices, you will be working on extra exercises that are based on the following topics:
• Basic SQL SELECT statement
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
functions.
Tasks
1. The HR department needs to find data for all the clerks who were hired after 1997.
s a
2.
co
The HR department needs a report of employees who earn a commission. Show the last ) ha
u ฺ
name, job, salary, and commission of these employees. Sort the data by salary in
descending order.
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
3. For budgeting purposes,G
ua ense needs a report on projected raises. The report
the HR department
i
should display those
h laemployees
l e licwho have no commission, but who have a 10% raise in
salary (roundrc ab
o A off the
f e rsalaries).
l l e rm rans
i t
Gu non-
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la who
5. Show those employees
l e lic a last name starting with the letters “J,” “K,” “L,” or “M.”
have
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A
These exercises
rc canrbeabused for extra practice after you have discussed the following
o f e
s SELECT statements, basic SQL Developer commands, SQL functions,
l l e rm basic
topics:
r a n
SQL
i joins, nand-t group functions.
G7.u Create
no 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.
For example, if the user enters 1800, results are as follows:
8. Find the number of employees who have a last name that ends with the letter “n.” Create
two possible solutions.
10. The HR department needs to find the job titles in departments 10 and 20. Create a report to
display the job IDs for those departments.
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
11. Create a report that displays the jobs that are foundla
h i inforthethese tu Show and
Administration
S Executive
a r c
departments. Also display the number of employees
t h is jobs. the job with the
highest number of employees first.
n ( g s e
o
dr e to u
a
u ensl
G
h i la le lic
A rc rab
r m o
n s fe
e tra can be used for extra practice after you have discussed the following
illThesenexercises
-
u
G no 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).
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
14. Show all the employees
i l a who have
l i c managers with a salary higher than $15,000. Show the
h bname,
following data:cemployee le manager name, manager salary, and salary grade of the
manager. Ar a
m o s f er
r
u ille n-tran
G no
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G
the highest average salary.
uadepartment
16. Create a report to display the
e n se number and lowest salary of the department with
h i la le lic
A rc rab
r m o
n s fe
e ra that displays departments where no sales representatives work. Include the
illCreatena-treport
u
17.
G department
no number, department name, manager ID, and location in the output.
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Overview
Solutions to Additional Practice 1-1 are given as follows.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
Tasks
1. The HR department needs to find data for all the clerks who were hired after 1997.
SELECT *
FROM employees
WHERE job_id = 'ST_CLERK'
AND hire_date > '31-DEC-1997';
2. The HR department needs a report of employees who earn a commission. Show the last s a
name, job, salary, and commission of these employees. Sort the data by salary in
co ) ha
descending order.
u ฺ
a ฺ ed ideฺ
en t Gu
SELECT last_name, job_id, salary, commission_pct
FROM employees i
m dens
WHERE commission_pct IS NOT NULL @
ila s Stu
c h
ar e thi
ORDER BY salary DESC;
( g
d ron toneeds us a report on projected raises. The report
3. For budgeting purposes, the HR l
ua who
should display those employees
department
sdoenot get a commission but who have a 10% raise in
G e n
salary (round off the
h i lasalaries).
l e lic
SELECTA rc'The rsalary
ab of '||last_name||' after a 10% raise is '
o f e
s || ROUND(salary*1.10) "New salary"
l l e rm r a n
i FROM n-t commission_pct
Gu noWHERE
employees
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;
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.
SELECT last_name, salary,
decode(commission_pct, NULL, 'No', 'Yes') commission
FROM employees;
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, s a
joins, and group functions.
co ) ha
u ฺ ฺ
a ฺ
7. Create a report that displays the department name, location ID, last name, edjob title,
i d eand
s
salary of those employees who work in a specific location. Promptenthe user G u
for a location.
i
m den t
Enter 1800 for location_id when prompted. @
ila s Stu
c h
( g ar e thi e.last_name, e.job_id,
SELECT d.department_name, d.location_id,
us d
e.salary
FROM
l
employees e JOINd rondepartments
t o
ON
G
e.department_idua =end.department_id
se
AND i la le lic = &location_id;
d.location_id
h
A rc rab
8. Findm
r onumbersoffeemployees who have a last name that ends with the letter “n.” Create
the
e
illtwo possible
t r n
asolutions.
u
G noSELECT n -
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;
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
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.
SELECT e.job_id, count(e.job_id) FREQUENCY
FROM employees e JOIN departments d
ON e.department_id = d.department_id
WHERE d.department_name IN ('Administration', 'Executive')
s a
GROUP BY e.job_id
co ) ha
ORDER BY FREQUENCY DESC;
u ฺ
a ฺ ed ideฺ
i s en t Gu
These exercises can be used for extra practice after you have m discussed
d e n the following
topics: basic SQL SELECT statements, basic SQL Developer @ tu
ila s Scommands, SQL functions,
c h
joins, group functions, and subqueries.
( g ar e thi
d roinn the tfirst
o us
12. Show all employees who were
u l
a nse half of the month (before the 16th of the
hired
month, irrespective of the
a G ice
year).
h i l l e l
c
SELECT last_name, hire_date
o
r
FROM A employees
f e rab
e rm
WHERE n
a s
i l l t r TO_CHAR(hire_date, 'DD') < 16;
Gu non-
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;
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
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 RIGHT OUTER JOIN employees e1
ON d.department_id = e1.department_id
RIGHT OUTER JOIN employees e2
ON d.department_id = e2.department_id
s a
) ha
GROUP BY d.department_id, d.department_name, e2.last_name,
e2.salary,
e2.job_id u ฺ co
ORDER BY d.department_id, employees; a ฺ ed ideฺ
i s en t Gu
16. Create a report to display the department number and lowest
@ m salarydeofnthe department with
the highest average salary.
c h ila s Stu
SELECT department_id, MIN(salary)
( g ar e thi
FROM employees
l d ron to us
GROUP BY department_id
G ua ense
=c(SELECT MAX(AVG(salary))
HAVING AVG(salary)
h i l a e l i
r c a b l FROM employees
o A f er GROUP BY department_id);
r m s
u ille n-tran
G17. Create
no 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);
ON d.department_id = e.department_id
GROUP BY d.department_id, d.department_name
HAVING COUNT(*) < 3;
o A COUNT(*)
HAVING
f e ra = (SELECT MIN(COUNT(*))
erm -tran s FROM employees
i l l
Gu non GROUP BY department_id);
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;
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
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
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
store database and generate a report. The database contains only the essential tables.
The following is a diagram of the table and columns for the online book store application:
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
GNote: nIf oyou 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.
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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
Tasks
1. Table Details
a. Table Name: AUTHOR
Column Data type Key Table Dependent Type
Author_ID VARCHAR2 PK
Author_Name VARCHAR2
s a
) ha
b. Table Name: BOOKS
Column Datatype Key
u ฺ co Table Dependent On
Book_ID VARCHAR2 PK
a ฺ ed ideฺ
Book_Name VARCHAR2
s e n G u
Author_ID VARCHAR2 FK i
m den
AUTHORS t
Price NUMBER @ tu
ila PUBLISHER
c h S
Publisher_ID VARCHAR2
( g ar e this
FK
c. Table Name: CUSTOMER
d ron toKey us
Column Name Data type
u a l s e Table Dependent On
Customer_ID
a G icen
VARCHAR2 PK
Customer_Name l
hi VARCHAR2le
VARCHAR2l
A r c a b
er VARCHAR2
Street_Address
City mo s f
r
u ille n-tran
Phone_Number VARCHAR2
GCredit_Card_Number
n o VARCHAR2 FK Credit_Card_Details
d. CREDIT_CARD_DETAILS
Column Name Data type Key Table Dependent On
Credit_Card_Number VARCHAR2 PK
Credit_Card_Type VARCHAR2
Expiry_Date DATE
e. Table Name: ORDER_DETAILS
Column Data type Key Table Dependent On
Order_ID NUMBER PK
Customer_ID VARCHAR2 FK CUSTOMER
Shipping_Type VARCHAR2 FK SHIPPING_TYPE
Date_of_Purchase DATE
Shopping_Cart_ID NUMBER FK SHOPPING_CART
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
(
5. Add data to the tables. Create a script for g
each set
thi to be added.
ar eof data
l
Add data to the following tables:d ron to us
a. AUTHOR G ua ense
h i la le lic
rc rab
b. PUBLISHER
A
r m n fe
c.o SHIPPING_TYPE
s
e a
ill nd. -trCUSTOMER
u
G no e. CREDIT_CARD_DETAILS
f. BOOKS
g. SHOPPING_CART
h. ORDER_DETAILS
i. PURCHASE_HISTORY
Note: Save the scripts using the task number. For example, to save the script created
for the BOOKS table, you can save it as labs_apcs_5a_1.sql. Ensure that you save
the scripts in the /home/oracle/labs folder.
u ฺ co
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G b.noEnter a shopping cart detail for the book details that you just entered in 7(a).
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
Overview
The solution to Practice 1-2 is given as follows.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
Tasks
1. Table Details
a. AUTHOR
CREATE TABLE AUTHOR
(
Author_ID VARCHAR2 (10) NOT NULL ,
Author_Name VARCHAR2 (20)
) s a
;
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
COMMENT ON TABLE AUTHOR IS 'Author'
@ m den
;
c h ila s Stu
( g ar e thi
l d r on to us
ALTER TABLE AUTHORa
G e n se PRIMARY KEY (Author_ID);
u AUTHOR_PK
h i la le lic
ADD CONSTRAINT
b. BOOKS A rc rab
r m o
n s fe BOOKS
e
ill n-t(ra
CREATE TABLE
u
G no
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
)
;
r m n fe
o Credit_Card_Type
s VARCHAR2 (10) ,
e a
ill n-trExpiry_Date
u
G no )
DATE
)
;
h. SHIPPING_TYPE s a
CREATE TABLE SHIPPING_TYPE
co ) ha
u ฺ
d deฺ
(
a ฺ e i
Shipping_Type VARCHAR2 (10) NOT NULL , n
e G u
Shipping_Price NUMBER (6)
m is ent
)
h i la@ Stud
;
g a rc this
n ( s e
o u
dr e to IS 'Shipping Type'
a l
COMMENT ON TABLE SHIPPING_TYPE
u ens
;
G
h i la le lic
c SHIPPING_TYPE
ALTER r
o A TABLE
f e rab SHIPPING_TYPE_PK PRIMARY KEY ( Shipping_Type
e rm ADD
) ; ran
s
CONSTRAINT
i l l t
Gu non-
u ฺ co
ฺ e d deฺ
ALTER TABLE ORDER_DETAILS
e n a u i
is KEYent G
ADD CONSTRAINT FK_Order_details FOREIGN m
(
h i la@ Stud
Shipping_Type
g a rc this
)
n ( s e
o
dr e to u
a l
REFERENCES SHIPPING_TYPE
u ens
( G
h i la le lic
Shipping_Type
A
) rc rab
r ; o
m n s fe
e
ill n-tra
u
G no
ALTER TABLE ORDER_DETAILS
ADD CONSTRAINT Order_Details_fk FOREIGN KEY
(
Shopping_Cart_ID
)
REFERENCES SHOPPING_CART
(
Shopping_Cart_ID
)
;
Order_ID
)
REFERENCES ORDER_DETAILS
(
Order_ID
)
;
ALTER TABLE PURCHASE_ HISTORY
s a
ADD CONSTRAINT Purchase_History_CUSTOMER_FK FOREIGN KEY
co ) ha
(
u ฺ
Customer_ID
a ฺ ed ideฺ
)
i s en t Gu
REFERENCES CUSTOMER
@ m den
(
c h ila s Stu
Customer_ID
( g ar e thi
) ;
l d ron to us
a nse
uconstraint
d. Include a Foreign Key
a G i c e in the SHOPPING_CART table.
l
hi ble l
r c
ATABLE a
o
ALTER f e rSHOPPING_CART
erm -tADD s
anCONSTRAINT SHOPPING_CART_BOOKS_FK FOREIGN KEY
u i l l r
G non (
Book_ID
)
REFERENCES BOOKS
(
Book_ID
)
;
4. Create a sequence to uniquely identify each row in the ORDER DETAILS table.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
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.
s a
) ha
Alternatively, you can also query the user_sequences data dictionary view:
SELECT * FROM user_sequences;
u ฺ co
a ฺ ed ideฺ
5. Add data to the tables.
i s en t Gu
a. AUTHOR Table @ m den
c h ila s Stu
Author_ID
( g ar e thi
Author_Name
AN0001
r o n u sOliver Goldsmith
AN0002 o
ald nse t Oscar Wilde
u
G ice
AN0003 a George Bernard Shaw
h i l l e l
AN0004rc b Leo Tolstoy
o A fe r a
e r m
AN0005
a n s Percy Shelley
i l l r
Gu noAN0006 n-t Lord Byron
AN0007 John Keats
AN0008 Rudyard Kipling
AN0009 P. G. Wodehouse
Publisher_ID Publisher_Name
PN0001 Elsevier
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2015, Oracle and/or its affiliatesฺ
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c. SHIPPING _TYPE
c h ila s Stu
( g ar e thi
Shipping_Type l d ron to usShipping_Price
USPS G ua ense 200
i l a l i c
FedEx ch le 250
A r a b
o
DHL
m s f er 150
e r n
u ill n-tra
G no
Street
CN0002 Ngao LaDoris 5 Modrany Bratislav 586-355-8882 000-111-222-444
a
CN0003 Nagayama Midori 68 Via Sao 254-852-5764 000-111-222-555
Centrale Paolo
CN0004 Quick-To-See 6921 King Way Lagos 63-559-777 000-111-222-666
Mark
CN0005 Ropeburn Audry 86 Chu Street Hong 41-559-87 s a
000-111-222-777
Kong
co 000-111-222-888 ) ha
CN0006 Urguhart Molly 3035 Laurier u ฺ Quebec 418-542-9988
Blvd. a ฺ ed ideฺ
s G u 000-111-222-999
en322-504-2228
CN0007 Menchu Roberta Boulevard de i
Brussels
m den t
Waterloo 41 @
398 High c h ila Columbu
S tu 614-455-9863 000-111-222-222
ar e ths is
CN0008 Biri Ben St.
( g
CN0009 Catchpole d ron88 Alfred
t o uSt.s Brisbane 616-399-1411 000-111-222-111
Antoinetteua l se
G e n
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no
g. SHOPPING_CART
Shopping _Cart Book _ID Price Shopping _Cart Quantity
_ID _Date
SC0001 BN0002 200 12-JUN-2001 10
SC0002 BN0003 90 31-JUL-2004 8
SC0003 BN0003 175 28-JUN-2005 7
SC0004 BN0001 80 14-AUG-2006 9
SC0005 BN0001 175 21-SEP-2006 4
SC0006 BN0004 100 11-AUG-2007 6
SC0007 BN0005 200 28-OCT-2007 5
s a
co ) ha
u ฺ
h. ORDER _DETAILS
a ฺ ed ideฺ
s G u _Cart _ID
en t Shopping
Order _ID Customer
_ID
Shipping_
Type
i
Date _of _Purchase
m den
@
ila s Stu
OD0001 CN0001 USPS
r c h12-JUN-2001
i SC0002
OD0002 CN0002 USPS(g
a e t h
28-JUN-2005 SC0005
o n u s
OD0003 CN0003 ldrFedEx to 31-JUL-2004 SC0007
u a nse
OD0004
a G iceFedEx
CN0004 14-AUG-2006 SC0004
i l
OD0005 ch CN0005
l
le FedEx 21-SEP-2006 SC0003
A r r a b
m o
OD0006 s f eCN0006 DHL 28-OCT-2007 SC0001
e r n
u ill OD0007
n - tra CN0007 DHL 11-AUG-2007 SC0006
G no OD0008 CN0008 DHL 18-SEP-2009 SC0008
OD0009 CN0009 USPS 25-NOV-2009 SC0009
CN0004 OD0005
CN0009 OD0007
s a
co ) ha
ฺ
6. Create a view named CUSTOMER_DETAILS to show the Customer Name, Customer
u
a ฺ ed ideฺ
Address, and the details of the order placed by the customer. Order the results by Customer
ID.
i s en t Gu
CREATE VIEW customer_details AS
@ m den
SELECT ila s Stu o.order_id,
c.customer_name, c.street_address,
c h
o.customer_id, o.shipping_type,
o.shopping_cart_id ( g ar e thi
o.date_of_purchase,
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
r o u s details that you just entered in 7(a).
b. Enter a shopping cart detailnfor the book
ald nse t o
u
G ice
INSERT INTOashopping_cart(shopping_cart_id,
h i l l e l book_id, price,
rc('SC0010','BN0013','200',TO_DATE('12-JUN-2006','DD-MON-
rab
Shopping_cart_date,quantity)
A
o
VALUES
s f e
l l e rm a n
YYYY'),'12');
r
i t
Gu non-
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.
s a
co ) ha
u ฺ
a ฺ ed ideฺ
i s en t Gu
@ m den
c h ila s Stu
( g ar e thi
l d ron to us
G ua ense
h i la le lic
A rc rab
r m o
n s fe
e
ill n-tra
u
G no