You are on page 1of 146

Koenig Solutions Limited

Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
Oracle Database 12c: a
) hSQL
Workshop I ilco m e
i d
g ma nt Gu
4 0 @ ude
e d s St
Activity Guide
a m thi
e ( C se
u
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

D80190GC11
Edition 1.1
July 2014
D87242
Koenig Solutions Limited

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 2014, 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.

Restricted Rights Notice

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:

U.S. GOVERNMENT RIGHTS


The U.S. Governments rights to use, modify, reproduce, release, perform, display, or disclose these training materials are restricted
by the terms of the applicable Oracle license agreement and/or the applicable U.S. Government contract.

Trademark Notice

a
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective
s
owners.
)h a
m
co uide
Author i l
Dimpi Rani Sarmah g ma nt G
4 0 @ ude
Technical Contributors and Reviewers
e i St
dLaszlosCzinkoczki,
a m th
Nancy Greenberg, Swarnapriya Shridhar, Bryan Roberts, KimSeong Loh,

e C se
( Siddireddy
Brent Dayley, Jim Spiller, Christopher Wensley, Manish Pawar, Clair Bennett, Yanti Chang,
Joel Goodman, Gerlinde Frenzen and Madhavi u
e dumnse to
o Am lice
Y a using:
This book was published b le Oracle Tutor
t
en sfer a
m
Cle n-tran
no
Koenig Solutions Limited

Table of Contents
Practices for Lesson 1: Introduction ........................................................................................................ 1-1
Practices for Lesson 1: Overview............................................................................................................. 1-2
Practice 1-1: Introduction......................................................................................................................... 1-3
Solution 1-1: Introduction......................................................................................................................... 1-4
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

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
Practices for Lesson 4: Overview............................................................................................................. 4-2
Practice 4-1: Using Single-Row Functions to Customize Output................................................................ 4-3
a
Solution 4-1: Using Single-Row Functions to Customize Output................................................................ 4-9
) h as
om ide5-2
Practices for Lesson 5: Using Conversion Functions and Conditional Expressions ............................. 5-1

l c
Practices for Lesson 5: Overview.............................................................................................................

m ai t Gu 5-3
Practice 5-1: Using Conversion Functions and Conditional Expressions....................................................

@ g en
Solution 5-1: Using Conversion Functions and Conditional Expressions.................................................... 5-9
0 u d
Practices for Lesson 6: Reporting Aggregated Data Using the Group
e d4Functions s St................................... 6-1
m th i
Practices for Lesson 6: Overview.............................................................................................................
a 6-2
Practice 6-1: Reporting Aggregated Data by Using Group
e C se
( Functions......................................................... 6-3
Solution 6-1: Reporting Aggregated Data by Using m Group
to u
Functions......................................................... 6-6
d u e
A me from
Practices for Lesson 7: Displaying Data
ic e n s Tables Using Joins ............................................ 7-1
Multiple
Practices for Lesson 7: Overview
a o e l
.............................................................................................................
l Tables by Using Joins............................................................ 7-3
7-2

n t Y Data
Practice 7-1: Displaying
r a bMultiple
Data from Multiple

m e
Solution 7-1: Displaying
s f efrom Tables by Using Joins............................................................ 7-8

Clefor Lesson
Practices
Practices forn - tra8:8:nUsing
Lesson
Subqueries to Solve Queries ................................................................... 8-1
Overview............................................................................................................. 8-2
no
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.

Oracle Database 12c: SQL Workshop I Table of Contents


i
Koenig Solutions Limited

Practices for Lesson 1............................................................................................................................. 12-2


Practice 1-1: Additional Practice .............................................................................................................. 12-3
Solution 1-1: Additional Practice .............................................................................................................. 12-11
Case Study: Online Book Store ............................................................................................................... 12-17
Practice 1-2 ............................................................................................................................................ 12-18
Solution 1-2 ............................................................................................................................................ 12-23
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Oracle Database 12c: SQL Workshop I Table of Contents


ii
Koenig Solutions Limited
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
Practices for Lesson c m e
o1:
i l id
Introduction gma t Gu
Chapter 1 40
@ uden
e d s St
a m thi
e ( C se
u
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 1
Koenig Solutions Limited

Practices for Lesson 1: Overview

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 2014, 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
SQL*Plus that is available in this course.
For any query, the sequence of rows retrieved from the database may differ from
a
has
the screenshots shown.
)
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 2
Koenig Solutions Limited

Practice 1-1: Introduction


Overview
This is the first of many practices in this course. The solutions (if you require them) can be found
at the end of this practice. The practices are intended to cover most of the topics that are
presented in the corresponding lesson.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

In this practice, you perform the following:


Start Oracle SQL Developer and create a new connection to the ora1 account.
Use Oracle SQL Developer to examine the data objects in the ora1 account. The ora1
account contains the HR schema tables.
Note the following location for the practice files:
/home/oracle/labs/sql1/labs
If you are asked to save any practice files, save them in the preceding location.
Tasks
1. Start Oracle SQL Developer by using the SQL Developer Desktop icon.
2. Create a New Oracle SQL Developer Database Connection
s a
a. To create a new database connection, in the Connections Navigator, right-click
a
)h
Connections and select New Connection from the context menu. The New/Select
Database Connection dialog box appears. m
co uide
i l
Connection Name: myconnection g ma nt G
b. Create a database connection by using the following information:

4 0 @ ude
Username: ora1
e d s St
Password: ora1 a m thi
e ( C se
Hostname: localhost u
Port: 1521
e dumnse to
SID: ORCL Am ce
o
aselect the l i
Ensure that you
t Y a b leSave Password check box.
enthe Oracle
3. Testing f r Developer Database Connection and Connecting to the
eSQL
m s
tranthe new connection.
Cle a.n-Test
Database

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

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 3
Koenig Solutions Limited

Solution 1-1: Introduction


1. Starting Oracle SQL Developer Using the SQL Developer Desktop Icon
Double-click the Oracle SQL Developer desktop icon.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

The SQL Developer Interface appears.

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no
2. Creating a New Oracle SQL Developer Database Connection
a. To create a new database connection, in the Connections Navigator, right-click
Connections and select New Connection from the context menu.

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 4
Koenig Solutions Limited

The New / Select Database Connection dialog box appears.


Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
l c om ide
i. Connection Name: myconnection m ai t Gu
b. Create a database connection by using the following information:

@ g en
ii. Username: ora1
d 4 0
S t ud
iii. Password: ora1
a me this
iv. Hostname: localhost
e (C use
v. Port: 1521 um to
e d s e
m icen
vi. SID: ORCL
A
Ensure that
a e l the Save Password check box.
o you lselect
e nt Y ferab
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 5
Koenig Solutions Limited

3. Testing and Connecting Using the Oracle SQL Developer Database Connection
a. Test the new connection.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
a
)h
m
co uide
i
a tG l
g m
b. If the status is Success, connect to the database@
0 u d ennew connection.
by using this

e d4 s St
a m thi
e ( C se
u
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

When you create a connection, a SQL Worksheet for that connection opens automatically.

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 6
Koenig Solutions Limited
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
l c om ide
4. Browsing the Tables in the Connections Navigator m ai t Gu
@
a. In the Connections Navigator, view the objects that
gare available
en to you in the
0 u d
d4are present:
Tables node. Verify that the following tables
e s St
COUNTRIES am e th i
DEPARTMENTS ( C
e o us
EMPLOYEES m
du nse t
JOB_GRADES e
JOB_HISTORY
JOBS ao
Am lice
t Y a b le
n fer
LOCATIONS
eREGIONS
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 7
Koenig Solutions Limited

b. Browse the structure of the EMPLOYEES table.


Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
l c om ide
c. View the data of the DEPARTMENTS table.
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 8
Koenig Solutions Limited
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
Practices for Lesson c m e
o2:
a l
i Gthe u id
Retrieving Data Using
gm ent
SQL SELECT4 @
0 Statement
ud
d S t
a me2 this
Chapter
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 1
Koenig Solutions Limited

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 2014, Oracle and/or its affiliates

Describing the structure of tables


Performing arithmetic calculations and specifying column names

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 2
Koenig Solutions Limited

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 2014, 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

2. The following SELECT statement executes successfully:


a
SELECT *
) has
FROM job_grades;
l c om ide
True/False m ai t Gu
@ g en
d 4 0
S t ud
me tCan
3. There are four coding errors in the following statement.
a h isyou identify them?
e ( C se
SELECT employee_id, last_name u
sal x 12 ANNUAL SALARY
e dumnse to
FROM
Am lice
employees;
o
Task 2
Y a ble
e t ra you begin with the practices:
n pointsfebefore
Note the following
em tyour s
npractice
ClSave all - r a files at the following location:
o n
n /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.

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 3
Koenig Solutions Limited

4. Your first task is to determine the structure of the DEPARTMENTS table and its contents.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
l c om ide
5. i contents.
Your task is to determine the structure of the EMPLOYEES table andaits G u
g m t
a. Determine the structure of the EMPLOYEES table. 0@
u d en
e d4 s St
a m thi
e ( C se
u
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 4
Koenig Solutions Limited

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 2014, Oracle and/or its affiliates

in the same worksheet. Open a new worksheet.

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 5
Koenig Solutions Limited

6. The HR department wants a query to display all unique job IDs from the EMPLOYEES table.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
Task 3 a
)h
If you have time, complete the following exercises:
m
co uide
i l
7. The HR department wants more descriptive column headings form itsareporttonGemployees.
g n
@ udeName the columns
Copy the statement from lab_02_5b.sql to a new SQL Worksheet.
Emp #, Employee, Job, and Hire Date, respectively. 4 0
d srunStthe query again.
Then
e
m thi
C a
e ( u se
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 6
Koenig Solutions Limited

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 2014, Oracle and/or its affiliates

s a
a
)h
m
co uide
i
a tGl
g m
If you want an extra challenge, complete the following exercise:@
0 u d en
e
9. To familiarize yourself with the data in the EMPLOYEESd4table,s create
St a query to display all
i
amoutpute bytha comma. Name the column
the data from that table. Separate each column
THE_OUTPUT. ( C
e o us
m
du nse t
e
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 7
Koenig Solutions Limited

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 2014, Oracle and/or its affiliates

SELECT last_name, job_id, salary AS Sal


FROM employees;

True/False

2. The following SELECT statement executes successfully:


SELECT *
FROM job_grades;

True/False s a
a
)h
m
o ide
cthem?
i l
3. There are four coding errors in the following statement. Can you identify
g ma nt Gu
SELECT employee_id, last_name
4 0 @ ude
sal x 12 ANNUAL SALARY
e d s St
FROM employees;
a m thi
The EMPLOYEES table does not contain e C
( a columnse called sal. The column is called
u
SALARY.
e dumnse to
Am liisce*, not x, as shown in line 2.
The multiplication operator
o
The ANNUALYSALARY a aliasb le cannot include spaces. The alias should read
t a
en sfeorr should be enclosed within double quotation marks.
ANNUAL_SALARY
m
ClAecomma aisnmissing after the LAST_NAME column.
n - t r
Task 2 no
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;

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 8
Koenig Solutions Limited

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 2014, 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.
SELECT DISTINCT job_id
FROM employees;
s a
)h a
Task 3
c m
o ide
i l
If you have time, complete the following exercises:
g ma nt Gu
7. The HR department wants more descriptive column headings
0Worksheet. e on employees.
@ for itsudreport
Copy the statement from lab_02_5b.sql to a newdSQL
e 4 t Name the columns
S the query
a m th
Emp #, Employee, Job, and Hire Date, respectively. i
Then srun again.

e C
( last_name se "Employee",
SELECT employee_id "Emp #",
m u
to"Hire Date"
e
job_id "Job", duhire_date
s e
FROM A m icen
employees;
a o le l
e nt Y fehasrarequested
8. The HR department
b
lastle
m ans with the jobaIDreport
name concatenated
of all employees and their job IDs. Display the
C
column n - t r (separated by a comma and space) and name the
o Employee and Title.
nSELECT last_name||', '||job_id "Employee and Title"
FROM employees;

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 9
Koenig Solutions Limited

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 2014, Oracle and/or its affiliates

SELECT employee_id || ',' || first_name || ',' || last_name


|| ',' || email || ',' || phone_number || ','|| job_id
|| ',' || manager_id || ',' || hire_date || ','
|| salary || ',' || commission_pct || ',' ||
department_id
THE_OUTPUT
FROM employees;

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 10
Koenig Solutions Limited
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
Practices for Lesson c m e
o3:
a l
i GuData id
Restricting and Sorting
gm ent
0 @ ud
Chapter 3 d4 t
S
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 1
Koenig Solutions Limited

Practices for Lesson 3: Overview

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 2014, Oracle and/or its affiliates

Restricting rows by using the WHERE clause


Sorting rows by using the ORDER BY clause
Using substitution variables to add flexibility to your SQL SELECT statements

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 2
Koenig Solutions Limited

Practice 3-1: Restricting and Sorting Data

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 2014, 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
a
)h
m
co uide
i l
g ma nt G
4 0 @
t u de and department
2.
number for employee number 176. Run the query. m ed is S
Open a new SQL Worksheet. Create a report that displays the last name

( C a e th
m e o us
e du nse t
o Am lice
Y a needsbtolefind high-salary and low-salary employees. Modify
3. t
The HR department
e ra the last name and salary for any employee whose salary is not
n tofedisplay
lem
lab_03_01.sql
Cthe
in ranget r a ns through $12,000. Save your SQL statement as lab_03_03.sql.
$5,000
-
non

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 3
Koenig Solutions Limited

4. Create a report to display the last name, job ID, and hire date for employees with the last
names of Matos and Taylor. Order the query in ascending order by hire date.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

5. Display the last name and department ID of all employees in departments 20 or 50 in


ascending alphabetical order by last_name.

a
) has
l c om ide
6. ai t who
Modify lab_03_03.sql to display the last name and salary of employees
m Guearn
between $5,000 and $12,000, and are in department 20 or 50.gLabel thencolumns
Employee and Monthly Salary, respectively. Save 4 0 @ ude as
e d s St
lab_03_03.sql
lab_03_06.sql again. Run the statement in lab_03_06.sql.
a m thi
e ( C se
u
e dumnse to
o Am lice
Y a ble
7. e t
n feneeds
The HR department ra a report that displays the last name and hire date of all
m anwere s hired in 2006.
Cle n-twho
employees
r
no

8. Create a report to display the last name and job title of all employees who do not have a
manager.

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 4
Koenig Solutions Limited

9. Create a report to display the last name, salary, and commission of all employees who earn
commissions. Sort the data in descending order of salary and commissions.
Use the columns numeric position in the ORDER BY clause.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

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
a
)h
m
co uide
i l
g ma nt G
4 0 @ ude
e d s St
11. C
The HR department wants to run reports (based thi Create a query that prompts
amon aemanager.
the user for a manager ID, and generates
m t us ID, last name, salary, and
e theoemployee
department for that managersd
e u seThe HR department wants the ability to sort the
employees.
m Youiccan
report on a selected column.
A l entest the data with the following values:
Y
manager_id =t 103,
aosortedbbylelast_name:
e n fera
m s
Cle n-tran
no
manager_id = 201, sorted by salary:

manager_id = 124, sorted by employee_id:

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 5
Koenig Solutions Limited

If you have time, complete the following exercises:


12. Display the last names of all employees where the third letter of the name is a.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

13. Display the last names of all employees who have both an a and an e in their last name.

If you want an extra challenge, complete the following exercises: s a


a
) hof a
14. Display the last name, job, and salary for all employees whose jobs are either m that
co$2,500, e
sales representative or a stock clerk, and whose salaries are not equal
a i l
to
u i d$3,500,
or $7,000.
g m nt G
4 0 @ ude
e d s St
a m thi
e ( C se
u
e dumnse to
o Am lice
Y a btoldisplay
e the last name, salary, and commission for all
15. t
Modify lab_03_06.sql
er a
enwhosescommission
m
employees
n f is 20%. Save lab_03_06.sql as lab_03_15.sql again.
l
Rerune
C n-tr the a
statement in lab_03_15.sql.
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 6
Koenig Solutions Limited

Solution 3-1: Restricting and Sorting Data

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 earning more than $12,000. Save your SQL statement as a file
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

named lab_03_01.sql. Run your query.


SELECT last_name, salary
FROM employees
WHERE salary > 12000;
2. Open a new SQL Worksheet. Create a report that displays the last name and department
number for employee number 176.
SELECT last_name, department_id
FROM employees
WHERE employee_id = 176;
s a
3. The HR department needs to find high-salary and low-salary employees. Modify a
)h
lab_03_01.sql to display the last name and salary for all employees whose salary is not
m
l
in the range $5,000 through $12,000. Save your SQL statement as lab_03_03.sql.
i co uide
SELECT last_name, salary g ma nt G
4 0 @ ude
St
FROM employees
e d12000; s
WHERE salary NOT BETWEEN 5000 AND i
am ehirethdate for employees with the last
C
Create a report to display the last name, (job
4.
names of Matos and Taylor. Orderm theequeryto us
ID, and
in ascending order by hire date.
d u e
SELECT me job_id,
last_name,
A e n s hire_date
FROM
a o le lic
employees
WHEREnt Ylast_namer a b IN ('Matos', 'Taylor')
e
m BY sf e
l e
ORDER
a n hire_date;
C nthe-trlast name and department ID of all employees in departments 20 or 50 in
5. Display
no alphabetical order by last_name.
ascending
SELECT last_name, department_id
FROM employees
WHERE department_id IN (20, 50)
ORDER BY last_name ASC;
6. Modify lab_03_03.sql to list the last name and salary of employees who earn between
$5,000 and $12,000, and are in department 20 or 50. Label the columns Employee and
Monthly Salary, respectively. Save lab_03_03.sql as lab_03_06.sql again. Run
the statement in lab_03_06.sql.
SELECT last_name "Employee", salary "Monthly Salary"
FROM employees
WHERE salary BETWEEN 5000 AND 12000
AND department_id IN (20, 50);
Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 7
Koenig Solutions Limited

7. The HR department needs a report that displays the last name and hire date of all
employees who were hired in 2006.
SELECT last_name, hire_date
FROM employees
WHERE hire_date >= '01-JAN-06' AND hire_date < '01-JAN-07';
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

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
columns numeric position in the ORDER BY clause.
SELECT last_name, salary, commission_pct
FROM employees
s a
WHERE commission_pct IS NOT NULL
)h a
ORDER BY 2 DESC, 3 DESC; m
co that
10. Members of the HR department want to have more flexibility with the a i l
queries u deare
iyou
writing. They would like a report that displays the last name andg m t G who
salary of employees
n
4 @ (You
earn more than an amount that the user specifies after a0prompt.
t u decan use the query
created in Task 1 and modify it.) Save this query to adfile namedS
m e i s lab_03_10.sql.
Enter 12000 when prompted: C a et h
(
e o us
SELECT last_name, salary m
du nse t
employees e
A>m&sal_amt;
FROM
WHERE o
salary l i ce
Y a ble
Enter 12000
e t
n fprompted
when
e ra for a value in a dialog box. Click OK.
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 8
Koenig Solutions Limited

11. The HR department wants to run reports based on a manager. Create a query that prompts
the user for a manager ID, and generates the employee ID, last name, salary, and
department for that managers employees. The HR department wants the ability to sort the
report on a selected column. You can test the data with the following values:
manager _id = 103, sorted by last_name
manager_id = 201, sorted by salary
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

manager_id = 124, sorted by employee_id


SELECT employee_id, last_name, salary, department_id
FROM employees
WHERE manager_id = &mgr_num
ORDER BY &order_col;

If you have the time, complete the following exercises:


12. Display the last names of all employees where the third letter of the name is a.
s a
SELECT
FROM
last_name
employees )h a
m
co uide
WHERE last_name LIKE '__a%';
i l
a e int their
13. Display the last names of all employees who have both an a and
g man n G last name.
SELECT last_name
4 0 @ ude
e d s St
FROM employees
a m thi
WHERE last_name LIKE '%a%'
e ( C se
u
dumnse to
AND last_name LIKE '%e%';
e
o Amcomplete
If you want an extra challenge, l i cethe following exercises:
a ble
Yname,
t
14. Display thenlast
e e a and salary for all employees whose job is that of a sales
rjob,
m ans
representative or a f
stock clerk, and whose salary is not equal to $2,500, $3,500, or $7,000.
l e
C SELECT
o n -tr last_name, job_id, salary
nFROM employees
WHERE job_id IN ('SA_REP', 'ST_CLERK')
AND salary NOT IN (2500, 3500, 7000);
15. Modify lab_03_06.sql to display the last name, salary, and commission for all
employees whose commission amount is 20%. Save lab_03_06.sql as
lab_03_15.sql again. Rerun the statement in lab_03_15.sql.
SELECT last_name "Employee", salary "Monthly Salary",
commission_pct
FROM employees
WHERE commission_pct = .20;

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 9
Koenig Solutions Limited
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 10
Koenig Solutions Limited
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
)h a
Practices for Lesson m
co4: uUsing
a i l ide
Single-Row Functions
g m nt Gto
Customize4 0 @Output
t u de
m ed is S
( C a 4 e th
Chapter

m e o us
e du nse t
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Using Single-Row Functions to Customize Output


Chapter 4 - Page 1
Koenig Solutions Limited

Practices for Lesson 4: Overview

Practice Overview
This practice covers the following topics:
Writing a query that displays the current date
Unauthorized reproduction or distribution prohibited Copyright 2014, 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

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Using Single-Row Functions to Customize Output


Chapter 4 - Page 2
Koenig Solutions Limited

Practice 4-1: Using Single-Row Functions to Customize Output


Overview
This practice provides a variety of exercises using the different functions that are available for
character, number, and date data types. Remember that for nested functions, the results are
evaluated from the innermost function to the outermost function.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

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
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.
a
3. Run your query in the lab_04_02.sql file.
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Using Single-Row Functions to Customize Output


Chapter 4 - Page 3
Koenig Solutions Limited

4. Modify your query in lab_04_02.sql to add a column that subtracts the old salary from
the new salary. Label the column Increase. Save the contents of the file as
lab_04_04.sql. Run the revised query.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
)h a
m
co uide
i l
g ma nt G
4 0 @ ude
e d s St
a m thi
e ( C se
u
e dumnse to
o Am lice
Y a ble
e t
nfollowing e ra
5. Perform the
m ans f tasks:
CleWriten-atquery
a. r that displays the last name (with the first letter in uppercase and all the
o
other letters in lowercase) and the length of the last name for all employees whose
nname starts with the letters J, A, or M. Give each column an appropriate label. Sort
the results by the employees last names.

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Using Single-Row Functions to Customize Output


Chapter 4 - Page 4
Koenig Solutions Limited

b. Rewrite the query so that the user is prompted to enter the letter that the last name
starts with. For example, if the user enters H (capitalized) when prompted for a letter,
the output should show all employees whose last name starts with the letter H.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

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
a
)h
m
co uide
i l
g ma nt G
4 0 @ ude
e d s St
a m thi
e ( C se
u
e d um se to
If you have time, complete them
A l i c en
following exercises:

Y ao wants
6. The HR department
b letolastfindname
the duration of employment for each employee. For
e t
each employee, display
n the date
e a
ron which the employee
the and calculate the number of months between
today and f
m ans Order your results by thewas hired. Label the column as
l e
C n-tr
MONTHS_WORKED. number of months employed. The number
of o
n months must be rounded to the closest whole number.

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Using Single-Row Functions to Customize Output


Chapter 4 - Page 5
Koenig Solutions Limited

Note: Because this query depends on the date when it was executed, the values in the
MONTHS_WORKED column will differ for you.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Using Single-Row Functions to Customize Output


Chapter 4 - Page 6
Koenig Solutions Limited

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.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
8.
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Using Single-Row Functions to Customize Output


Chapter 4 - Page 7
Koenig Solutions Limited

Create a query that displays the employees last names, and indicates the amounts of
their salaries with asterisks. Each asterisk signifies a thousand dollars. Sort the data in
descending order of salary. Label the column EMPLOYEES_AND_THEIR_SALARIES.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
)h a
m
co uide
i l
g ma nt G
4 0 @ ude
e d s St
a m thi
e ( C se
u
e dumnse to
o Am lice
Y a ble
e t
n fera
9.ClCreate a nsto display the last name and the number of weeks employed for all
em atrquery
n o n- in department 90. Label the number of weeks column as TENURE. Truncate
employees
the number of weeks value to 0 decimal places. Show the records in descending order
of the employees tenure.
Note: The TENURE value will differ because it depends on the date on which you run the
query.

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Using Single-Row Functions to Customize Output


Chapter 4 - Page 8
Koenig Solutions Limited

Solution 4-1: Using Single-Row Functions to Customize Output


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.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

SELECT sysdate "Date"


FROM dual;

2. The HR department needs a report to display the employee number, last name, salary, and
salary increased by 15.5% (expressed as a whole number) for each employee. Label the
column New Salary. Save your SQL statement in a file named lab_04_02.sql.
SELECT employee_id, last_name, salary,
ROUND(salary * 1.155, 0) "New Salary"
FROM employees;

a
3. Run your query in the file lab_04_02.sql.
) has
SELECT employee_id, last_name, salary,
c o m e
ROUND(salary * 1.155, 0) "New Salary"
a i Guid
l
FROM employees;
@ gm ent
d 4 0
S t ud
4. Modify your query in the lab_04_02.sql to add
a mea column
t h isthat subtracts the old salary
e ( C
from the new salary. Label the column Increase.
s e
Save the contents of the file as
lab_04_04.sql. Run the revisedm query.
to u
e d u s e
SELECT employee_id,
A c n
m i*last_name,
e1.155, salary,
a l
o le * 1.155, 0) "New
ROUND(salary 0) Salary",

n t Y rab
ROUND(salary - salary "Increase"

m
FROM
n fe
e employees;
s
e
Cl n-tra
5. no the following tasks:
Perform
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.
SELECT INITCAP(last_name) "Name",
LENGTH(last_name) "Length"
FROM employees
WHERE last_name LIKE 'J%'
OR last_name LIKE 'M%'
OR last_name LIKE 'A%'
ORDER BY last_name;

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Using Single-Row Functions to Customize Output


Chapter 4 - Page 9
Koenig Solutions Limited

b. Rewrite the query so that the user is prompted to enter the letter that starts the last
name. For example, if the user enters H (capitalized) when prompted for a letter, the
output should show all employees whose last names start with the letter H.
SELECT INITCAP(last_name) "Name",
LENGTH(last_name) "Length"
FROM employees
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

WHERE last_name LIKE '&start_letter%'


ORDER BY last_name;
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.
SELECT INITCAP(last_name) "Name",
LENGTH(last_name) "Length"
FROM employees
WHERE last_name LIKE UPPER('&start_letter%' )
ORDER BY last_name;
s a
a
)h
If you have time, complete the following exercises: m
co uide
i l
foraeach employee.
6. The HR department wants to find the duration of employmentm
g
each employee, display the last name and calculate the number of e n
monthst GbetweenFor
4 0 @ ucolumn d
today and the date on which the employee was hired.
d
e of months S t
Label the
MONTHS_WORKED. Order your results by the number
a m t h i s employed. The number
of months must be rounded to the closest
e (C whole
u snumber.
e
Note: Because this query dependsm to
on the date when it was executed, the values in the
d u e
MONTHS_WORKED column will
A me icens
differ for you.

a
SELECT last_name, l
o leROUND(MONTHS_BETWEEN(
Y rabhire_date)) MONTHS_WORKED
ntSYSDATE,
FROM
m e s fe
employees
n
e
Cl ORDER a months_worked;
trBY
n -
no a query to display the last name and salary for all employees. Format the salary
7. Create
to be 15 characters long, left-padded with the $ symbol. Label the column SALARY.
SELECT last_name,
LPAD(salary, 15, '$') SALARY
FROM employees;

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Using Single-Row Functions to Customize Output


Chapter 4 - Page 10
Koenig Solutions Limited

8. Create a query that displays employees last names, and indicates the amounts of their
salaries with asterisks. Each asterisk signifies a thousand dollars. Sort the data in
descending order of salary. Label the column EMPLOYEES_AND_THEIR_SALARIES.

SELECT last_name,
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

rpad(' ', salary/1000, '*')


EMPLOYEES_AND_THEIR_SALARIES
FROM employees
ORDER BY salary DESC;

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 employees tenure.
Note: The TENURE value will differ because it depends on the date when you run the query.
a
has
SELECT last_name, trunc((SYSDATE-hire_date)/7) AS TENURE
FROM employees )
WHERE department_id = 90
l c om ide
ORDER BY TENURE DESC;
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Using Single-Row Functions to Customize Output


Chapter 4 - Page 11
Koenig Solutions Limited
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Using Single-Row Functions to Customize Output


Chapter 4 - Page 12
Koenig Solutions Limited
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
)h a
Practices for Lesson m
co5: uUsing
a i l ide
Conversion Functions
g m nt Gand
Conditional
4 0 t u de
@Expressions
m ed is S
( C a 5 e th
Chapter

m e o us
e du nse t
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 1
Koenig Solutions Limited

Practices for Lesson 5: Overview

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 2014, Oracle and/or its affiliates

Creating queries that use conditional expressions such as CASE , SEARCHED CASE, and
DECODE

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 2
Koenig Solutions Limited

Practice 5-1: Using Conversion Functions and Conditional


Expressions
Overview
This practice provides a variety of exercises using the TO_CHAR and TO_DATE functions, and
conditional expressions such as CASE, searched CASE, and DECODE.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

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.

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 3
Koenig Solutions Limited

2. Display each employees last name, hire date, and salary review date, which is the first
Monday after six months of service. Label the column REVIEW. Format the dates to
appear in a format that is similar to Monday, the Thirty-First of July, 2000.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 4
Koenig Solutions Limited

3. Create a query that displays employees last names and commission amounts. If an
employee does not earn commission, show No Commission. Label the column COMM.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 5
Koenig Solutions Limited

4. Using the CASE function, write a query that displays the grade of all employees based on
the value of the JOB_ID column, using the following data:
Job Grade
AD_PRES A
ST_MAN B
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

IT_PROG C
SA_REP D
ST_CLERK E
None of the above 0

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 6
Koenig Solutions Limited

5. Rewrite the statement in the preceding exercise by using the searched CASE syntax.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 7
Koenig Solutions Limited

6. Rewrite the statement in the preceding exercise by using the searched DECODE syntax.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 8
Koenig Solutions Limited

Solution 5-1: Using Conversion Functions and Conditional


Expressions
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.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

SELECT last_name || ' earns '


|| TO_CHAR(salary, 'fm$99,999.00')
|| ' monthly but wants '
|| TO_CHAR(salary * 3, 'fm$99,999.00')
|| '.' "Dream Salaries"
FROM employees;
2. Display each employees last name, hire date, and salary review date, which is the first
Monday after six months of service. Label the column REVIEW. Format the dates to appear
in a format that is similar to Monday, the Thirty-First of July, 2000.
SELECT last_name, hire_date,
TO_CHAR(NEXT_DAY(ADD_MONTHS(hire_date, 6),'MONDAY'), s a
'fmDay, "the" Ddspth "of" Month, YYYY') REVIEW
)h a
FROM employees;
o m
3. ilc GIfuanide
Create a query that displays employees last names and commissionaamounts.
employee does not earn commission, show No Commission. g m the ncolumn
Label t COMM.
0 @ ud e
SELECT last_name, d 4 S t
e 'No iCommission')
NVL(TO_CHAR(commission_pct),
a m t h s COMM
FROM employees;
e ( C se
u
4.
value of the JOB_ID column,e dum
Using the CASE function, write a query
using s e to the grade of all employees based on the
that displays
the following data:
A m icen
Job
a o le l Grade
AD_PRES nt
Y rab A
m e
n s fe
C l e
ST_MAN
t r a B
-
non
IT_PROG C
SA_REP D
ST_CLERK E
None of the above 0

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 9
Koenig Solutions Limited

SELECT job_id, CASE job_id


WHEN 'ST_CLERK' THEN 'E'
WHEN 'SA_REP' THEN 'D'
WHEN 'IT_PROG' THEN 'C'
WHEN 'ST_MAN' THEN 'B'
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

WHEN 'AD_PRES' THEN 'A'


ELSE '0' END GRADE
FROM employees;

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'
WHEN job_id = 'SA_REP' THEN 'D'
WHEN job_id = 'IT_PROG' THEN 'C'
WHEN job_id = 'ST_MAN' THEN 'B' a
WHEN job_id = 'AD_PRES'
) has THEN 'A'
ELSE '0' END GRADE
l c om ide
FROM employees;
m ai t Gu
@ g en
6. d 4
Rewrite the statement in the preceding exercise by using0 t ud DECODE syntax.
the searched
S
a me this
e (C use
dumnse to'E',
SELECT job_id, decode (job_id,
e'ST_CLERK',

o Am 'SA_REP',
l i ce 'D',
a e
Y rabl 'IT_PROG', 'C',
n t
m e
n s fe 'ST_MAN', 'B',
e
Cl n-tra 'AD_PRES', 'A',

n o '0')GRADE
FROM employees;

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 10
Koenig Solutions Limited
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
Practices for Lesson c m e
o6:
a l
i GData u id
Reporting Aggregated
gm ent
Using the 4 @
0Group udFunctions
d S t
a me6 this
Chapter
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 1
Koenig Solutions Limited

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 2014, Oracle and/or its affiliates

Grouping by rows to achieve multiple results


Restricting groups by using the HAVING clause

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 2
Koenig Solutions Limited

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 2014, 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.
True/False

s a
The HR department needs the following reports:
)h a
4. Find the highest, lowest, sum, and average salary of all employees.c
m
o theidcolumns
Label e
Maximum, Minimum, Sum, and Average, respectively. Round a i l
your results u
to the
g m nt G
nearest whole number. Save your SQL statement as lab_06_04.sql. Run the query.
0 @ d e
e d4 s Stu
a m thi
e ( C e
sthe
m
5. Modify the query in lab_06_04.sql to to u
display minimum, maximum, sum, and
average salary for each jobd
e ensu
type. e
Save lab_06_04.sql as lab_06_05.sql again.
Run the statement A m
a l e lic
o in lab_06_05.sql.
e nt Y ferab
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 3
Koenig Solutions Limited

6. Write a query to display the number of people with the same job.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
Generalize the query so that the user in the HR department is prompted for a job title.
s
a
Save the script to a file named lab_06_06.sql. Run the query. Enter IT_PROG when
)h
prompted.
m
co uide
i l
g ma nt G
4 0 @ ude
7. Determine the number of managers without listing
e d s Label
them.
i St the column Number of
Managers.
( C am e th
Hint: Use the MANAGER_ID column
m t o us the number of managers.
e to determine
e du nse
o Am lice
Y a ble
8. Finde the t
n difference
e rabetween the highest and lowest salaries. Label the column
m s f
Cle n-tran
DIFFERENCE.

no
If you have time, complete the following exercises:
9. Create a report to display the manager number and the salary of the lowest-paid
employee for that manager. Exclude anyone whose manager is not known. Exclude
any groups where the minimum salary is $6,000 or less. Sort the output in descending
order of salary.

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 4
Koenig Solutions Limited

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 2014, 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.

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 5
Koenig Solutions Limited

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 2014, Oracle and/or its affiliates

2. Group functions include nulls in calculations.


True/False

3. The WHERE clause restricts rows before inclusion in a group calculation.


True/False

The HR department needs the following reports:


4. Find the highest, lowest, sum, and average salary of all employees. Label the columns
Maximum, Minimum, Sum, and Average, respectively. Round your results to the nearest
whole number. Save your SQL statement as lab_06_04.sql. Run the query. s a
a
)h
SELECT ROUND(MAX(salary),0) "Maximum", m
co uide
ROUND(MIN(salary),0) "Minimum",
i l
ROUND(SUM(salary),0) "Sum",
g ma nt G
ROUND(AVG(salary),0) "Average" @
4 0 t u de
FROM employees;
m ed is S
( C a e th
5. Modify the query in lab_06_04.sql e
m usminimum, maximum, sum, and average
to display the
t o
salary for each job type. Save d
e u se as lab_06_05.sql again. Run the
lab_06_04.sql
m icen
statement in lab_06_05.sql.
A
a l e l
o ROUND(MAX(salary),0)
t Y raROUND(MIN(salary),0)
SELECT job_id,
n b "Maximum",

m e s f e ROUND(SUM(salary),0) "Minimum",
Cle n-tran
"Sum",
ROUND(AVG(salary),0) "Average"
o
nFROM 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.

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 6
Koenig Solutions Limited

SELECT job_id, COUNT(*)


FROM employees
WHERE job_id = '&job_title'
GROUP BY job_id;
Unauthorized reproduction or distribution prohibited Copyright 2014, 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.
SELECT MAX(salary) - MIN(salary) DIFFERENCE
FROM employees;
s a
a
)h
If you have time, complete the following exercises:
m
co uide
i l
alowest-paid
9. Create a report to display the manager number and the salary ofm
g the
n t G employee
0 @
for that manager. Exclude anyone whose manager is not known.
u d e
Exclude any groups where
4descending
the minimum salary is $6,000 or less. Sort the outputdin
e St order of salary.
am e th i s
SELECT
FROM
manager_id, MIN(salary)
employees ( C
e NULLo us
WHERE manager_id IS m
du nse t
NOT
GROUP BY manager_id e
HAVING Am li>ce6000
MIN(salary)
o
a ble DESC;
ORDER BYYMIN(salary)
e t
n fera
Cyoulem t r a ns challenge, complete the following exercises:
If
n o n-
want an extra
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;

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 7
Koenig Solutions Limited

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 2014, Oracle and/or its affiliates

SUM(DECODE(department_id , 80, salary)) "Dept 80",


SUM(DECODE(department_id , 90, salary)) "Dept 90",
SUM(salary) "Total"
FROM employees
GROUP BY job_id;

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 8
Koenig Solutions Limited
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
a
)h
Practices for Lesson m
co7: uide
i l
Displaying Data
g mafrom n t Multiple
G
Tables Using
4 0 @ Joins
t u de
m ed is S
( C a 7 e th
Chapter

m e o us
e du nse t
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 1
Koenig Solutions Limited

Practices for Lesson 7: Overview

Practice Overview
This practice covers the following topics:
Joining tables using an equijoin
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Performing outer and self-joins


Adding conditions

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 2
Koenig Solutions Limited

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:1999compliant joins.
Tasks
Unauthorized reproduction or distribution prohibited Copyright 2014, 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.

2. The HR department needs a report of all employees with corresponding departments. Write a
has
a query to display the last name, department number, and department name for these
)
employees.
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 3
Koenig Solutions Limited

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 2014, 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.

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
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.

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 4
Koenig Solutions Limited
Unauthorized reproduction or distribution prohibited Copyright 2014, 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
)h a
m
co uide
i l
g ma nt G
4 0 @ ude
e d s St
a m thi
e ( C se
u
e dumnse to
7. The HR department needs
o Ama report l i ceon job grades and salaries. To familiarize yourself with
the JOB_GRADES Y atable, first
b leshow the structure of the JOB_GRADES table. Then create a
t
en sfthe
query that displays a
ername, job, department name, salary, and grade for all employees.
m
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 5
Koenig Solutions Limited
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
)h a
m
co uide
i l
g ma nt G
4 0 @ ude
d s St
If you want an extra challenge, complete the following exercises:
e
8. The HR department wants to determine the a
names
i
m of allthemployees who were hired after
Davies. Create a query to display the e
name
C
( and uhiresedate of any employee hired after
employee Davies. m
du nse t o
e
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 6
Koenig Solutions Limited

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 2014, Oracle and/or its affiliates

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 7
Koenig Solutions Limited

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 2014, Oracle and/or its affiliates

SELECT location_id, street_address, city, state_province,


country_name
FROM locations
NATURAL JOIN countries;
2. The HR department needs a report of all employees with corresponding departments. Write
a query to display the last name, department number, and department name for all the
employees.
SELECT last_name, department_id, department_name
FROM employees
JOIN departments
USING (department_id);
s a
3. The HR department needs a report of employees in Toronto. Display the last name, a
) h job,
department number, and department name for all employees who work in Toronto.
c m
o ide
SELECT e.last_name, e.job_id, e.department_id,ad.department_name i l u
g m t G
FROM employees e JOIN departments d
0 @ u d en
ON (e.department_id = d.department_id)
e d4 s St
JOIN locations l a m thi
e ( C se
USING (location_id)
u
d mnse to
WHERE LOWER(l.city) =u'toronto';
e
Create a report to displaym
4.
managers last nameso A
and
employees
l
manageri cenumbers.
last names and employee numbers along with their
Label the columns Employee, Emp#,
Y a respectively.
b l e Save your SQL
Manager, and
e n t era
Mgr#, statement as lab_07_04.sql. Run the
query.m
l e a n sf
C SELECT
o n -tr w.last_name "Employee", w.employee_id "EMP#",
n m.last_name "Manager", m.employee_id "Mgr#"
FROM employees w JOIN employees m
ON (w.manager_id = m.employee_id);
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.
SELECT w.last_name "Employee", w.employee_id "EMP#",
m.last_name "Manager", m.employee_id "Mgr#"
FROM employees w
LEFT OUTER JOIN employees m
ON (w.manager_id = m.employee_id)
ORDER BY 2;

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 8
Koenig Solutions Limited

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 2014, 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.
DESC JOB_GRADES
/
SELECT e.last_name, e.job_id, d.department_name,
s a
e.salary, j.grade_level )h a
FROM employees e JOIN departments d m
co uide
i l
ON (e.department_id = d.department_id)
g ma nt G
JOIN job_grades j
4 0 @ ude
ON d s St
(e.salary BETWEEN j.lowest_sal AND j.highest_sal);
e
a mexercises:
If you want an extra challenge, complete the following t h i
e ( C sofeall employees who were hired after
8. The HR department wants to determine u
the names
m name and to hire date of any employee hired after
d uthe
Davies. Create a query to display
e s e
employee Davies.
A m icen
a o le le.hire_date
Y rabe JOIN employees davies
SELECT e.last_name,
ntemployees
FROM
m e
n s fe
e
Cl WHERE
ON
t r a
(davies.last_name = 'Davies')
-
on davies.hire_date < e.hire_date;
n
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;

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 9
Koenig Solutions Limited
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 10
Koenig Solutions Limited
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
)h a
Practices for Lesson m
co8: uUsing
a i l ide
Subqueries to g mSolventQueries
G
Chapter 8 d4
0@ tude
e i s S
m
a et h
( C
e o us
m
du nse t
e
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Subqueries to Solve Queries


Chapter 8 - Page 1
Koenig Solutions Limited

Practices for Lesson 8: Overview

Practice Overview
This practice covers the following topics:
Creating subqueries to query values based on unknown criteria
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Using subqueries to find values that exist in one set of data and not in another

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Subqueries to Solve Queries


Chapter 8 - Page 2
Koenig Solutions Limited

Practice 8-1: Using Subqueries to Solve Queries


Overview
In this practice, you write complex queries using nested SELECT statements.
For practice questions, you may want to create the inner query first. Make sure that it runs and
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

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 employees 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
)h a
m
co uide
i l
g ma nt G
4 0 @ ude
e d s St
a m thi
e ( C se
u
2. Create a report that displayse
dumnse number,
the employee
to
last name, and salary of all employees
A m icsalary.
e
a o le l
who earn more than the average Sort the results in ascending order by salary.

e nt Y ferab
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Subqueries to Solve Queries


Chapter 8 - Page 3
Koenig Solutions Limited

3. Write a query that displays the employee number and last name of all employees who work
in a department with any employee whose last name contains the letter u. Save your SQL
statement as lab_08_03.sql. Run your query.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

4. The HR department needs a report that displays the last name, department number, and
job ID of all employees whose department location ID is 1700. a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
Modify the query so thatA m usericiseprompted for a location ID. Save this to a file named
the
lab_08_04.sql.a o l e l
e nt Y ferab
5. C lema report
Create t r a nforsHR that displays the last name and salary of every employee who
-
nonto King.
reports

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Subqueries to Solve Queries


Chapter 8 - Page 4
Koenig Solutions Limited

6. Create a report for HR that displays the department number, last name, and job ID for every
employee in the Executive department.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

7. Create a report that displays a list of all employees whose salary is more than the salary of
any employee from department 60.

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a thebfollowing
If you have time, complete le exercise:
t er a
enquery sinflab_08_03.sql
8. Modifym the to display the employee number, last name, and
l e a n
C ofnall-tremployees who earn more than the average salary, and who work in a
salary
no with any employee whose last name contains the letter u. Save
department
lab_08_03.sql as lab_08_08.sql again. Run the statement in lab_08_08.sql.

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Subqueries to Solve Queries


Chapter 8 - Page 5
Koenig Solutions Limited

Solution 8-1: Using Subqueries to Solve Queries


1. The HR department needs a query that prompts the user for an employees 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).
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

--Execute the UNDEFINE command to remove a variable

UNDEFINE Enter_name

-- Execute the below SELECT statements to retrieve the values


from employees table

SELECT last_name, hire_date


FROM employees
WHERE department_id = (SELECT department_id
s a
FROM employees
)h a
WHERE last_name = '&&Enter_name')
m
co uide
AND last_name <> '&Enter_name';
i l
Note: UNDEFINE and SELECT are individual queries; execute g maone nafter
them t Gthe other or
press Ctrl + A + F9 to run them together.
4 0 @ ude
e dlast name, t salary of all employees
Sand
2. Create a report that displays the employee number,
athemresults i s
thin ascending order by salary.
who earn more than the average salary. Sort
( C e
m e osalary
t us
u se
SELECT employee_id, last_name,
employees ed
FROM
A m(SELECT
l i c en
WHERE salary
a o le> AVG(salary)

e n t Y erabFROM employees)
l e m BY
ORDER
a n sf
salary;
C n-tr
3. noa query that displays the employee number and last name of all employees who work
Write
in a department with any employee whose last name contains the letter u. Save your SQL
statement as lab_08_03.sql. Run your query.
SELECT employee_id, last_name
FROM employees
WHERE department_id IN (SELECT department_id
FROM employees
WHERE last_name like '%u%');

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Subqueries to Solve Queries


Chapter 8 - Page 6
Koenig Solutions Limited

4. The HR department needs a report that displays the last name, department number, and
job ID of all employees whose department location ID is 1700.
SELECT last_name, department_id, job_id
FROM employees
WHERE department_id IN (SELECT department_id
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

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
WHERE department_id IN (SELECT department_id
FROM departments
WHERE location_id =
s a
&Enter_location); a
)h
m
co uide
i l
a employee
5. Create a report for HR that displays the last name and salary of m
g every
n t G who
reports to King.
4 0 @ ude
SELECT last_name, salary e d s St
a m thi
FROM employees
e C se
( employee_id
WHERE manager_id = (SELECT
m employees
to u
e duFROM s e
A m iWHERE
l c en last_name = 'King');
Y ao ble
e nt for fHR
e a
rthat
6. Create
l e m in the
a report
a n s displays the department number, last name, and job ID for every
C n-tr
employee Executive department.
o
nSELECT 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);

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Subqueries to Solve Queries


Chapter 8 - Page 7
Koenig Solutions Limited

If you have time, complete the following exercise:


8. Modify the query in lab_08_03.sql to display the employee number, last name, and
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 to lab_08_08.sql again. Run the statement in lab_08_08.sql.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

SELECT employee_id, last_name, salary


FROM employees
WHERE department_id IN (SELECT department_id
FROM employees
WHERE last_name like '%u%')
AND salary > (SELECT AVG(salary)
FROM employees);

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Subqueries to Solve Queries


Chapter 8 - Page 8
Koenig Solutions Limited
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
)h a
Practices for Lesson m
co9: uUsing
a i l ide
the Set Operators g m nt G
Chapter 9 d4
0@ tude
e i s S
m
a et h
( C
e o us
m
du nse t
e
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using the Set Operators


Chapter 9 - Page 1
Koenig Solutions Limited

Practices for Lesson 9: Overview

Practice Overview
In this practice, you create reports by using the following:
UNION operator
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

INTERSECT operator
MINUS operator

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using the Set Operators


Chapter 9 - Page 2
Koenig Solutions Limited

Practice 9-1: Using Set Operators


Overview
In this practice, you write queries using the set operators UNION, INTERSECT, and MINUS.
Tasks
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

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
2. The HR department needs a list of countries that have no departments located )in h a
them.
c m
o ide this
Display the country IDs and the names of the countries. Use the set operators to create
report. l
ai t Gu
m
g en
4 0 @ ud
e d S t
3. Produce a list of all the employees who workainm t h
departments
is50 and 80. Display the
employee ID, job ID, and department e
C seset operators.
( usinguthe
ID by

e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

4. Create a report that lists the detail of all employees who are sales representatives and are
currently working in the sales department.

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using the Set Operators


Chapter 9 - Page 3
Koenig Solutions Limited

5. The HR department needs a report with the following specifications:


Last names and department IDs of all employees from the EMPLOYEES table,
regardless of whether or not they belong to a department
Department IDs and department names of all departments from the DEPARTMENTS
table, regardless of whether or not they have employees working in them
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Write a compound query to accomplish this report.

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using the Set Operators


Chapter 9 - Page 4
Koenig Solutions Limited

Solution 9-1: Using Set Operators


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.
SELECT department_id
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

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.
SELECT country_id,country_name
FROM countries
a
has
MINUS
SELECT l.country_id,c.country_name )
FROM locations l JOIN countries c
l c om ide
ON (l.country_id = c.country_id)
m ai t Gu
JOIN departments d @ g en
ON d.location_id=l.location_id; d 4 0
S t ud
inm
e is50 and 80. Display the
3. Produce a list of all the employees who worka
C t h
departments
employee ID, job ID, and department e ID by seset operators.
( usinguthe
SELECT employee_id,djob_id,
e um sedepartment_id
to
FROM EMPLOYEESAm
l i c en
Y ao ble
WHERE department_id=50
e t era
nALL
sf
UNION
l e m aemployee_id,
n
SELECT
C FROM - t r job_id, department_id
on EMPLOYEES
nWHERE 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;

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using the Set Operators


Chapter 9 - Page 5
Koenig Solutions Limited

5. The HR department needs a report with the following specifications:


Last names and department IDs of all employees from the EMPLOYEES table,
regardless of whether or not they belong to a department
Department IDs and department names of all departments from the DEPARTMENTS
table, regardless of whether or not they have employees working in them
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Write a compound query to accomplish this report.


SELECT last_name,department_id,TO_CHAR(null)dept_name
FROM employees
UNION
SELECT TO_CHAR(null),department_id,department_name
FROM departments;

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using the Set Operators


Chapter 9 - Page 6
Koenig Solutions Limited
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
Practices for Lesson c m e
o10:
ManipulatinggData a i Guid
l
m nt
4 0 @
t u de
ed is S
Chapter 10
m
( C a e th
m e o us
e du nse t
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Manipulating Data


Chapter 10 - Page 1
Koenig Solutions Limited

Practices for Lesson 10: Overview

Lesson Overview
This practice covers the following topics:
Inserting rows into tables
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Updating and deleting rows in a table


Controlling transactions

Note: Before starting this practice, execute


/home/oracle/labs/sql1/code_ex /cleanup_scripts/cleanup_10.sql script.

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Manipulating Data


Chapter 10 - Page 2
Koenig Solutions Limited

Practice 10-1: Managing Tables by Using DML Statements


Overview
The HR department wants you to create SQL statements to insert, update, and delete employee
data. As a prototype, you use the MY_EMPLOYEE table before giving the statements to the HR
department.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

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.

Tasks
a
1. Create a table called MY_EMPLOYEE.
) has
2.
l c om ide
Describe the structure of the MY_EMPLOYEE table to identify the column names.

m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Manipulating Data


Chapter 10 - Page 3
Koenig Solutions Limited

3. Create an INSERT statement to add the first row of data to the MY_EMPLOYEE table from
the following sample data. Do not list the columns in the INSERT clause. Do not enter all
rows yet.

ID LAST_NAME FIRST_NAME USERID SALARY


Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

1 Patel Ralph rpatel 895

2 Dancs Betty bdancs 860

3 Biri Ben bbiri 1100

4 Newman Chad cnewman 750

s a
5 Ropeburn Audrey aropebur 1550 ) h
a
l c om ide
m ai t Gu
4. Populate the MY_EMPLOYEE table with the second row of the @ g en from the
sample data
4
preceding list. This time, list the columns explicitly indthe
0
S
INSERT t ud
clause.
5. Confirm your addition to the table. a me this
e (C use
e dumnse to
o Am lice
Y a ble
6. t
n statement
Write an INSERT
e e ra in a dynamic reusable script file to load the remaining rows into
the e m f
ns table. The script should prompt for all the columns (ID, LAST_NAME,
Cl n-traUSERID,
MY_EMPLOYEE
FIRST_NAME, and SALARY). Save this script to a lab_10_06.sql file.
7.
o
n the table with the next two rows of the sample data listed in step 3 by running the
Populate
INSERT statement in the script that you created.
8. Confirm your additions to the table.

9. Make the data additions permanent.

Update and delete data in the MY_EMPLOYEE table.


10. Change the last name of employee 3 to Drexler.
Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Manipulating Data


Chapter 10 - Page 4
Koenig Solutions Limited

11. Change the salary to $1,000 for all employees who have a salary less than $900.
12. Verify your changes to the table.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

13. Delete Betty Dancs from the MY_EMPLOYEE table.


14. Confirm your changes to the table.

15. Commit all pending changes. a


) has
Control the data transaction to the MY_EMPLOYEE table. l c om ide
m ai t Gu
16. Populate the table with the last row of the sample data listed ingstep 3 bynusing the
4 0
statements in the script that you created in step 6. Run the@statements
t u dein the script.
Note: Perform the steps (17-23) in one sessionm ed is S
only.
( C a e th
17. Confirm your addition to the table.
m e o us
e du nse t
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
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.

23. Make the data addition permanent.

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Manipulating Data


Chapter 10 - Page 5
Koenig Solutions Limited

If you have time, complete the following exercise:


24. Modify the lab_10_06.sql script such that the USERID is generated automatically by
concatenating the first letter of the first name and the first seven characters of the last
name. The generated USERID must be in lowercase. Therefore, the script should not
prompt for the USERID. Save this script to a file named lab_10_24.sql.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

25. Run the lab_10_24.sql script to insert the following record:

ID LAST_NAME FIRST_NAME USERID SALARY

6 Anthony Mark manthony 1230

26. Confirm that the new row was added with the correct USERID.

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Manipulating Data


Chapter 10 - Page 6
Koenig Solutions Limited

Solution 10-1: Managing Tables by Using DML Statements


Insert data into the MY_EMPLOYEE table.
1. Create a table called MY_EMPLOYEE.
CREATE TABLE my_employee
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

(id NUMBER(4) CONSTRAINT my_employee_id_pk PRIMARY Key,


last_name VARCHAR2(25),
first_name VARCHAR2(25),
userid VARCHAR2(8),
salary NUMBER(9,2));

2. Describe the structure of the MY_EMPLOYEE table to identify the column names.
DESCRIBE my_employee

a
has
3. Create an INSERT statement to add the first row of data to the MY_EMPLOYEE table from
)
the following sample data. Do not list the columns in the INSERT clause.

l c om ide
m ai t GSALARYu
ID LAST_NAME FIRST_NAME
g
USERID
@ en
0 u d
e d4 rpatel
s St
1 Patel Ralph
a m th i 895

e (C use
2 Dancs m
duBetty to bdancs 860
e s e
A m icen
a o le l Ben
3
t Y
Biri
a b bbiri 1100

m en sfer
n
Cle 4n-traNewman Chad cnewman 750

no
5 Ropeburn Audrey aropebur 1550

INSERT INTO my_employee


VALUES (1, 'Patel', 'Ralph', 'rpatel', 895);

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

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Manipulating Data


Chapter 10 - Page 7
Koenig Solutions Limited

5. Confirm your additions to the table.


SELECT *
FROM my_employee;

6. Write an INSERT statement in a dynamic reusable script file to load the remaining rows into
Unauthorized reproduction or distribution prohibited Copyright 2014, 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
INSERT statement in the script that you created.
INSERT INTO my_employee
a
VALUES (&p_id, '&p_last_name', '&p_first_name',
) has
om ide
'&p_userid', &p_salary);
l c
m ai t Gu
8. Confirm your additions to the table.
@ g en
SELECT * d 4 0
S t ud
FROM my_employee; a me this
e (C use
dumnse to
9. Make the data additions permanent.
e
COMMIT; o Am lice
Y a ble
e t
n fera
C emdelete
Updateland
t r a ns in the MY_EMPLOYEE table.
data
-
nonthe last name of employee 3 to Drexler.
10. Change
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;

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Manipulating Data


Chapter 10 - Page 8
Koenig Solutions Limited

12. Verify your changes to the table.


SELECT *
FROM my_employee;

13. Delete Betty Dancs from the MY_EMPLOYEE table.


Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

DELETE
FROM my_employee
WHERE last_name = 'Dancs';

14. Confirm your changes to the table.


SELECT *
FROM my_employee;

a
15. Commit all pending changes.
) h as
COMMIT;
l c om ide
m ai t Gu
Control the data transaction to the MY_EMPLOYEE table.
@ g en
16. Populate the table with the last row of the sample e
0 tud3 by using the
d4listedsinSstep
data
statements in the script that you created in step
a m6. Run tthe
h istatements in the script.
e ( C se
u
INSERT INTO my_employee
e dumnse to
m ice
VALUES (&p_id,A'&p_last_name', '&p_first_name',
o
a b&p_salary);
le l
t Y
'&p_userid',
a
m en sfer
Cle Perform
Note: t r n steps (17-23) in one session only.
athe
-
non
17. Confirm your addition to the table.
SELECT *
FROM my_employee;

18. Mark an intermediate point in the processing of the transaction.


SAVEPOINT step_17;

19. Delete all the rows from the MY_EMPLOYEE table.


DELETE
FROM my_employee;

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Manipulating Data


Chapter 10 - Page 9
Koenig Solutions Limited

20. Confirm that the table is empty.


SELECT *
FROM my_employee;
21. Discard the most recent DELETE operation without discarding the earlier INSERT operation.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

ROLLBACK TO step_17;

22. Confirm that the new row is still intact.


SELECT *
FROM my_employee;

23. Make the data addition permanent.


COMMIT;
a
) has
If you have time, complete the following exercise:
l c om ide
24. Modify the lab_10_06.sql script such that the USERID is generated
m ai automatically
t G u by
@ g
concatenating the first letter of the first name and the first seven characters
e n of the last
name. The generated USERID must be in lowercase. The 4 0 script u d
should,
t therefore, not
d S
me tlab_10_24.sql.
prompt for the USERID. Save this script to a file named
a h is
SET ECHO OFF
e ( C se
u
SET VERIFY OFF
e d um se to
m icen
INSERT INTO my_employee
A
a
VALUES (&p_id,
l e l
o '&&p_last_name', '&&p_first_name',
n Y
t era b
lower(substr('&p_first_name', 1, 1) ||
e sf
msubstr('&p_last_name',
l e
C n-tr a n 1, 7)), &p_salary);

o VERIFY ON
nSET
SET ECHO ON
UNDEFINE p_first_name
UNDEFINE p_last_name

25. Run the lab_10_24.sql script to insert the following record:

ID LAST_NAME FIRST_NAME USERID SALARY

6 Anthony Mark manthony 1230

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Manipulating Data


Chapter 10 - Page 10
Koenig Solutions Limited

26. Confirm that the new row was added with the correct USERID.
SELECT *
FROM my_employee
WHERE ID='6';
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Manipulating Data


Chapter 10 - Page 11
Koenig Solutions Limited
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Manipulating Data


Chapter 10 - Page 12
Koenig Solutions Limited
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
Practices for Lesson c m e
o11:
a l
i Gto u id
Using DDL Statements
gm ent
Create and4 @
0 Manage
ud Tables
d S t
a me11 this
Chapter
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Using DDL Statements to Create and Manage Tables
Chapter 11 - Page 1
Koenig Solutions Limited

Practices for Lesson 11: Overview

Lesson Overview
This practice covers the following topics:
Creating new tables
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Creating a new table by using the CREATE TABLE AS syntax


Verifying that tables exist
Altering tables
Adding columns
Dropping columns
Setting a table to read-only status
Dropping tables

a
Note: Before starting this practice, execute the
) has
/home/oracle/labs/sql1/code_ex/cleanup_scripts/cleanup_11.sql script.
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Using DDL Statements to Create and Manage Tables
Chapter 11 - Page 2
Koenig Solutions Limited

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 2014, 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.
Tasks
a
has
1. Create the DEPT table based on the following table instance chart. Save the statement in
the lab_11_01.sql script, and then execute the statement in the script to create the
)
table. Confirm that the table is created.
l c om ide
Column Name ID m
NAME ai t Gu
@ g en
Key Type Primary key
d 4 0
S t ud
Nulls/Unique
a me this
FK Table
e (C use
FK Column
e dumnse to
Data type
o Am NUMBER
l i ce VARCHAR2
Length Y a ble7 25
n t r a
m e
n s fe
e
Cl n-tra
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Using DDL Statements to Create and Manage Tables
Chapter 11 - Page 3
Koenig Solutions Limited

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.

Column Name ID LAST_NAME FIRST_NAME DEPT_ID


Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Key Type
Nulls/Unique
FK Table DEPT
FK Column ID
Data type NUMBER VARCHAR2 VARCHAR2 NUMBER
Length 7 25 25 7

s a
)h a
m
co uide
i l
g ma nt G
4 0 @ ude
e d s St
a m thi
3. Modify the EMP table. Add a COMMISSIONe C
(columnuofsethe NUMBER data type, with precision 2
dumnse to
and scale 2. Confirm your modification.
e
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

4. Modify the EMP table to allow for longer employee last names. Confirm your modification.

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Using DDL Statements to Create and Manage Tables
Chapter 11 - Page 4
Koenig Solutions Limited

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 2014, 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
)h a
m
co uide
i l
g ma nt G
4 0 @ ude
7. Drop all the UNUSED columns from the EMP table. ed
i s St
8. (
Create the EMPLOYEES2 table based on the C am eof tthe
structure
h EMPLOYEES table. Include only
e o SALARY,
the EMPLOYEE_ID, FIRST_NAME, LAST_NAME,
m t us and DEPARTMENT_ID columns.
Name the columns in your new
e u ID,sFIRST_NAME,
dtable e LAST_NAME, SALARY, and
DEPT_ID, respectively.Am e n
a o le lic
e nt Y ferab
m s
Cle n-tran
no

9. Alter the status of the EMPLOYEES2 table to read-only.

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Using DDL Statements to Create and Manage Tables
Chapter 11 - Page 5
Koenig Solutions Limited

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 2014, Oracle and/or its affiliates

11. Revert the EMPLOYEES2 table to read/write status. Now try to add the same column again.
Now, because the table is assigned a READ WRITE status, you will be allowed to add a
a
has
column to the table.
You should get the following messages: )
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no EMP, DEPT, and EMPLOYEES2 table.
12. Drop the

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Using DDL Statements to Create and Manage Tables
Chapter 11 - Page 6
Koenig Solutions Limited

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 2014, 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
CREATE TABLE dept )h a
m
coKEY,uide
(id NUMBER(7)CONSTRAINT department_id_pk PRIMARY
i l
name VARCHAR2(25));
g ma nt G
4 0 t defollowing command:
@issueuthe
To confirm that the table was created and to view its structure,
DESCRIBE dept;
m ed is S
( C a e th
2. e table
Create the EMP table based on the following s
uinstance chart. Save the statement in a
script called lab_11_02.sql,dand u mthen e t o
execute the statement in the script to create the
meis created.
table. Confirm that the table
A e n s
a o le lic
Column
Y IDrab
ntName
e
m ans f e LAST_NAME FIRST_NAME DEPT_ID

CleKeynType-tr
n o
Nulls/Unique
FK Table DEPT
FK Column ID
Data type NUMBER VARCHAR2 VARCHAR2 NUMBER
Length 7 25 25 7

CREATE TABLE emp


(id NUMBER(7),
last_name VARCHAR2(25),
first_name VARCHAR2(25),
dept_id NUMBER(7)
CONSTRAINT emp_dept_id_FK REFERENCES dept (id)
);
Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Using DDL Statements to Create and Manage Tables
Chapter 11 - Page 7
Koenig Solutions Limited

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 2014, Oracle and/or its affiliates

ALTER TABLE emp


ADD commission NUMBER(2,2);

DESCRIBE emp

4. Modify the EMP table to allow for longer employee last names. Confirm your modification.
ALTER TABLE emp
MODIFY (last_name VARCHAR2(50));
s a
)h a
DESCRIBE emp m
co uide
i l
g ma nt G
4 0 @ ude
5. d your
Drop the FIRST_NAME column from the EMP table. Confirm
e t
Smodification by checking
the description of the table. am e th i s
( C
e o us
ALTER TABLE emp
m
du nse t
e
DROP COLUMN first_name;
DESCRIBE emp Am
o l i ce
Y a ble
e t
n mark e ra DEPT_ID column as UNUSED. Confirm your modification by
6. In the EMP table, f
ns of the table.
m description the
Cle nthe
checking
- t r a
no
ALTER TABLE emp
SET UNUSED (dept_id);

DESCRIBE emp

7. Drop all the UNUSED columns from the EMP table.


ALTER TABLE emp
DROP UNUSED COLUMNS;

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Using DDL Statements to Create and Manage Tables
Chapter 11 - Page 8
Koenig Solutions Limited

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 2014, Oracle and/or its affiliates

SELECT employee_id id, first_name, last_name, salary,


department_id dept_id
FROM employees;
DESCRIBE employees2

9. Alter the EMPLOYEES2 table status to read-only.


ALTER TABLE employees2 READ ONLY;

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 a
has
be allowed to add any column to the table because it is assigned a read-only status.
)
ALTER TABLE employees2
l c om ide
ADD job_id VARCHAR2(9);
m ai t Gu
@ g en
d 4 0
S t udthe same column
me this
11. Revert the EMPLOYEES2 table to the read/write status. Now try to add
again. a
(CWRITEusstatus,
e you will be allowed to add a
e
Now, because the table is assigned a READ
column to the table.
e dumnse to
Am liceREAD WRITE;
ALTER TABLE employees2
o
Y a ble
e t ra
nTABLEfeemployees2
m ans VARCHAR2(9);
ALTER
CleADDn-job_id
tr employees2
n o
DESCRIBE

12. Drop the EMP, DEPT, and EMPLOYEES2 table.


Note: You can even drop a table that is in READ ONLY mode. To test this, alter the table
again to READ ONLY status, and then issue the DROP TABLE command. The tables will be
dropped.
DROP TABLE emp;
DROP TABLE dept;
DROP TABLE employees2;

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Using DDL Statements to Create and Manage Tables
Chapter 11 - Page 9
Koenig Solutions Limited
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Using DDL Statements to Create and Manage Tables
Chapter 11 - Page 10
Koenig Solutions Limited
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
Additional Practices c m e
oand
i l id
Solutions gma t Gu
0 @ u d en
d4 s St
Chapter 12
e
a m thi
e ( C se
u
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 1
Koenig Solutions Limited

Practices for Lesson 1

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 2014, Oracle and/or its affiliates

Basic SQL Developer commands


SQL functions

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 2
Koenig Solutions Limited

Practice 1-1: Additional Practice

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 2014, Oracle and/or its affiliates

functions.

Tasks
1. The HR department needs to find data for all the clerks who were hired after 1997.

2. The HR department needs a report of employees who earn a commission. Show the last
name, job, salary, and commission of these employees. Sort the data by salary in
s a
descending order.
)h a
m
co uide
i l
g ma nt G
4 0 @ ude
e d s St
a m thi
e C
( needs saereport on projected raises. The report
3. For budgeting purposes, the HR department u
mhave notocommission, but who have a 10% raise in
should display those employees
e duwho n se
m
salary (round off the salaries). e
a o A le lic
e nt Y ferab
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 3
Koenig Solutions Limited

4. Create a report of employees and their duration of employment. Show the last names of all
the employees together with the number of years and the number of completed months that
they have been employed. Order the report by the duration of their employment. The
employee who has been employed the longest should appear at the top of the list.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
)h a
m
co uide
i l
g ma nt G
4 0 @ ude
e d s St
a m thi
e ( C se
u
5.
e dum
Show those employees who have tostarting with the letters J, K, L, or M.
a last name
s e
A m icen
a o le l
e nt Y ferab
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 4
Koenig Solutions Limited

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.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
)h a
m
co uide
i l
g ma nt G
4 0 @ ude
e d s St
a m thi
e ( C se
u
e dumnse to
These exercises can be
m foricextra
Aused e practice after you have discussed the following
o l
aSELECTbstatements,
le
topics: basic SQL
t Y r
n functions. a
basic SQL Developer commands, SQL functions,
joins, andegroup
m n s fe
7. e
Cl a report
Create
tra employees
that displays the department name, location ID, last name, job title, and
o -
salary ofnthose who work in a specific location. Prompt the user for a location.
Fornexample, 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.

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 5
Koenig Solutions Limited

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.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

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
a
)h
m
co uide
i l
a and
11. Create a report that displays the jobs that are found in the Administration
g m n t GExecutive
departments. Also display the number of employees for these
0 @ jobs.
u d e job with the
Show the
highest number of employees first.
e d4 s St
a m thi
e ( C se
u
e dumnse to
o Am lice
Y a ble
t
en can e raused for extra practice after you have discussed the following
Thesem exercises f
nsSELECT statements, basic SQL Developer commands, SQL functions,
be
C le basic
topics: t r a
SQL
joins,o n- functions, and subqueries.
n group
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).

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 6
Koenig Solutions Limited

13. Create a report that displays the following for all employees: last name, salary, and salary
expressed in terms of thousands of dollars.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
)h a
m
co uide
i l
g ma nt G
4 0 @ ude
e d s St
a m thi
e ( C se
14. Show all the employees who have m
managerst u
o salary higher than $15,000. Show the
with a
d u e
A me imanager
following data: employee name,
e n s name, manager salary, and salary grade of the
manager.
a o le l c
e nt Y ferab
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 7
Koenig Solutions Limited

15. Show the department number, name, number of employees, and average salary of all the
departments, together with the names, salaries, and jobs of the employees working in each
department.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
a
)h
m
co uide
i l
g ma nt G
4 0 @ ude
e d s St
a m thi
16. C se lowest salary of the department with
Create a report to display the department(number and
e u
dumnse to
the highest average salary.
e
o Am lice
Y a ble
17. Create ae
t
report ra departments where no sales representatives work. Include the
n thatfedisplays
m number, s department name, manager ID, and location in the output.
Cle n-tran
department

no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 8
Koenig Solutions Limited

18. Create the following statistical reports for the HR department. Include the department
number, department name, and the number of employees working in each department that:
a. Employs fewer than three employees:
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

b. Has the highest number of employees:

c. Has the lowest number of employees:

a
) has
19. Create a report that displays the employee number, last name, salary, department number,
and the average salary in their department for all employees.
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 9
Koenig Solutions Limited

20. Create an anniversary overview based on the hire date of the employees. Sort the
anniversaries in ascending order.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 10
Koenig Solutions Limited

Solution 1-1: Additional Practice

Overview
Solutions to Additional Practice 1-1 are given as follows.
Unauthorized reproduction or distribution prohibited Copyright 2014, 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
name, job, salary, and commission of these employees. Sort the data by salary in
descending order. a
h a s
SELECT last_name, job_id, salary, commission_pct
m )
FROM employees
i l co uide
WHERE commission_pct IS NOT NULL
g ma nt G
ORDER BY salary DESC;
4 0 @ ude
e d s St
3. For budgeting purposes, the HR department a m a report
needs t h i on projected raises. The report
should display those employees who do e C
not se
( get aucommission but who have a 10% raise in
salary (round off the salaries). um t o
d nse
eof
SELECT 'The salary
A m i c e
'||last_name||' after a 10% raise is '
o l
a|| ROUND(salary*1.10)
le
t Y a b "New salary"
FROM n employees
m s f er
e commission_pct
Cle n-tran
WHERE IS NULL;

n o
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;

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 11
Koenig Solutions Limited

5. Show those employees who have a last name that starts with the letters J, K, L, or M.
SELECT last_name
FROM employees
WHERE SUBSTR(last_name, 1,1) IN ('J', 'K', 'L', 'M');
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

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,
joins, and group functions.

s a
7. Create a report that displays the department name, location ID, last name, job title, a
) hand
salary of those employees who work in a specific location. Prompt the user for
c m a location.
o ide
i l
Enter 1800 for location_id when prompted.
g ma nt Gu
SELECT d.department_name, d.location_id,@
4 0 de e.job_id,
e.last_name,
t u
e.salary
m edd is S
FROM employees e JOIN departments
( C a e th
ON e o us
e.department_id = d.department_id
m
AND
e d nse t
d.location_idu= &location_id;

o Am lice
8. Find the number of
Y aemployees
b le who have a last name that ends with the letter n. Create
en sfer
two possible tsolutions. a
m n
CleSELECT - t r aCOUNT(*)
non
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.

Additional Practices and Solutions


Chapter 12 - Page 12
Koenig Solutions Limited

10. The HR department needs to find the job titles in departments 10 and 20. Create a report to
display the job IDs for these departments.
SELECT DISTINCT job_id
FROM employees
WHERE department_id IN (10, 20);
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

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')
GROUP BY e.job_id
ORDER BY FREQUENCY DESC;
s a
)h a
m
o following
These exercises can be used for extra practice after you have discussed
a i l cthe u i de
topics: basic SQL SELECT statements, basic SQL Developer commands,
g m nSQL t Gfunctions,
joins, group functions, and subqueries.
4 0 @ ude
e d s St
12. Show all employees who were hired in theC a
first
m t
half of the h i
month (before the 16th of the
month, irrespective of the year). e ( u se
SELECT last_name, e dumnse to
hire_date
FROM
o Am lice
employees
Y a ble
n t r a
WHERE TO_CHAR(hire_date, 'DD') < 16;

m e
n s fe
13.
e
Cl anreport
Create t ra that displays the following for all employees: last name, salary, and salary
-
no in terms of thousands of dollars.
expressed
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.

Additional Practices and Solutions


Chapter 12 - Page 13
Koenig Solutions Limited

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

SELECT d.department_id, d.department_name,


Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

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
GROUP BY d.department_id, d.department_name, e2.last_name,
e2.salary,
e2.job_id
s a
ORDER BY d.department_id, employees;
)h a
m
codepartment
16.
a
Create a report to display the department number and lowest salary ofilthe u ide with
the highest average salary. g m nt G
4 0 @ ude
SELECT department_id, MIN(salary)
e d s St
FROM employees
a m thi
GROUP BY department_id
e ( C se
HAVING AVG(salary) = u m
(SELECT to u
MAX(AVG(salary))
e d FROM s e
A m icGROUP
l en BY department_id);
employees

Y ao ble
e nt fera
17. l e
Create ma reporta s displays the departments where no sales representatives work. Include
nthat
C t r
on- *
the department number, department name, manager ID, and location in the output.
nSELECT
FROM departments
WHERE department_id NOT IN(SELECT department_id
FROM employees
WHERE job_id = 'SA_REP'
AND department_id IS NOT NULL);

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 14
Koenig Solutions Limited

18. Create the following statistical reports for the HR department. Include the department
number, department name, and the number of employees working in each department that:
a. Employs fewer than three employees:
SELECT d.department_id, d.department_name, COUNT(*)
FROM departments d JOIN employees e
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

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

b. Has the highest number of employees:


SELECT d.department_id, d.department_name, COUNT(*)
FROM departments d JOIN employees e
ON d.department_id = e.department_id
GROUP BY d.department_id, d.department_name
HAVING COUNT(*) = (SELECT MAX(COUNT(*)) s a
FROM employees
a
)h
m
co uide
GROUP BY department_id);
i
a tGl
g m
c. Has the lowest number of employees:
0 @ u d en
SELECT d.department_id, d.department_name, e d4 s SCOUNT(*)
t
am ee th i
FROM departments d JOIN employees
( C
ON d.department_id = e
m o us
e.department_id
t
e
GROUP BY d.department_id, du nsd.department_name
e
m e
HAVING COUNT(*)
a o A =le(SELECT ic MIN(COUNT(*))
lFROM
n t Y rab employees

m e s f e GROUP BY department_id);

Cle n-tran
19. n oa report that displays the employee number, last name, salary, department number,
Create
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;

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 15
Koenig Solutions Limited

20. Create an anniversary overview based on the hire date of employees. Sort the
anniversaries in ascending order.
SELECT last_name, TO_CHAR(hire_date, 'Month DD') BIRTHDAY
FROM employees
ORDER BY TO_CHAR(hire_date, 'DDD');
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 16
Koenig Solutions Limited

Case Study: Online Book Store

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 2014, 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
)h a
m
co uide
i l
g ma nt G
4 0 @ ude
e d s St
a m thi
e ( C se
u
e dumnse to
o Am lice
Y a ble
e t
n fera
Note: Ifle
you s the tables, you can execute the commands in the
mwant atonbuild
C t r
n- execute the commands in the Online_Book_Store_Drop_Tables.sql
Online_Book_Store_Create_Table.sql script in SQL Developer. If you want to drop the
nocan
tables, you
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.

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 17
Koenig Solutions Limited

Practice 1-2

Overview
In this practice, you create the tables based on the following table instance charts. Select the
appropriate data types and be sure to add integrity constraints.
Unauthorized reproduction or distribution prohibited Copyright 2014, 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
b. Table Name: BOOKS
Column Datatype Key Table Dependent On
a
has
Book_ID VARCHAR2 PK
Book_Name VARCHAR2 )
Author_ID VARCHAR2 FK AUTHORS
l c om ide
Price NUMBER m ai t Gu
@ g en
ud
Publisher_ID VARCHAR2 FK PUBLISHER
d 4 0 t
S
me thTable
c. Table Name: CUSTOMER
Column Name Data type a
Key
is Dependent On
e C
( PK use
dumnse to
Customer_ID VARCHAR2
Customer_Name
e
VARCHAR2
Street_Address
o Am lice
VARCHAR2
City
Y a VARCHAR2
b le
Phone_Numbern
e t a
erVARCHAR2
VARCHAR2
m s f
C le -tran
Credit_Card_Number FK Credit_Card_Details

on
d. CREDIT_CARD_DETAILS
n
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

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 18
Koenig Solutions Limited

f. Table Name: PUBLISHER


Column Data type Key Table Dependent Type
Publisher_ID VARCHAR2 PK
Publisher_Name VARCHAR2
g. Table Name: PURCHASE_HISTORY
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Column Data type Key Table Dependent Type


Customer_ID VARCHAR2 FK CUSTOMER
Order_ID NUMBER FK ORDER_DETAILS

h. Table Name: SHIPPING_TYPE


Column Data type Key Table Dependent Type
Shipping_Type VARCHAR2 PK
Shipping_Price NUMBER
i. Table Name: SHOPPING_CART
Column Data type Key Table Dependent On a
Shopping_Cart_ID NUMBER PK
) has
Book_ID VARCHAR2 FK
BOOKS
l c om ide
Price NUMBER
m ai t Gu
Date DATE
@ g en
Quantity NUMBER
d 4 0
S t ud
a me this
2. e (C touthe
Add additional Referential Integrity constraints setables created.
3. dum
Verify that the tables were created
e e
properly
s
tochecking in the Connections Navigator in
by
SQL Developer.
A m icen
4. Create a sequence a oto uniquely
l e l
identify each row in the ORDER_DETAILS table.
t Y a b
n 100;fdoernot allow caching of the values. Name the sequence
a. Startewith
m
CleORDER_ID_SEQ.
t r a ns
-
non

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 19
Koenig Solutions Limited

b. Verify the existence of the sequences in the Connections Navigator in SQL Developer.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
l c om ide
m ai t Gu
@ g en
5. 4 0
Add data to the tables. Create a script for each set ofddata S
to be t ud
added.
Add data to the following tables: a me this
e (C use
dumnse to
a. AUTHOR
b. PUBLISHER me
o A l i ce
a ble
c. SHIPPING_TYPE
Y
t
n fera
d. eCUSTOMER
m ans
Clee.n-CREDIT_CARD_DETAILS
tr
o
n 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.

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 20
Koenig Solutions Limited

6. Create a view named CUSTOMER_DETAILS to show the Customer Name, Customer


Address, and the details of the order placed by the customer. Order the results by
Customer ID.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

7. Make changes to the data in the tables.


a. Add a new book detail. Verify if the author detail for the book is available in the AUTHOR
table. If not, make an entry in the AUTHOR table.

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
s cart detail for the book details that you just entered in 7(a).
m a shopping
C n-tran
b. leEnter

no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 21
Koenig Solutions Limited

8. Create a report that contains each customers 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.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 22
Koenig Solutions Limited

Solution 1-2

Overview
The solution to Practice 1-2 is given as follows.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Tasks
1. Table Details
a. AUTHOR
CREATE TABLE AUTHOR
(
Author_ID VARCHAR2 (10) NOT NULL ,
Author_Name VARCHAR2 (20)
)
;
a
) has
c o m e
COMMENT ON TABLE AUTHOR IS 'Author'
a i Guid
l
;
@ gm ent
d 4 0
S t ud
m e is
C a t h
ALTER TABLE AUTHOR
e ( u se KEY (Author_ID);
dumnse to
ADD CONSTRAINT AUTHOR_PK PRIMARY
e
b. BOOKS
o Am lice
Y a BOOKS
b le
t
CREATE TABLE
e(n sfer a
m
ran VARCHAR2 (10) NOT NULL ,
Cle n-tBook_ID
no Book_Name VARCHAR2 (50) ,
Author_ID VARCHAR2 (10) NOT NULL ,
Price NUMBER (10) ,
Publisher_ID VARCHAR2 (10) NOT NULL
)
;

COMMENT ON TABLE BOOKS IS 'Books'


;

ALTER TABLE BOOKS


ADD CONSTRAINT books_PK PRIMARY KEY ( Book_ID );

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 23
Koenig Solutions Limited

c. CUSTOMER
CREATE TABLE CUSTOMER
(
Customer_ID VARCHAR2 (6) NOT NULL ,
Customer_Name VARCHAR2 (40) ,
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Street_Address VARCHAR2 (50) ,


City VARCHAR2 (25) ,
Phone_Number VARCHAR2 (15) ,
Credit_Card_Number VARCHAR2 (20) NOT NULL
)
;

COMMENT ON TABLE CUSTOMER IS 'Customer'


;

a
) h as
om id) e;
ALTER TABLE CUSTOMER
l c
ai t Gu
ADD CONSTRAINT Customer_PK PRIMARY KEY ( Customer_ID
m
g en
4 0 @ ud
d S t
d. CREDIT_CARD_DETAILS
a me this
e (C use
CREATE TABLE CREDIT_CARD_DETAILS
(
e dumnse to
A m iceVARCHAR2 (20) NOT NULL ,
Credit_Card_Number
a o le l VARCHAR2 (10) ,
Credit_Card_Type

e t Y erabDATE
nExpiry_Date
l e m ) ansf
C ; n-tr
no
COMMENT ON TABLE CREDIT_CARD_DETAILS IS 'Credit Card Details'
;

ALTER TABLE CREDIT_CARD_DETAILS


ADD CONSTRAINT Credit_Card_Details_PK PRIMARY KEY (
Credit_Card_Number) ;

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 24
Koenig Solutions Limited

e. ORDER_DETAILS
CREATE TABLE ORDER_DETAILS
(
Order_ID VARCHAR2 (6) NOT NULL ,
Customer_ID VARCHAR2 (6) NOT NULL ,
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Shipping_Type VARCHAR2 (10) NOT NULL ,


Date_of_Purchase DATE ,
Shopping_Cart_ID varchar2(6) NOT NULL
)
;

COMMENT ON TABLE ORDER_DETAILS IS 'Order Details'


;
ALTER TABLE ORDER_DETAILS
ADD CONSTRAINT ORDER_DETAILS_PK PRIMARY KEY (Order_ID ) ;
a
f. PUBLISHER
) has
CREATE TABLE PUBLISHER
l c om ide
(
m ai t Gu
Publisher_ID VARCHAR2 (10) NOT NULL g,
Publisher_Name VARCHAR2 (50) 40
@ uden
e d s St
)
a m thi
;
e ( C se
u
e dumnse to
o Am lice
COMMENTt Y
a bPUBLISHER
le
e n r
ON TABLE
e a IS 'Publisher'

l ;m
e a n sf
C n-tr
no
ALTER TABLE PUBLISHER
ADD CONSTRAINT PUBLISHER_PK PRIMARY KEY ( Publisher_ID) ;

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 25
Koenig Solutions Limited

g. PURCHASE_HISTORY
CREATE TABLE PURCHASE_HISTORY
(
Customer_ID VARCHAR2 (6) NOT NULL ,
Order_ID VARCHAR2 (6) NOT NULL
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

)
;

COMMENT ON TABLE PURCHASE_HISTORY IS 'Purchase History'


;

h. SHIPPING_TYPE
CREATE TABLE SHIPPING_TYPE
( s a
Shipping_Type VARCHAR2 (10) NOT NULL ,
a
)h
m
co uide
Shipping_Price NUMBER (6)
i l
)
g ma nt G
;
4 0 @ ude
e d s St
COMMENT ON TABLE SHIPPING_TYPEaIS t h i Type'
m 'Shipping
e ( C se
; u
e dumnse to
o Am SHIPPING_TYPE_PK
ALTER TABLE SHIPPING_TYPE
l i ce
Y a ble
ADD CONSTRAINT PRIMARY KEY ( Shipping_Type
) ;
e nt fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 26
Koenig Solutions Limited

i. SHOPPING _CART
CREATE TABLE SHOPPING_CART
(
Shopping_Cart_ID VARCHAR2 (6) NOT NULL ,
Book_ID VARCHAR2 (10) NOT NULL ,
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Price NUMBER (10) ,


Shopping_cart_Date DATE ,
Quantity NUMBER (6)
)
;

COMMENT ON TABLE SHOPPING_CART IS 'Shopping Cart'


;

ALTER TABLE SHOPPING_CART


a
ADD CONSTRAINT SHOPPING_CART_PK PRIMARY KEY (SHOPPING_CART_ID)
; ) has
l c om ide
i Gu
aCreated
2. m
Adding Additional Referential Integrity Constraints to the Table
g ent
@ d
d40 s Stu
a. Include a Foreign Key constraint in the BOOKSetable.
a m thi
e ( C se
u
dumnse to FOREIGN KEY
ALTER TABLE BOOKS
e
ADD CONSTRAINT BOOKS_AUTHOR_FK
(
o Am lice
Y a ble
Author_ID
e)n
t e ra
m ans AUTHORf
Cle n-REFERENCES
tr
n o (
Author_ID
)
;

ALTER TABLE BOOKS


ADD CONSTRAINT BOOKS_PUBLISHER_FK FOREIGN KEY
(
Publisher_ID
)
REFERENCES PUBLISHER
(
Publisher_ID
);

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 27
Koenig Solutions Limited

b. Include a Foreign Key constraint in the ORDER_DETAILS table.

ALTER TABLE ORDER_DETAILS


Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

ADD CONSTRAINT Order_ID_FK FOREIGN KEY


(
Customer_ID
)
REFERENCES CUSTOMER
(
Customer_ID
)
;

a
ALTER TABLE ORDER_DETAILS ) has
ADD CONSTRAINT FK_Order_details FOREIGN KEY co
m e
a i Guid
l
(
@ gm ent
Shipping_Type
d 4 0
S t ud
) e is
REFERENCES SHIPPING_TYPE am t h
e ( C se
(
m to u
Shipping_Type du e
e
m icen s
) A
o le l
a
nt Y ferab
;
e
m ans
CleALTER
n -trTABLE ORDER_DETAILS
o
n ADD CONSTRAINT Order_Details_fk FOREIGN KEY
(
Shopping_Cart_ID
)
REFERENCES SHOPPING_CART
(
Shopping_Cart_ID
)
;

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 28
Koenig Solutions Limited

c. Include a Foreign Key constraint in the PURCHASE_HISTORY table.

ALTER TABLE PURCHASE_HISTORY


ADD CONSTRAINT Pur_Hist_ORDER_DETAILS_FK FOREIGN KEY
(
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Order_ID
)
REFERENCES ORDER_DETAILS
(
Order_ID
)
;
ALTER TABLE PURCHASE_ HISTORY
ADD CONSTRAINT Purchase_History_CUSTOMER_FK FOREIGN KEY
(
a
Customer_ID
) has
)
l c om ide
REFERENCES CUSTOMER
m ai t Gu
(
@ g en
Customer_ID
d 4 0
S t ud
) ;
a me this
d. Include a Foreign Key constraint e
in
(CSHOPPING_CART
the u se table.
u m t o
m ed ense
A
ALTER TABLE oSHOPPING_CARTlic
ADDt Y
a l e
b SHOPPING_CART_BOOKS_FK FOREIGN KEY
e n r a
CONSTRAINT
e
l e m ( ansf
r
C n-tBook_ID
o
n )
REFERENCES BOOKS
(
Book_ID
)
;

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 29
Koenig Solutions Limited

3. Verify that the tables were created properly by checking in the Connections Navigator in
SQL Developer. In the Connections Navigator, expand Connections > myconnection >
Tables.

4. Create a sequence to uniquely identify each row in the ORDER DETAILS table.
Unauthorized reproduction or distribution prohibited Copyright 2014, 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.
Alternatively, you can also query the user_sequences data dictionary view:
SELECT * FROM user_sequences;
a
) h as
5. Add data to the tables.
l c om ide
a. AUTHOR Table
m ai t Gu
Author_ID @
Author_Name g en
d 4 0
S t ud
AN0001
m e
Oliver Goldsmith
is
C a t h
AN0002
e ( u se
Oscar Wilde
AN0003
e dumnse to George Bernard Shaw
AN0004
A m ice Leo Tolstoy
AN0005 Yao le l Percy Shelley
t a b
m en sfer
AN0006 Lord Byron
e
Cl AN0007 tra n John Keats
o n -
nAN0008 Rudyard Kipling
AN0009 P. G. Wodehouse

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 30
Koenig Solutions Limited

b. PUBLISHER Table

Publisher_ID Publisher_Name
PN0001 Elsevier
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

PN0002 Penguin Group


PN0003 Pearson Education
PN0004 Cambridge University Press
PN0005 Dorling Kindersley

a
) has
l c om ide
m ai t Gu
c. SHIPPING _TYPE
@ g en
d 4 0
S t ud
e is
mShipping_Price
Shipping_Type
C a t h
e ( u se
dumnse to 250
USPS 200
FedEx e
DHL o Am lice 150
Y a ble
e nt fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 31
Koenig Solutions Limited

d. CUSTOMER

Customer Customer _Name Street City Phone Credit _Card


_ ID _Address _number _Number
CN0001 VelasquezCarmen 283 King Seattle 587-99-6666 000-111-222-333
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

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 000-111-222-777
Kong
CN0006 Urguhart Molly 3035 Laurier
s a Quebec 418-542-9988 000-111-222-888
Blvd.
) h a
CN0007 Menchu Roberta Boulevard de m
Brussels 322-504-2228 e
co uid000-111-222-999
Waterloo 41 i
a tGl
g m
CN0008 Biri Ben 398 High St.
0 @ u d en
Columbu 614-455-9863 000-111-222-222

e d4 s St
s
CN0009 Catchpole 88 Alfred
a m
St. h i
Brisbane
t 616-399-1411 000-111-222-111
Antoinette ( C
e o us e
m
du nse t
e
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 32
Koenig Solutions Limited

e. CREDIT_CARD_DETAILS

Credit _Card_ Number Credit _Card _Type Expiry _Date


000-111-222-333 VISA 17-JUN-2009
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

000-111-222-444 MasterCard 24-SEP-2005


000-111-222-555 AMEX 11-JUL-2006
000-111-222-666 VISA 22-OCT-2008
000-111-222-777 AMEX 26-AUG-2000
000-111-222-888 MasterCard 15-MAR-2008
000-111-222-999 VISA 4-AUG-2009
000-111-222-111 Maestro 27-SEP-2001
000-111-222-222 AMEX 9-AUG-2004

s a
)h a
m
co uide
i l
g ma nt G
4 0 @ ude
e d s St
a m thi
e ( C se
u
e dumnse to
o Am lice
Y a ble
f. BOOKSe t
n fera
m ans
CleBookn tr
-_ID Book _Name Author _ID Price Publisher _ID
o
nBN0001 Florentine Tragedy AN0002 150 PN0002
BN0002 A Vision AN0002 100 PN0003
BN0003 Citizen of the World AN0001 100 PN0001

BN0004 The Complete Poetical AN0001 300 PN0001


Works of Oliver
Goldsmith
BN0005 Androcles and the Lion AN0003 90 PN0004

BN0006 An Unsocial Socialist AN0003 80 PN0004

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 33
Koenig Solutions Limited

BN0007 A Thing of Beauty is a AN0007 100 PN0002


Joy Forever

BN0008 Beyond the Pale AN0008 75 PN0005


Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

BN0009 The Clicking of AN0009 175 PN0005


Cuthbert

BN00010 Bride of Frankenstein AN0006 200 PN0001

BN00011 Shelley's Poetry and AN0005 150 PN0003


Prose

BN00012 War and Peace AN0004 150 PN0002 a


) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
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

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 34
Koenig Solutions Limited

SC0008 BN0006 100 25-NOV-2009 7


SC0009 BN0006 150 18-SPET-2009 8
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
h. ORDER _DETAILS a
) h _Cart
Order _ID Customer Shipping_ m
o ide _ID
Date _of _Purchase Shopping
c
_ID Type l
ai t Gu
OD0001 CN0001 USPS 12-JUN-2001 m
g enSC0002
4 0 @ ud SC0005
OD0002 CN0002 USPS d
28-JUN-2005S t
OD0003 CN0003 FedEx a me31-JUL-2004
t h is SC0007
( C s e
e o u14-AUG-2006
OD0004 CN0004
u m
FedEx
t SC0004
OD0005 CN0005 ed FedEx
n se 21-SEP-2006 SC0003
A m e
OD0006 a o le licDHL
CN0006 28-OCT-2007 SC0001
OD0007
Y
nt fCN0007 ra b DHL 11-AUG-2007 SC0006
m e s e
CleOD0008
- t r an CN0008 DHL 18-SEP-2009 SC0008
o n
nOD0009 CN0009 USPS 25-NOV-2009 SC0009

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 35
Koenig Solutions Limited

i. PURCHASE_HISTORY
Customer _ID Order _ID
CN0001 OD0001
CN0003 OD0002
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

CN0004 OD0005
CN0009 OD0007

6. Create a view named CUSTOMER_DETAILS to show the Customer Name, Customer


a
has
Address, and the details of the order placed by the customer. Order the results by Customer
ID. )
l c om ide
CREATE VIEW customer_details AS
i Gu
ao.order_id,
SELECT m
g ent
c.customer_name, c.street_address,
@ ud
o.customer_id, o.shipping_type, o.date_of_purchase,
4 0
o.shopping_cart_id d S t
FROM
a me this o
customer c JOIN order_details
c.customer_id =(C se
ON
e u
o.customer_id;

e d um se to
SELECT *
A m icen
FROM
a o le l
customer_details
t Ycustomer_id;
ORDERnBY
e e r a b
l e m ansf
C n-tr
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 36
Koenig Solutions Limited

7. Make changes to the data in the tables.


a. Add a new book detail. Verify if the author detail for the book is available in the AUTHOR
table. If not, make an entry in the AUTHOR table.
INSERT INTO books(book_id, book_name, author_id, price,
publisher_id)
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

VALUES ('BN0013','Two States','AN0009','150','PN0005');

s a
)h a
m
co uide
i l
g ma nt G
4 0 @ ude
d that
b. Enter a shopping cart detail for the bookedetails S t just entered in 7(a).
you
am e th i s
(
e o usC
m
du nse t
INSERT INTO shopping_cart(shopping_cart_id, book_id, price,
e
Shopping_cart_date,quantity)
o Am lice
VALUES ('SC0010','BN0013','200',TO_DATE('12-JUN-2006','DD-MON-
Y a ble
YYYY'),'12');
e t
n fera
m ans
8. Cle anreport
Create r that contains each customers history of purchasing books. Be sure to
-tcustomer
include
n othe 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.

SELECT c.customer_name CUSTOMER, c.customer_id,


s.shopping_cart_id, s.book_id,o.date_of_purchase
FROM customer c
JOIN order_details o
ON o.customer_id=c.customer_id
JOIN shopping_cart s
ON o.shopping_cart_id=s.shopping_cart_id;

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 37
Koenig Solutions Limited
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a
) has
l c om ide
m ai t Gu
@ g en
d 4 0
S t ud
a me this
e (C use
e dumnse to
o Am lice
Y a ble
e t
n fera
m s
Cle n-tran
no

Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 38

You might also like