Download as pdf or txt
Download as pdf or txt
You are on page 1of 146

Organizacion Educativa Certificatic Sฺ C

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

s a
) h a
ฺm x
o m
Oracle Database 12c: SQL
Workshop I uroฺc ideฺ
f u t G u
r o
p den t
e s @ tu
a l
Activity Guide
S
ฺ m or this
i g no o use
( b en se t
r u z licen
s C ble
e
ral sfera
o
M ran
o
g on-t
n
e n i n
B

D80190GC11
Edition 1.1
July 2014
D87242
Organizacion Educativa Certificatic Sฺ C

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. Government’s 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
s a
) h a
owners.
ฺ m x
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective

ฺ c om ฺ
Author
t u ro uide
Dimpi Rani Sarmah u
rof ent G
p
Technical Contributors and Reviewers l e s@ Stud
o
Nancy Greenberg, Swarnapriya Shridhar, Bryan Roberts,ra Laszlo
t h isCzinkoczki, KimSeong Loh,
o ฺ
Brent Dayley, Jim Spiller, Christopher Wensley, m
Manish
s e Clair Bennett, Yanti Chang,
Pawar,
n
ig to
Joel Goodman, Gerlinde Frenzen and Madhavi u
Siddireddy
e n
z (b ense
C ru e lic
a l s using:
This book was published
e r a bl Oracle Tutor
M or nsfe
i g no n-tra
Be
n no
Organizacion Educativa Certificatic Sฺ C

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 s a
Practice 4-1: Using Single-Row Functions to Customize Output................................................................ 4-3
) h a
Solution 4-1: Using Single-Row Functions to Customize Output................................................................ 4-9
ฺ m x
Practices for Lesson 5: Using Conversion Functions and Conditional Expressions .............................
ฺ c om 5-1ฺ
u ro uide5-2
Practices for Lesson 5: Overview.............................................................................................................
t
r o f u
Practice 5-1: Using Conversion Functions and Conditional Expressions....................................................
t G 5-3

@ p den
Solution 5-1: Using Conversion Functions and Conditional Expressions.................................................... 5-9
Practices for Lesson 6: Reporting Aggregated Data Using the Group s
le Functions u
St................................... 6-1
o r a h i s
Practices for Lesson 6: Overview............................................................................................................. 6-2
ฺ m t
Practice 6-1: Reporting Aggregated Data by Using Group
i g nGroup u se
o Functions.........................................................
Functions......................................................... 6-3
Solution 6-1: Reporting Aggregated Data by Using
e n e t o 6-6
Practices for Lesson 7: Displaying Data
z (bfromeMultiple n s Tables Using Joins ............................................ 7-1
C u
r e lic
Practices for Lesson 7: Overview ............................................................................................................. 7-2
sData from
Practice 7-1: Displaying
l e a l Tables by Using Joins............................................................ 7-3
bMultiple
o r a
Solution 7-1: Displaying Data
f e r
from Multiple Tables by Using Joins............................................................ 7-8
s
MLessonra8:nUsing Subqueries to Solve Queries ................................................................... 8-1
n o
Practices for
g ofornLesson -t 8: Overview............................................................................................................. 8-2
e n i Practices
n
B 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
Organizacion Educativa Certificatic Sฺ C

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ฺ

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Oracle Database 12c: SQL Workshop I Table of Contents


ii
Organizacion Educativa Certificatic Sฺ C
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
ฺ m x
ฺ c om ฺ
Practices for Lesson 1:
ro uide
u t u
Introduction rof t G
p de n
Chapter 1 s@ t u
e
ral this S
o
ฺm se
n o
g to u
n i
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 1
Organizacion Educativa Certificatic Sฺ C

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.
s a
• For any query, the sequence of rows retrieved from the database may differ from
) h a
the screenshots shown.
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 2
Organizacion Educativa Certificatic Sฺ C

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.
s a
2. Create a New Oracle SQL Developer Database Connection
) h a
ฺ m x
a. To create a new database connection, in the Connections Navigator, right-click

Database Connection dialog box appears. ฺ c om ฺ


Connections and select New Connection from the context menu. The New/Select

t u ro uide
u
b. Create a database connection by using the following information:
rof ent G
Connection Name: myconnection p
Username: ora1 l e s@ Stud
Password: ora1 o ra this
n o ฺm se
Hostname: localhost
n i g to u
Port: 1521
SID: ORCL uz
(be ense
Cr the l e lic
Ensure that yous select
le eSQL a
Save Password check box.
bDeveloper Database Connection and Connecting to the
3. Testingra
the Oracle r
o Mo ransf
Database
i gn oa.n-Testt the new connection.
e n n b. If the status is Success, connect to the database by using this new connection.
B
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
Organizacion Educativa Certificatic Sฺ C

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.

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n
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
Organizacion Educativa Certificatic Sฺ C

The New / Select Database Connection dialog box appears.


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

s a
) h a
ฺ m x
ฺ c om ฺ
u ro uide
b. Create a database connection by using the following information:
t
i. Connection Name: myconnection
u
rof ent G
p
ii. Username: ora1
l e s@ Stud
iii. Password: ora1
o ra this
iv. Hostname: localhost
n o ฺm se
v. Port: 1521 nig t o u
vi. SID: ORCL
z (be ense
Ensure C ruyou select
that
e licthe Save Password check box.
s
le erab l
r a
o Mo ransf
n i gn on-t
Be n

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 5
Organizacion Educativa Certificatic Sฺ C

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
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
of thisnnew
rusing t G
p
b. If the status is Success, connect to the database by
@ d e connection.
s
le is St u
r a
o ฺ mo se th
n i gn to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
4. Browsing the Tables in the Connections Navigator
r u
of nt G
p de to you in the
a. In the Connections Navigator, view the objects that are available
@present:
e s t u
ral this S
Tables node. Verify that the following tables are
COUNTRIES o
ฺm se
DEPARTMENTS
n o
g to u
EMPLOYEES
n i
JOB_GRADES
z (be ense
JOB_HISTORY
JOBS Cr
u lic
s
le erab l e
r a
LOCATIONS
Mo REGIONS
a n sf
o
gn on-tr
n i n
Be

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 7
Organizacion Educativa Certificatic Sฺ C

b. Browse the structure of the EMPLOYEES table.


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

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
c. View the data of the DEPARTMENTS table. u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 8
Organizacion Educativa Certificatic Sฺ C
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
ฺ m x
ฺ c om ฺ
Practices for Lesson 2:
ro uide
u t u
Retrieving Data
p rof Using n t Gthe
SQL SELECT
e s t u de
@ Statement
o ra2l this S
n o ฺm se
Chapter

n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C

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

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C

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

s a
2. The following SELECT statement executes successfully:
) h a
SELECT * ฺ m x
FROM job_grades;
ฺ c om ฺ
t u ro uide
True/False u
rof ent G
p
l e s@ Stud
o
3. There are four coding errors in the following statement.ra tCan h isyou identify them?
ฺ m
SELECT employee_id, last_name
i g no o use
sal x 12 ANNUAL SALARY
( b en se t
FROM
u z licen
employees;
r
Task 2 s C ble
e
ral points ra you begin with the practices:
o
Note the following
s f e
before
M your
•noSave all r a npractice
i - t
g o/home/oracle/labs/sql1/labs
n files at the following location:
n n
Be
• 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
Organizacion Educativa Certificatic Sฺ C

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ฺ

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
r u
of nt G
5. Your task is to determine the structure of the EMPLOYEES table and its contents.
a. Determine the structure of the EMPLOYEES table. @ p de
e s t u
o ral this S
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C

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.

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C

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
) h a
ฺ m x
Task 3
ฺ c om ฺ
If you have time, complete the following exercises:
t u ro uide
7. The HR department wants more descriptive column headings for
r o u
f reporttonGemployees.
its
p
Copy the statement from lab_02_5b.sql to a new SQL Worksheet. d n the columns
eName
s @ u
Emp #, Employee, Job, and Hire Date, respectively.
r a le ThenisrunStthe query again.
o ฺ mo se th
n i gn to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C

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
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
If you want an extra challenge, complete the following exercise: p
e @ tud
stable,
l
ra bythaiscomma.
9. To familiarize yourself with the data in the EMPLOYEES S a query to display all
create
the data from that table. Separate each column
ฺ m ooutput Name the column
o e
THE_OUTPUT.
n i gn to us
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C

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;
s a
) h a
True/False
ฺ m x
ฺ c om ฺ
t
3. There are four coding errors in the following statement. Can you identifyu o ide
rthem?
o f u G u
SELECT employee_id, last_name r
p den t
e s @ tu
sal x 12 ANNUAL SALARY
a l S
FROM employees;
ฺ m or this
 The EMPLOYEES table does not contain
i g n u se called sal. The column is called
o a column
SALARY.
( b en se to
r u z liisce*, nnot x, as shown in line 2.
 The multiplication operator
 The ANNUALs C alias
b le cannot include spaces. The alias should read
l e SALARY
a
ra sfeorr should be enclosed within double quotation marks.
ANNUAL_SALARY
o
 oAMcomma r aisnmissing after the LAST_NAME column.
n
ig 2 non - t
e nTask
B 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
Organizacion Educativa Certificatic Sฺ C

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 s a
) h a
FROM employees;
ฺ m x
Task 3 ฺ c om ฺ
t u ro uide
If you have time, complete the following exercises:
r u
of nt G
p
7. The HR department wants more descriptive column headings for its d e on employees.
report
Copy the statement from lab_02_5b.sql to a newle s@
SQL t
Worksheet. u
S the queryName the columns
o r
Emp #, Employee, Job, and Hire Date, respectively. a Then
h i srun again.
ฺ m t
SELECT employee_id "Emp g#",
i no last_name
u se "Employee",
n e to"Hire Date"
job_id "Job",ehire_date
b
z ( e n s
FROM u
Cr ble lic
employees;
s
8. The HRo rale sfehasrarequested a report of all employees and their job IDs. Display the
department
o
last M concatenated
name r an with the job ID (separated by a comma and space) and name the
n - t
e nig columnn onEmployee and Title.
B SELECT 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
Organizacion Educativa Certificatic Sฺ C

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;

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
ฺ m x
ฺ c om ฺ
Practices for Lesson 3:
ro uide
u t u
Restricting and
p rof Sorting
n t G Data
Chapter 3les
@ tude
o ra this S
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 1
Organizacion Educativa Certificatic Sฺ C

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

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 2
Organizacion Educativa Certificatic Sฺ C

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
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p d and department
2. Open a new SQL Worksheet. Create a report that displays l e s@theSlasttuname
number for employee number 176. Run the query. o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
3. The HR department
a l e s needs
r a btol find high-salary and low-salary employees. Modify
M or nstofedisplay the last name and salary for any employee whose salary is not
lab_03_01.sql
ninothe range
- a through $12,000. Save your SQL statement as lab_03_03.sql.
tr$5,000
i g n
Be
n no

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

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 3
Organizacion Educativa Certificatic Sฺ C

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.

s a
) h a
ฺ m x
ฺ c om ฺ
t u rowhouearn
i de
u
of thencolumns
6. Modify lab_03_03.sql to display the last name and salary of employees
rLabel t G
between $5,000 and $12,000, and are in department 20 or 50. p
@ tude as
s
Employee and Monthly Salary, respectively. Save lab_03_03.sql
e
ral this S
lab_03_06.sql again. Run the statement in lab_03_06.sql.
o
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
7. The HRo r a
department f r a report that displays the last name and hire date of all
eneeds
M who
employees s
anwere hired in 2006.
n o - t r
e nig non
B

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
Organizacion Educativa Certificatic Sฺ C

9. Create a report to display the last name, salary, and commission of all employees who earn
commissions. Sort the data in descending order of salary and commissions.
Use the column’s numeric position in the ORDER BY clause.
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
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
11. The HR department wants to run reportsobased
n ฺm onsaemanager. Create a query that prompts
i
the user for a manager ID, and generates
n the u ID, last name, salary, and
g toemployee
department for that manager’s
( b e se
employees. The HR department wants the ability to sort the
n
ruz eYouliccan
report on a selected column.
C
e test the data with the following values:
manager_id =le
a
s sorted
103,
r a bbyl last_name:
M or nsfe
i g no n-tra
Be
n 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
Organizacion Educativa Certificatic Sฺ C

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.

s a
) h a
If you want an extra challenge, complete the following exercises: ฺ m x

14. Display the last name, job, and salary for all employees whose jobs are eitherc othatmof aฺ
ro$2,500,
sales representative or a stock clerk, and whose salaries are not equaluto
t u i e
d$3,500,
or $7,000. u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abtoldisplay the last name, salary, and commission for all
15. Modify lab_03_06.sql
o
employees
a f er
r whosescommission is 20%. Save lab_03_06.sql as lab_03_15.sql again.
o Mthe statement
a n
gn on-tr
Rerun in lab_03_15.sql.
n i n
Be

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

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 6
Organizacion Educativa Certificatic Sฺ C

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
s a
WHERE employee_id = 176;
) h a
3. The HR department needs to find high-salary and low-salary employees. Modify ฺ m x
c om ฺ
lab_03_01.sql to display the last name and salary for all employees whose salary is not

t u ro uide
in the range $5,000 through $12,000. Save your SQL statement as lab_03_03.sql.
u
rof ent G
SELECT last_name, salary
p
FROM employees
l e s@ Stud
WHERE salary NOT BETWEEN 5000 AND
o ra 12000;
t h is
4. Create a report to display the last name,o ฺ m
job ID, and sehire date for employees with the last
i
names of Matos and Taylor. Order the g nquery o
in u
ascending order by hire date.
e n e t
SELECT z
last_name,(b job_id,
e n s hire_date
FROM
u
Cr ble lic
employees
s
WHEREale last_name
o f e ra IN ('Matos', 'Taylor')
r BY hire_date;
o M rans
ORDER

n
n
5.ig Displayn
o -tlast name and department ID of all employees in departments 20 or 50 in
the
n alphabetical order by last_name.
Be 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
Organizacion Educativa Certificatic Sฺ C

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
column’s numeric position in the ORDER BY clause.
SELECT last_name, salary, commission_pct s a
FROM employees ) h a
WHERE commission_pct IS NOT NULL ฺ m x
ORDER BY 2 DESC, 3 DESC; ฺ c om ฺ
10. Members of the HR department want to have more flexibility with the t u ro that
queries u i deare
you
writing. They would like a report that displays the last name and
u
f of employees
rosalary t G who
earn more than an amount that the user specifies after a @ p n
decan use the query
prompt. (You
e s t u
o ral this S
created in Task 1 and modify it.) Save this query to a file named lab_03_10.sql.
Enter 12000 when prompted:
n o ฺm se
SELECT last_name, salary n i g to u
employees(b
e se
FROM
r u z l i c en
WHERE
s C ble
salary > &sal_amt;
e
ralwhensfprompted
Enter 12000
o era for a value in a dialog box. Click OK.
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 8
Organizacion Educativa Certificatic Sฺ C

11. The HR department wants to run reports based on a manager. Create a query that prompts
the user for a manager ID, and generates the employee ID, last name, salary, and
department for that manager’s employees. The HR department wants the ability to sort the
report on a selected column. You can test the data with the following values:
manager _id = 103, sorted by last_name
manager_id = 201, sorted by salary
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:


s a
12. Display the last names of all employees where the third letter of the name is “a.”
) h a
SELECT last_name
ฺ m x
FROM employees
ฺ c om ฺ
WHERE last_name LIKE '__a%';
t u ro uide
13. Display the last names of all employees who have both an “a” and u
rofan e t G last name.
“e” in their
p n
SELECT last_name
l e s@ Stud
FROM employees
o ra this
m
noฺ o use
WHERE last_name LIKE '%a%'
AND last_name LIKEig'%e%';
( b en se t
r u z licen
s C bcomplete
If you want an extra challenge,
l e the following exercises:
e
l name,
ralast
14. Display the a and salary for all employees whose job is that of a sales
rjob,
o f e
o M rans
representative or a stock clerk, and whose salary is not equal to $2,500, $3,500, or $7,000.

n i gn SELECT
o n -t last_name, job_id, salary
Be 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
Organizacion Educativa Certificatic Sฺ C
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 10
Organizacion Educativa Certificatic Sฺ C
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
ฺ m x
ฺ c om ฺ
Practices for Lesson ro uUsing
4: i de
u t u
rof ent Gto
Single-Row Functions
p
Customize s@Output
t ud
l e
ra4 this S
o
ฺm se
Chapter
n o
g to u
n i
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C

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

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C

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 s a
column New Salary. Save your SQL statement in a file named lab_04_02.sql. ) h a
ฺ m x
3. Run your query in the lab_04_02.sql file.
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C

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 x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
5. Performothe
a
r following f r
etasks:
M a query s
an that displays the last name (with the first letter in uppercase and all the
a.o Write -
n t r
g onletters in lowercase) and the length of the last name for all employees whose
Beni nother name 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
Organizacion Educativa Certificatic Sฺ C

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
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
(be eexercises:
If you have time, complete thezfollowing n se
C ruwantsetolifind
c the duration of employment for each employee. For
6. The HR department
s
le displaya l
bthe last name and calculate the number of months between
r a
each employee,
todayoand the s e r
f on which the employee was hired. Label the column as
o M ran date
i g n of months
- t must be Order
MONTHS_WORKED.
n
your results by the number of months employed. The number

Be
n no 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
Organizacion Educativa Certificatic Sฺ C

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ฺ

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C

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ฺ

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
8.
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C

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 x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
M arquery
9. oCreate an to display the last name and the number of weeks employed for all
n
g employees- t
n in department 90. Label the number of weeks column as TENURE. Truncate
Beni the nonumber of weeks value to 0 decimal places. Show the records in descending order
of the employee’s tenure.
Note: The TENURE value will differ because it depends on the date on which you run the
query.

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
Organizacion Educativa Certificatic Sฺ C

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;
s a
) h a
3. Run your query in the file lab_04_02.sql. ฺ m x
ฺ c om ฺ
SELECT employee_id, last_name, salary,
ROUND(salary * 1.155, 0) "New Salary" tur
o ide
o f u G u
FROM employees; r
p den t
e s @ tu
a l S
4. Modify your query in the lab_04_02.sql to add
ฺ m or aSave
columnis
t h that subtracts the old salary

n o
from the new salary. Label the column Increase.
u s e the contents of the file as
g to
lab_04_04.sql. Run the revised iquery.
n
e se salary,
(b last_name,
SELECT employee_id, z e n
C ru e li*c 1.155, 0) "New Salary",
ROUND(salary
l e s abl * 1.155, 0) - salary "Increase"
ROUND(salary
o
FROM a
r employees;
s f er
o M ran
n i g on-t
n
n the following tasks:
Be 5. 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
Organizacion Educativa Certificatic Sฺ C

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%' ) s a
ORDER BY last_name; ) h a
ฺ m x
ฺ c om ฺ
If you have time, complete the following exercises:
t u ro uide
6. The HR department wants to find the duration of employment for u
rof ofeach GbetweenFor
employee.
t
each employee, display the last name and calculate the number p de n
months
today and the date on which the employee was hired.
e s @ t
Label the ucolumn
MONTHS_WORKED. Order your results by the number
o ral tofhmonths
i s S employed. The number
of months must be rounded to the closest
n o ฺmwholesnumber.
e
Note: Because this query depends n i g
on the o
date
t u
when it was executed, the values in the
MONTHS_WORKED column will e
(b ens
differ for e
you.
u z lic
r eROUND(MONTHS_BETWEEN(
s C
SELECT last_name,
l
bhire_date)) MONTHS_WORKED
r a leSYSDATE,
e r a
M o nsf
FROM employees

i g n n-t a months_worked;
o ORDER rBY

Be no a query to display the last name and salary for all employees. Format the salary
n 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
Organizacion Educativa Certificatic Sฺ C

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 employee’s tenure.
Note: The TENURE value will differ because it depends on the date when you run the query. s a
) h a
SELECT last_name, trunc((SYSDATE-hire_date)/7) AS TENURE
ฺ m x
FROM employees
ฺ c om ฺ
WHERE department_id = 90
t u ro uide
ORDER BY TENURE DESC; u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
ฺ m x
ฺ c om ฺ
Practices for Lesson ro uUsing
5: i de
u t u
rof ent Gand
Conversion Functions
p
Conditional s@ Expressions
t ud
l e
ra5 this S
o
ฺm se
Chapter
n o
g to u
n i
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 1
Organizacion Educativa Certificatic Sฺ C

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

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 2
Organizacion Educativa Certificatic Sฺ C

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.

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 3
Organizacion Educativa Certificatic Sฺ C

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

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 4
Organizacion Educativa Certificatic Sฺ C

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ฺ

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 5
Organizacion Educativa Certificatic Sฺ C

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

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 6
Organizacion Educativa Certificatic Sฺ C

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ฺ

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 7
Organizacion Educativa Certificatic Sฺ C

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ฺ

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 8
Organizacion Educativa Certificatic Sฺ C

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 employee’s last name, hire date, and salary review date, which is the first
Monday after six months of service. Label the column REVIEW. Format the dates to appear
in a format that is similar to “Monday, the Thirty-First of July, 2000.”
s a
SELECT last_name, hire_date,
) h a
TO_CHAR(NEXT_DAY(ADD_MONTHS(hire_date, 6),'MONDAY'),
ฺ m x
FROM
'fmDay, "the" Ddspth "of" Month, YYYY') REVIEW
employees; ฺ c om ฺ
t u ro Ifuanide
3. Create a query that displays employees’ last names and commission
employee does not earn commission, show “No Commission.” Label
u amounts.
rof theencolumn
t G COMM.
p
SELECT last_name, l e s@ Stud
NVL(TO_CHAR(commission_pct), o ra 'No t h s
iCommission') COMM
FROM employees; ฺ m
o use
i g n
en that
4. Using the CASE function, write a query
e to the grade of all employees based on the
displays
value of the JOB_ID column,(b s
using the following data:
u z c e n
Job
s Cr ble liGrade
AD_PRES ale ra
o r f e A

o M rans
ST_MAN B
n
g IT_PROG - t
eni non
C
B 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
Organizacion Educativa Certificatic Sฺ C

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'
s a
WHEN job_id = 'IT_PROG' THEN 'C'
) h a
WHEN job_id = 'ST_MAN'
ฺ m x THEN 'B'
WHEN job_id = 'AD_PRES'
ฺ c om ฺ THEN 'A'
ELSE '0' END GRADE
t u ro uide
FROM employees; u
rof ent G
p
l e
6. Rewrite the statement in the preceding exercise by usings@ t ud DECODE syntax.
the searched
S
o ra this
n o ฺm se
SELECT job_id, decode (job_id,
n i g to u
z be nse 'E',
('ST_CLERK',
C l ice
ru e'SA_REP', 'D',
l e s abl 'IT_PROG', 'C',
o r a
s f er 'ST_MAN', 'B',
o M ran
i g n n - t 'AD_PRES', 'A',
n n o
Be
'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
Organizacion Educativa Certificatic Sฺ C
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
ฺ m x
ฺ c om ฺ
Practices for Lesson 6:
ro uide
u t u
rof ent GData
Reporting Aggregated
p
Using the Group
s@ t udFunctions
l e
ra6 this S
o
ฺm se
Chapter
n o
g to u
n i
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C

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

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C

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
) h a
ฺ m x
The HR department needs the following reports:
ฺ c om ฺ
o theidcolumns
4. Find the highest, lowest, sum, and average salary of all employees.rLabel
tu results e
Maximum, Minimum, Sum, and Average, respectively. Roundfu your u
to the
p ro ent G
nearest whole number. Save your SQL statement as lab_06_04.sql. Run the query.
e @
s Stu d
a l
ฺ m or this
noto display
u e
sthe
5. Modify the query in lab_06_04.sql
n i g t o minimum, maximum, sum, and
e
b ns
average salary for each (job type. e
Save lab_06_04.sql as lab_06_05.sql again.
Run the statementru z lic e
in lab_06_05.sql.
s C l e
r a le erab
o Mo ransf
n i gn on-t
Be n

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
Organizacion Educativa Certificatic Sฺ C

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ฺ

s a
h a
Save the script to a file named lab_06_06.sql. Run the query. Enter IT_PROG ฺ x)
Generalize the query so that the user in the HR department is prompted for a job title.
mwhen
prompted.
ฺ c om ฺ
t u ro uide
u
rof ent G
p
@ Label d column Number of
7. Determine the number of managers without listing l e sthem. S t uthe
Managers. o ra this
n o ฺm sethe number of managers.
Hint: Use the MANAGER_ID column
n i g to u
to determine

z (be ense
C ru e lic
l e s abl
o r
8. Find thea er between the highest and lowest salaries. Label the column
difference
s f
o M ran
DIFFERENCE.

n i g on-t
n
Be n
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
Organizacion Educativa Certificatic Sฺ C

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.

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C

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 s a
Maximum, Minimum, Sum, and Average, respectively. Round your results to the nearest
) h a
whole number. Save your SQL statement as lab_06_04.sql. Run the query.
ฺ m x
SELECT ROUND(MAX(salary),0) "Maximum", ฺ c om ฺ
ROUND(MIN(salary),0) "Minimum",
t u ro uide
ROUND(SUM(salary),0) "Sum",
r o f u t G
p n
ROUND(AVG(salary),0) "Average"
e s @ tude
ral this S
FROM employees;
o
ฺm se
5. Modify the query in lab_06_04.sql n o
g to the
to display u minimum, maximum, sum, and average
n i
e se as lab_06_05.sql again. Run the
salary for each job type. Saveblab_06_04.sql
statement in lab_06_05.sql. (
z licen
r u
C ROUND(MAX(salary),0)
l e s
SELECT job_id,
a b le "Maximum",
o r a f r
e ROUND(SUM(salary),0) "Minimum",
ROUND(MIN(salary),0)
M ran s "Sum",
n o
g FROM t
- employees ROUND(AVG(salary),0) "Average"
n i n o n
Be 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
Organizacion Educativa Certificatic Sฺ C

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.
s a
SELECT MAX(salary) - MIN(salary) DIFFERENCE
) h a
FROM employees;
ฺ m x
ฺ c om ฺ
If you have time, complete the following exercises:
t u ro uide
9. Create a report to display the manager number and the salary ofothe u
f lowest-paid
r Exclude t G employee
for that manager. Exclude anyone whose manager is not known. p d e nany groups where
s @ u
the minimum salary is $6,000 or less. Sort the output
r a i s St order of salary.
lein descending
SELECT manager_id, MIN(salary)
ฺ m o th
o us e
FROM employees
n i gn NULLt o
(be ense
WHERE manager_id IS NOT
GROUP BY manager_id
HAVING z
ru e li>c 6000
MIN(salary)
C
ORDER BY sMIN(salary) bl DESC;
a l e r a
M or nsfe
i g nIfoyou want
n - raextra challenge, complete the following exercises:
tan
n
Be 10. Createnoa 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
Organizacion Educativa Certificatic Sฺ C

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;

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
ฺ m x
ฺ c om ฺ
Practices for Lesson 7:
ro uide
u t u
Displaying Data
p rof from n t Multiple
G
Tables Using
e s @ Joins
t u de
o ra7l this S
n o ฺm se
Chapter

n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C

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

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C

Practice 7-1: Displaying Data from Multiple Tables by Using Joins


Overview
This practice is intended to give you experience in extracting data from multiple tables using the
SQL:1999–compliant joins.
Tasks
Unauthorized reproduction or distribution prohibitedฺ Copyright© 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.

s a
) h a
2. x
The HR department needs a report of all employees with corresponding departments. Write
ฺ m
employees. ฺ c om ฺ
a query to display the last name, department number, and department name for these

t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C

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.

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n
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
Organizacion Educativa Certificatic Sฺ C
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 x
… ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
7. The HR department needs
C rufirstaeshow ictheonstructure
report
l job grades and salaries. To familiarize yourself with
the JOB_GRADES
l e s abl
table, of the JOB_GRADES table. Then create a
a fthe
query thatrdisplays
o s ername, job, department name, salary, and grade for all employees.
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
If you want an extra challenge, complete the following exercises:
o raof allthemployees
is
8. The HR department wants to determine the
o ฺ mnames
s e who were hired after

n i gn to u
Davies. Create a query to display the name and hire date of any employee hired after

(be ense
employee Davies.
z
ru e lic
C
s abl
l e
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C

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ฺ

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C

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
s a
JOIN departments
) h a
USING (department_id);
ฺ m x
3.
ฺ c om ฺ
The HR department needs a report of employees in Toronto. Display the last name, job,
department number, and department name for all employees who work in Toronto.
t u ro uide
SELECT e.last_name, e.job_id, e.department_id, u
rof ent G
d.department_name
FROM employees e JOIN departments d p
ON (e.department_id = d.department_id) l e s@ Stud
JOIN locations l o ra this
n o ฺm se
ig to u
USING (location_id)
WHERE LOWER(l.city) e =n'toronto';
(b enlast
4. Create a report to displayzemployees’
senames and employee numbers along with their
C
managers’ last names ruand manager
e lic numbers. Label the columns Employee, Emp#,
Manager, and s b l
leMgr#,erespectively.
a Save your SQL statement as lab_07_04.sql. Run the
r a r
M ransf
query. o
o
n i gn SELECT
o n -t w.last_name "Employee", w.employee_id "EMP#",
Be 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
Organizacion Educativa Certificatic Sฺ C

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
s a
/
) h a
SELECT e.last_name, e.job_id, d.department_name,
ฺ m x
e.salary, j.grade_level
ฺ c om ฺ
FROM employees e JOIN departments d
t u ro uide
ON (e.department_id = d.department_id) u
rof ent G
JOIN job_grades j p
ON l e s@ Stud
(e.salary BETWEEN j.lowest_sal AND j.highest_sal);
o
If you want an extra challenge, complete the following
raexercises:
t h is
ฺ m sofeall employees who were hired after
8. The HR department wants to determine i g nothe names
u
enthe name
Davies. Create a query to display
b e to hire date of any employee hired after
and
employee Davies. (
z licen s
r u
C ble e.hire_date
s
SELECT e.last_name,
e
FROMral employees e ra e JOIN employees davies
M o ns f
n o ON
- t r a
(davies.last_name = 'Davies')

e nig nWHERE on davies.hire_date < e.hire_date;


B 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
Organizacion Educativa Certificatic Sฺ C
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
ฺ m x
ฺ c om ฺ
Practices for Lesson ro uUsing
8: i de
f u t u
Subqueries to roSolve tQueries
G
p n
Chapter 8les
@ tude
o ra this S
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 8: Using Subqueries to Solve Queries


Chapter 8 - Page 1
Organizacion Educativa Certificatic Sฺ C

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

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 8: Using Subqueries to Solve Queries


Chapter 8 - Page 2
Organizacion Educativa Certificatic Sฺ C

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 employee’s last name. The
query then displays the last name and hire date of any employee in the same department
as the employee whose name the user supplies (excluding that employee). For example, if
the user enters Zlotkey, find all employees who work with Zlotkey (excluding Zlotkey).

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
2. Create a report that displays(b
e se number, last name, and salary of all employees
r
who earn more than the u z
averagel i c en Sort the results in ascending order by salary.
the employee
salary.
s C ble
e
ral sfera
o
M ran
o
g on-t
n
n i n
Be

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

Practices for Lesson 8: Using Subqueries to Solve Queries


Chapter 8 - Page 3
Organizacion Educativa Certificatic Sฺ C

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ฺ

s a
4. The HR department needs a report that displays the last name, department number, and
) h a
job ID of all employees whose department location ID is 1700.
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z be nse
(user
Modify the query so thatu the ise
c prompted for a location ID. Save this to a file named
C r l i
lab_08_04.sql.
l e s able
o ra sfer
o Ma reportr anfor HR that displays the last name and salary of every employee who
5. n
Create
- t
e nig reports
n onto King.
B

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

Practices for Lesson 8: Using Subqueries to Solve Queries


Chapter 8 - Page 4
Organizacion Educativa Certificatic Sฺ C

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.

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
e s the
If you have time, complete
l a l
bfollowing exercise:
8. Modify the
a e r
or querynsinflab_08_03.sql to display the employee number, last name, and
o M a
of alltremployees who earn more than the average salary, and who work in a
gnsalary -
Be n i n n with any employee whose last name contains the letter “u.” Save
o
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
Organizacion Educativa Certificatic Sฺ C

Solution 8-1: Using Subqueries to Solve Queries


1. The HR department needs a query that prompts the user for an employee’s last name. The
query then displays the last name and hire date of any employee in the same department
as the employee whose name the user supplies (excluding that employee). For example, if
the user enters Zlotkey, find all employees who work with Zlotkey (excluding Zlotkey).
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
s a
WHERE department_id = (SELECT department_id
) h a
FROM employees ฺ m x
WHERE last_name = '&&Enter_name')
ฺ c om ฺ
AND last_name <> '&Enter_name';
t u ro uide
Note: UNDEFINE and SELECT are individual queries; execute r them
u
of one nafter
t Gthe other or
press Ctrl + A + F9 to run them together.
p
@ tude
e s
2. Create a report that displays the employee number,
o rallasttname,
h i s Sand salary of all employees
who earn more than the average salary. Sort
o ฺ mthe results
s e in ascending order by salary.
SELECT employee_id, last_name, n i gn tosalaryu
employees (b
e se
FROM
WHERE salaryru
z l i c en
s C bFROM
> (SELECT
l e AVG(salary)

r a le era employees)

M
ORDER
a sf
o BYnsalary;
o
gn on-tr
n i
Be 3. Writen a query that displays the employee number and last name of all employees who work
in a department with any employee whose last name contains the letter “u.” Save your SQL
statement as lab_08_03.sql. Run your query.
SELECT employee_id, last_name
FROM employees
WHERE department_id IN (SELECT department_id
FROM employees
WHERE last_name like '%u%');

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

Practices for Lesson 8: Using Subqueries to Solve Queries


Chapter 8 - Page 6
Organizacion Educativa Certificatic Sฺ C

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
s a
FROM departments
) h a
WHERE location_id =
ฺ m x
&Enter_location);
ฺ c om ฺ
t u ro uide
5. Create a report for HR that displays the last name and salary of o u
f employee
r every t G who
p n
reports to King.
e s @ tude
SELECT last_name, salary
o r al his S
FROM employees
o ฺ m se t
WHERE manager_id = (SELECT
n i gn employee_id
t o u
z (beFROM e n s eemployees
C ru e liWHEREc last_name = 'King');

l e s abl
6. Create ao a
r forsfHR
report erthat displays the department number, last name, and job ID for every
o M inrthe
employee anExecutive department.
n - t
e nig nSELECT
on department_id, last_name, job_id
B 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
Organizacion Educativa Certificatic Sฺ C

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

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 8: Using Subqueries to Solve Queries


Chapter 8 - Page 8
Organizacion Educativa Certificatic Sฺ C
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
ฺ m x
ฺ c om ฺ
Practices for Lesson ro uUsing
9: i de
u t u
rof ent G
the Set Operators
p
Chapter 9les
@ tud
o ra this S
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 9: Using the Set Operators


Chapter 9 - Page 1
Organizacion Educativa Certificatic Sฺ C

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

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 9: Using the Set Operators


Chapter 9 - Page 2
Organizacion Educativa Certificatic Sฺ C

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
) h a
ฺ m x
2.
ฺ c om ฺ
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. t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this50 and 80. Display the
n
employee ID, job ID, and department ID o ฺm seset operators.
3. Produce a list of all the employees who work in departments
by usinguthe
e n ig to
z (b ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C

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.

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 9: Using the Set Operators


Chapter 9 - Page 4
Organizacion Educativa Certificatic Sฺ C

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
s a
FROM countries
) h a
MINUS
ฺ m x
SELECT l.country_id,c.country_name
ฺ c om ฺ
FROM locations l JOIN countries c
t u ro uide
ON (l.country_id = c.country_id) u
rof ent G
JOIN departments d p
ON d.location_id=l.location_id; l e s@ Stud
3. Produce a list of all the employees who work ino ra this50 and 80. Display the
departments
m seset operators.
byฺ using the
o
employee ID, job ID, and department ID
i n
g to u
SELECT employee_id, b n
e sedepartment_id
job_id,
FROM EMPLOYEESuz
( en
r
C ble l i c
l e s
WHERE department_id=50

o
UNIONraALL f e ra
o M
SELECT a
t r ns
employee_id, job_id, department_id
n -
e nig nFROMo n EMPLOYEES
B WHERE department_id=80;
4. Create a report that lists the detail of all employees who are sales representatives and are
currently working in the sales department.
SELECT EMPLOYEE_ID
FROM EMPLOYEES
WHERE JOB_ID='SA_REP'
INTERSECT
SELECT EMPLOYEE_ID
FROM EMPLOYEES
WHERE DEPARTMENT_ID=80;

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

Practices for Lesson 9: Using the Set Operators


Chapter 9 - Page 5
Organizacion Educativa Certificatic Sฺ C

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;

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 9: Using the Set Operators


Chapter 9 - Page 6
Organizacion Educativa Certificatic Sฺ C
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
ฺ m x
ฺ c om ฺ
Practices for Lesson 10:
ro uide
u t u
ManipulatingrData
p of nt G
e s @ tude
ral this S
Chapter 10
o
ฺm se
n o
g to u
n i
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 10: Manipulating Data


Chapter 10 - Page 1
Organizacion Educativa Certificatic Sฺ C

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.

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 10: Manipulating Data


Chapter 10 - Page 2
Organizacion Educativa Certificatic Sฺ C

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.

s a
Tasks
) h a
1. Create a table called MY_EMPLOYEE. ฺ m x
ฺ c
2. Describe the structure of the MY_EMPLOYEE table to identify the column names. om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 10: Manipulating Data


Chapter 10 - Page 3
Organizacion Educativa Certificatic Sฺ C

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

s a
4 Newman Chad cnewman 750
) h a
ฺ m x
5 Ropeburn Audrey aropebur
ฺ c om ฺ 1550

t u ro uide
u
rof entfrom G
4. Populate the MY_EMPLOYEE table with the second row of thepsample data the
s @ u d
preceding list. This time, list the columns explicitly inle
r a the INSERT
i s Stclause.
5. Confirm your addition to the table.
o ฺ mo se th
n i gn to u
z (be ense
C ru e lic
l e s abl
o r a
6. Write an INSERT
s er Theinscript
statement
f a dynamic reusable script file to load the remaining rows into

o M ran
the MY_EMPLOYEE table. should prompt for all the columns (ID, LAST_NAME,
i n
g on- t
FIRST_NAME, USERID, and SALARY). Save this script to a lab_10_06.sql file.
n n the table with the next two rows of the sample data listed in step 3 by running the
Be 7. 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
Organizacion Educativa Certificatic Sฺ C

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.

s a
) h a
15. Commit all pending changes.
ฺ m x
ฺ c om ฺ
Control the data transaction to the MY_EMPLOYEE table.
t u ro uide
16. Populate the table with the last row of the sample data listedp
u
of 3 bynusing
inrstep t G the
e s @statements
statements in the script that you created in step 6. Run the
t u dein the script.
ral this S
Note: Perform the steps (17-23) in one session only.
o
17. Confirm your addition to the table.
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be 18. Markn 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
Organizacion Educativa Certificatic Sฺ C

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.

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 10: Manipulating Data


Chapter 10 - Page 6
Organizacion Educativa Certificatic Sฺ C

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
s a
) h a
3. m x
Create an INSERT statement to add the first row of data to the MY_EMPLOYEE table from

ฺ c om ฺ
the following sample data. Do not list the columns in the INSERT clause.

t u ro uide
ID LAST_NAME FIRST_NAME USERID u
rof ent GSALARY
p
l e s@ Stud
1 Patel Ralph
o ra thrpatel
i s 895

n o ฺm se
n i g to u
2 Dancs
( b e se
Betty bdancs 860

r u z licen
3 s C ble Ben
Biri bbiri 1100
l e
ra sfer a
o
M4 raNewmann
g n o - t Chad cnewman 750

en i no n
B 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
Organizacion Educativa Certificatic Sฺ C

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.
s a
INSERT INTO my_employee
) h a
VALUES (&p_id, '&p_last_name', '&p_first_name', ฺ m x
'&p_userid', &p_salary);
ฺ c om ฺ
t u ro uide
8. Confirm your additions to the table.
u
rof ent G
p
SELECT * l e s@ Stud
FROM my_employee; o ra this
n o ฺm se
n i g to u
(be ense
9. Make the data additions permanent.
z
COMMIT;
C ru e lic
l e s abl
o r a f r
ethe
M ran
Update and delete s
data in MY_EMPLOYEE table.
n o t
- last name of employee 3 to Drexler.
e ig Change
n10. n onthe
B 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
Organizacion Educativa Certificatic Sฺ C

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;
s a
) h a
15. Commit all pending changes.
ฺ m x
COMMIT; ฺ c om ฺ
t u ro uide
u
rof ent G
Control the data transaction to the MY_EMPLOYEE table. p
l
16. Populate the table with the last row of the sample data e @ in step
slisted S t ud3 by using the
o
statements in the script that you created in step raRun tthe
6. h s
istatements in the script.
o ฺ m e
n i gn to us
INSERT INTO my_employee
VALUES (&p_id,uz
(be ense '&p_first_name',
lic
Cr b&p_salary);
'&p_last_name',
l e
s
'&p_userid',
le era
r a
o nsf
MPerform
i g n n-trathe steps (17-23) in one session only.
o
Note:

Be
n no
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
Organizacion Educativa Certificatic Sฺ C

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


h a s
COMMIT;
x )
ฺ m
If you have time, complete the following exercise: ฺ c om ฺ
t u ro uide
24. Modify the lab_10_06.sql script such that the USERID is generated
r o f u automatically
t G by

@ p dentherefore, not
concatenating the first letter of the first name and the first seven characters of the last
name. The generated USERID must be in lowercase. The
a l e s S tu
script should,

ฺ m or this
prompt for the USERID. Save this script to a file named lab_10_24.sql.
SET ECHO OFF
g n o use
SET VERIFY OFF
e i
n e to
z ( b n s
INSERT INTO my_employee
u lic e
VALUES (&p_id,
s Cr '&&p_last_name',
b l e '&&p_first_name',

r a l e r a
lower(substr('&p_first_name', 1, 1) ||
sf e
o Mosubstr('&p_last_name',
a n 1, 7)), &p_salary);

n i gn SET o n -tr
Be n VERIFY ON
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
Organizacion Educativa Certificatic Sฺ C

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ฺ

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 10: Manipulating Data


Chapter 10 - Page 11
Organizacion Educativa Certificatic Sฺ C
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Practices for Lesson 10: Manipulating Data


Chapter 10 - Page 12
Organizacion Educativa Certificatic Sฺ C
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
ฺ m x
ฺ c om ฺ
Practices for Lesson 11:
ro uide
u t u
rof ent Gto
Using DDL Statements
p
Create and s@Manage
t ud Tables
l e
ra11 this S
o
ฺm se
Chapter
n o
g to u
n i
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C

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
h a s
x )
Note: Before starting this practice, execute the ฺ m
/home/oracle/labs/sql1/code_ex/cleanup_scripts/cleanup_11.sql script.
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C

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.
s a
Tasks
) h a
1. x
Create the DEPT table based on the following table instance chart. Save the statement in
ฺ m
ฺ c om ฺ
the lab_11_01.sql script, and then execute the statement in the script to create the
table. Confirm that the table is created.
t u ro uide
Column Name ID NAMEf u
ro ent G
p
Key Type Primary key
l e s@ Stud
Nulls/Unique
o ra this
FK Table
n o ฺm se
n i g to u
FK Column
z ( be nse
Data type
C ru e lice
NUMBER VARCHAR2
Length
l e s abl 7 25
a
or nsfe r
M
i g no n-tra
Be
n 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
Organizacion Educativa Certificatic Sฺ C

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 x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
3. Modify the EMP table. Add a COMMISSION n o ฺm ofsethe NUMBER data type, with precision 2
column
n i g to u
and scale 2. Confirm your modification.
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C

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 x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
7. Drop all the UNUSED columns from the EMP table. ale
s@ Stud
8. Create the EMPLOYEES2 table based on the ฺ m or his
structureeof tthe EMPLOYEES table. Include only
i g no o SALARY,
the EMPLOYEE_ID, FIRST_NAME, LAST_NAME, us and DEPARTMENT_ID columns.
n t
DEPT_ID, respectively.uz
(betableeID,
Name the columns in your new
n e
sFIRST_NAME, LAST_NAME, SALARY, and

s Cr ble lic
r a le era
o Mo ransf
n i gn on-t
Be n

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
Organizacion Educativa Certificatic Sฺ C

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.
s a
Now, because the table is assigned a READ WRITE status, you will be allowed to add a
) h a
column to the table.
ฺ m x
You should get the following messages:
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i
12.
n
gDrop the
o n -t
EMP, DEPT, and EMPLOYEES2 table.
Be n

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
Organizacion Educativa Certificatic Sฺ C

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
) h a
ฺ m x
CREATE TABLE dept
ฺ c om ฺ
(id NUMBER(7)CONSTRAINT department_id_pk PRIMARY KEY,
t u ro uide
name VARCHAR2(25));
r u
of nt G
p
@ tudefollowing command:
To confirm that the table was created and to view its structure, issue the
e s
DESCRIBE dept;
o ral this S
n o ฺm se
g ttable
2. Create the EMP table based on the ifollowing
n o uinstance chart. Save the statement in a
script called lab_11_02.sql,
( b e se
and then execute the statement in the script to create the
n
ruz eis created.
table. Confirm that the table
C l ice
l e s IDabl
Column
o r a Name
f e r LAST_NAME FIRST_NAME DEPT_ID

o M
Key Type
t r a ns
n
e on-
nig nNulls/Unique
B 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
Organizacion Educativa Certificatic Sฺ C

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 s a
MODIFY (last_name VARCHAR2(50)); ) h a
ฺ m x
DESCRIBE emp ฺ c om ฺ
t u ro uide
u
rof ent G
p
l
5. Drop the FIRST_NAME column from the EMP table. Confirm e ud
s@yourSmodification
t by checking
r a i s
the description of the table.
o ฺ mo se th
ALTER TABLE emp
n i gn to u
(be ense
DROP COLUMN first_name;
DESCRIBE emp uz
s Cr ble lic
r a le era
Mothetable,
6. In the EMP
a n sf the DEPT_ID column as UNUSED. Confirm your modification by
mark

g o
n n-tr
checking description of the table.
n i no
Be
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
Organizacion Educativa Certificatic Sฺ C

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. s a


) h a
ฺ m x
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.
ฺ c om ฺ
ALTER TABLE employees2
t u ro uide
ADD job_id VARCHAR2(9); u
rof ent G
p
l
11. Revert the EMPLOYEES2 table to the read/write status.e s@try S
Now to t udthe same column
add
again. o ra this
m se
noฺ WRITE
Now, because the table is assigned iagREAD
o u status, you will be allowed to add a
n t
column to the table.
z (be ense
ru e lic READ WRITE;
ALTER TABLE employees2
C
l e s abl
o a
r TABLE f r
eemployees2
ALTER
M s
an VARCHAR2(9);
n o t r
ADD job_id
-
e nig nDESCRIBE
on employees2
B
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
Organizacion Educativa Certificatic Sฺ C
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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
Organizacion Educativa Certificatic Sฺ C
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
ฺ m x
ฺ c om ฺ
Additional Practices and
ro uide
u t u
Solutions
p rof ent G
l
Chapter 12 e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Additional Practices and Solutions


Chapter 12 - Page 1
Organizacion Educativa Certificatic Sฺ C

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

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Additional Practices and Solutions


Chapter 12 - Page 2
Organizacion Educativa Certificatic Sฺ C

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.

s a
2. The HR department needs a report of employees who earn a commission. Show the last
) h a
name, job, salary, and commission of these employees. Sort the data by salary in
descending order. ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
i g tneeds
3. For budgeting purposes, the HR department
n o u a report on projected raises. The report
should display those employees
( b e se
who have no commission, but who have a 10% raise in
n
ruz e lice
salary (round off the salaries).
C
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Additional Practices and Solutions


Chapter 12 - Page 3
Organizacion Educativa Certificatic Sฺ C

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 x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i glast name
t o u
5. Show those employees who have
( b e se
a starting with the letters “J,” “K,” “L,” or “M.”
n
C ruz e lice
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Additional Practices and Solutions


Chapter 12 - Page 4
Organizacion Educativa Certificatic Sฺ C

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 x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
These exercises can be
C ruusedeforlicextra practice after you have discussed the following
lesfunctions.
topics: basic SQL l
SELECTbstatements,
a
basic SQL Developer commands, SQL functions,
a
joins, andrgroup
o nsfe r
M
7. Create
i g nsalary n - tra employees
o ofa those
report that displays the department name, location ID, last name, job title, and
who work in a specific location. Prompt the user for a location.
e o
n Fornexample,
B 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
Organizacion Educativa Certificatic Sฺ C

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
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof Show
11. Create a report that displays the jobs that are found in the Administration and
t GExecutive
departments. Also display the number of employees for these pjobs.
d n
e job with the
the
s @ u
highest number of employees first.
r a le is St
o ฺ mo se th
n i gn to u
z (be ense
C ru e lic
l e s abl
o r a
These exercises s f
can eber used for extra practice after you have discussed the following
o MbasicraSQLn SELECT statements, basic SQL Developer commands, SQL functions,
ntopics:
- t
e nig joins,nogroup
n functions, and subqueries.
B 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
Organizacion Educativa Certificatic Sฺ C

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 x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
14. Show all the employees who have n i g towithua salary higher than $15,000. Show the
managers
(
following data: employee name,
z bemanager
n sename, manager salary, and salary grade of the
manager. ru e lic e
C
s abl
l e
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Additional Practices and Solutions


Chapter 12 - Page 7
Organizacion Educativa Certificatic Sฺ C

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
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
16. Create a report to display the department
n o ฺm and
number se lowest salary of the department with
i g u
en se to
the highest average salary.
( b
z licen
r
C ble u
e s
ral that
17. Create a report
o f e ra departments where no sales representatives work. Include the
displays
o M rnumber,
department
t a ns department name, manager ID, and location in the output.
n
e nig non-
B

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

Additional Practices and Solutions


Chapter 12 - Page 8
Organizacion Educativa Certificatic Sฺ C

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:

s a
) h a
ฺ m x
19. Create a report that displays the employee number, last name, salary, department number,
and the average salary in their department for all employees.
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Additional Practices and Solutions


Chapter 12 - Page 9
Organizacion Educativa Certificatic Sฺ C

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ฺ

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Additional Practices and Solutions


Chapter 12 - Page 10
Organizacion Educativa Certificatic Sฺ C

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 s a
descending order. ) h a
ฺ m x
SELECT last_name, job_id, salary, commission_pct
ฺ c om ฺ
FROM employees
t u ro uide
WHERE commission_pct IS NOT NULL u
rof ent G
ORDER BY salary DESC; p
l e s@ Stud
o raa report
t h ison projected raises. The report
3. For budgeting purposes, the HR department
ฺ m needs
se
onot get aucommission
should display those employees who do
i g n o
but who have a 10% raise in
salary (round off the salaries). n t
z (bofe '||last_name||'
e n se
SELECT 'The salary
C r u l i c after a 10% raise is '

l e s a b le
|| ROUND(salary*1.10) "New salary"
FROMra employees
o s f er
o M ran
WHERE commission_pct IS NULL;
n t
e nig non-
B 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
Organizacion Educativa Certificatic Sฺ C

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
) h a
ฺ m x
7.
ฺ c om ฺ
Create a report that displays the department name, location ID, last name, job title, and
salary of those employees who work in a specific location. Prompt the user for a location.
t u ro uide
Enter 1800 for location_id when prompted.
r u
of nt G
SELECT d.department_name, d.location_id, p de e.job_id,
@e.last_name,
e s t u
ral d this S
e.salary
FROM employees e JOIN departments o
ฺm se
ON n o
e.department_id = d.department_id u
g&location_id;
n i t o
(be ense
AND d.location_id =
z
ru e who lic have a last name that ends with the letter “n.” Create
8. Find the numbersofC l
employees
two possiblea e
lsolutions.
r a b
r sf e
o Mo raCOUNT(*)
SELECT n
n i gn FROM
o n -t employees
Be nWHERE 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
Organizacion Educativa Certificatic Sฺ C

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
s a
ORDER BY FREQUENCY DESC;
) h a
ฺ m x
ฺ c om ฺ
These exercises can be used for extra practice after you have discussed
t u rothe following
u i de
topics: basic SQL SELECT statements, basic SQL Developer commands, u
rof enSQL t Gfunctions,
joins, group functions, and subqueries. p
l e s@ Stud
o ra this
12. Show all employees who were hired in theฺfirst
o m sofethe month (before the 16th of the
half
month, irrespective of the year).
n i gn to u
SELECT last_name,(b e se
hire_date
FROM r u
employees z l i c en
WHERE e s C ble
a l r a
TO_CHAR(hire_date, 'DD') < 16;

M or nsfe
13. n
i g o a report
Create
n - t ra that displays the following for all employees: last name, salary, and salary
Be no in terms of thousands of dollars.
n 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
Organizacion Educativa Certificatic Sฺ C

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,
s a
e2.salary,
) h a
e2.job_id
ฺ m x
om ฺ
ORDER BY d.department_id, employees;
ฺ c
rodepartment
16. Create a report to display the department number and lowest salary of
u t u
the u i de with
the highest average salary.
p rof ent G
SELECT department_id, MIN(salary)
l e s@ Stud
FROM employees o ra this
GROUP BY department_id
n o ฺm se
HAVING AVG(salary) = (SELECT n i t o u
g MAX(AVG(salary))
z (be FROMe n se employees
C ru e licGROUP BY department_id);
l e s abl
o r a f r
edisplays
M ran
17. Create a report s
that the departments where no sales representatives work. Include
n o t
nig nSELECTon- *
the department number, department name, manager ID, and location in the output.
B e
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
Organizacion Educativa Certificatic Sฺ C

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
s a
GROUP BY d.department_id, d.department_name
) h a
HAVING COUNT(*) = (SELECT MAX(COUNT(*))
ฺ m x
FROM employees
ฺ c om ฺ
GROUP BY department_id);
t u ro uide
u
rof ent G
c. Has the lowest number of employees: p
l e t ud
s@ SCOUNT(*)
SELECT d.department_id, d.department_name,
o ra e this
FROM departments d JOIN employees
d.department_id i=gn
oฺm use
ON
b to
e.department_id
en sd.department_name
e
(
GROUP BY d.department_id,
z= (SELECT en MIN(COUNT(*))
HAVING COUNT(*) r u l i
C bleFROM employeesc
e s
o ral sfera GROUP BY department_id);
o M ran
n i g n
o n -t
n a report that displays the employee number, last name, salary, department number,
Be 19. 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
Organizacion Educativa Certificatic Sฺ C

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ฺ

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Additional Practices and Solutions


Chapter 12 - Page 16
Organizacion Educativa Certificatic Sฺ C

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 x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
M wantratonbuild the tables, you can execute the commands in the
Note: If you
o
n i g on-t
n
Online_Book_Store_Create_Table.sql script in SQL Developer. If you want to drop the
B n can execute the commands in the Online_Book_Store_Drop_Tables.sql
e 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
Organizacion Educativa Certificatic Sฺ C

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
s a
Column Datatype Key Table Dependent On
) h a
Book_ID VARCHAR2 PK
ฺ m x
Book_Name VARCHAR2
ฺ c om ฺ
Author_ID VARCHAR2 FK AUTHORS
t u ro uide
Price NUMBER u
rof ent G
p
s@ Stud
Publisher_ID VARCHAR2 FK PUBLISHER
c. Table Name: CUSTOMER l e
ra thTable
m o is Dependent On
Column Name Data type ฺ Key
o PK use
VARCHAR2 gn
Customer_ID
i
en se to
Customer_Name b
VARCHAR2
(
z licen
Street_Address
r u
VARCHAR2
C VARCHAR2
City
l e s a b le
Phone_Number
o ra sferVARCHAR2
o M ran VARCHAR2
Credit_Card_Number FK Credit_Card_Details
n t
e on-
nig d. nCREDIT_CARD_DETAILS
B 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
Organizacion Educativa Certificatic Sฺ C

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 s a
) h a
Column Data type Key
ฺ m x
Table Dependent On
Shopping_Cart_ID NUMBER PK
ฺ c om ฺ
Book_ID VARCHAR2 BOOKS FK
t u ro uide
Price NUMBER
u
rof ent G
Date DATE p
Quantity NUMBER
l e s@ Stud
o ra this
n o ฺm to the
2. Add additional Referential Integrity constraints setables created.
i g u
tochecking in the Connections Navigator in
( b enproperly
3. Verify that the tables were created
s e by
SQL Developer.
r u z licen
4. Create a sequence s Cto uniquely
b le identify each row in the ORDER_DETAILS table.
l e a
a 100;fdoernot allow caching of the values. Name the sequence
rwith
o
a. Start
M rans
n o
g on-t
ORDER_ID_SEQ.
n i n
Be

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

Additional Practices and Solutions


Chapter 12 - Page 19
Organizacion Educativa Certificatic Sฺ C

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ฺ

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l
5. Add data to the tables. Create a script for each set ofedata ud
s@to beSadded.
t
o ra this
Add data to the following tables:
n o ฺm se
a. AUTHOR
n i g to u
b. PUBLISHER
z (be ense
C
c. SHIPPING_TYPE
ru e lic
a les erabl
d. rCUSTOMER
a n sf
Me.o CREDIT_CARD_DETAILS
o tr
gn of. n-BOOKS
n i n
Be
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
Organizacion Educativa Certificatic Sฺ C

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.
s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f ercart detail for the book details that you just entered in 7(a).
o M ran
b. Enter a shopping

n i g on-t
n
Be n

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

Additional Practices and Solutions


Chapter 12 - Page 21
Organizacion Educativa Certificatic Sฺ C

8. Create a report that contains each customer’s history of purchasing books. Be sure to
include the customer name, customer ID, book ID, date of purchase, and shopping cart ID.
Save the commands that generate the report in a script file named lab_apcs_8.sql.
Note: Your results may be different.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Additional Practices and Solutions


Chapter 12 - Page 22
Organizacion Educativa Certificatic Sฺ C

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)
)
; s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
COMMENT ON TABLE AUTHOR IS 'Author'
u
rof ent G
;
p
l e s@ Stud
o ra this
ALTER TABLE AUTHOR
n o ฺm se
n i
ADD CONSTRAINT AUTHOR_PK g PRIMARY
t o u KEY (Author_ID);
z (be ense
b. BOOKS
C ru e lic
a l
CREATE e r bl
sTABLEaBOOKS
M or( nsfe
i g ra
no n-tBook_ID VARCHAR2 (10) NOT NULL ,

Be
n 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
Organizacion Educativa Certificatic Sฺ C

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'


;
s a
) h a
ฺ m x
ALTER TABLE CUSTOMER
ฺ c om ฺ
ADD CONSTRAINT Customer_PK PRIMARY KEY ( Customer_ID
t u ro uid) e;
u
rof ent G
p
l e s@ Stud
d. CREDIT_CARD_DETAILS o ra this
n o ฺm se
CREATE TABLE CREDIT_CARD_DETAILS
n i g to u
(be eVARCHAR2se
(

u z
Credit_Card_Number
c n (20) NOT NULL ,
r l i
C ble VARCHAR2 (10) ,
l e s
Credit_Card_Type

o r)aExpiry_Date
f e ra DATE
o M rans
n i g ;on-t
n
Be n
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
Organizacion Educativa Certificatic Sฺ C

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
s a
ADD CONSTRAINT ORDER_DETAILS_PK PRIMARY KEY (Order_ID ) ;
) h a
f. PUBLISHER ฺ m x
ฺ c om ฺ
CREATE TABLE PUBLISHER
t u ro uide
( u
r,of ent G
Publisher_ID VARCHAR2 (10) NOT NULL p
Publisher_Name VARCHAR2 (50) es@
l S t ud
) o ra this
;
n o ฺm se
n i g to u
z (be ense
C ru e lic
s TABLE
COMMENTleON a l
bPUBLISHER
r a e r IS 'Publisher'
; o
M a n sf
o
gn on-tr
n i n
Be 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
Organizacion Educativa Certificatic Sฺ C

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
s a
CREATE TABLE SHIPPING_TYPE
) h a
(
ฺ m x
Shipping_Type VARCHAR2 (10) NOT NULL ,
ฺ c om ฺ
Shipping_Price NUMBER (6)
t u ro uide
) u
rof ent G
p
s@ Stud
;
l e
a his Type'
COMMENT ON TABLE SHIPPING_TYPE o ISr 'Shipping
o ฺ m se t
;
n i gn to u
z (be ense
C ru eSHIPPING_TYPE_PK
ALTER TABLE SHIPPING_TYPE
lic
e s b l
ADD CONSTRAINT PRIMARY KEY ( Shipping_Type
) ;
o ral sfera
o M ran
n i g on-t
n
Be n

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

Additional Practices and Solutions


Chapter 12 - Page 26
Organizacion Educativa Certificatic Sฺ C

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'


;

s a
ALTER TABLE SHOPPING_CART
) h a
ADD CONSTRAINT SHOPPING_CART_PK PRIMARY KEY (SHOPPING_CART_ID) ฺ m x
;
ฺ c om ฺ
t u ro uide
u
rof Created
2. Adding Additional Referential Integrity Constraints to the Table t G
p n
e s @ tude
r l this S
a. Include a Foreign Key constraint in the BOOKSatable.
o
n o ฺm se
ALTER TABLE BOOKS
n i g to u
( e se
ADD CONSTRAINTbBOOKS_AUTHOR_FK FOREIGN KEY
z e n
(
C ru e lic
e s abl
Author_ID
l
o r)a
s f er
o M REFERENCES
r an AUTHOR
n - t
e nig non (
B 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
Organizacion Educativa Certificatic Sฺ C

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
)
;
s a
) h a
ฺ m x
ALTER TABLE ORDER_DETAILS
ฺ c om ฺ
ADD CONSTRAINT FK_Order_details FOREIGN KEY
t u ro uide
(
r u
of nt G
Shipping_Type
@ p de
e s t u
)
REFERENCES SHIPPING_TYPE mo
ral this S
n o ฺ se
(
i g to u
Shipping_Type en e
( b
z licen s
)
r u
C ble
;
e s
o ral sfera
o M ran
n i n
g ALTER
o n -t TABLE ORDER_DETAILS
Be 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
Organizacion Educativa Certificatic Sฺ C

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 s a
( ) h a
Customer_ID ฺ m x
) ฺ c om ฺ
REFERENCES CUSTOMER t u ro uide
u
rof ent G
(
p
Customer_ID
l e s@ Stud
) ;
o ra this
n o ฺm se
n i
d. Include a Foreign Key constraint in the
t o u
g SHOPPING_CART table.

z (be ense
ru e lic
ALTER TABLECSHOPPING_CART
s abl SHOPPING_CART_BOOKS_FK FOREIGN KEY
ADDleCONSTRAINT
o r( sfer
a
o M Book_ID
r an
n - t
e nig non )
B REFERENCES BOOKS
(
Book_ID
)
;

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

Additional Practices and Solutions


Chapter 12 - Page 29
Organizacion Educativa Certificatic Sฺ C

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: a
h a s
SELECT * FROM user_sequences;
x )
ฺ m
5. Add data to the tables. ฺ c om ฺ
t u ro uide
a. AUTHOR Table u
rof ent G
Author_ID Author_Name p
@ tud
l e sGoldsmith
AN0001
o ra this S
Oliver
AN0002
n o ฺm Oscar
s e Wilde
AN0003 n u
ig to George Bernard Shaw
e
(b ense Leo Tolstoy
AN0004 z
ru e lic
AN0005 s C l Percy Shelley
l e a b
o ra sfer
AN0006 Lord Byron
M n
i g no AN0007
n - tra John Keats
e n o
nAN0008 Rudyard Kipling
B
AN0009 P. G. Wodehouse

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

Additional Practices and Solutions


Chapter 12 - Page 30
Organizacion Educativa Certificatic Sฺ C

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

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
c. SHIPPING _TYPE p
l e s@ Stud
o a his
rShipping_Price
Shipping_Type
o ฺ m se t
USPS
n i gn to u200
FedEx
z (be ense 250
DHL C ru e lic 150
e s b l
o ral sfera
o M ran
n i g on-t
n
Be n

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

Additional Practices and Solutions


Chapter 12 - Page 31
Organizacion Educativa Certificatic Sฺ C

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 s a
) h a
CN0006 Urguhart Molly 3035 Laurier
Blvd. ฺ m xQuebec 418-542-9988 000-111-222-888

ฺ c om000-111-222-999
CN0007 Menchu Roberta Boulevard de
Waterloo 41 t u ro uideฺ
Brussels 322-504-2228

r o fu t G
CN0008 Biri Ben 398 High St. Columbu
s@
s u d en
p 614-455-9863 000-111-222-222

r a le is St
88 Alfredo
CN0009 Catchpole
Antoinette o ฺ th
m St. se Brisbane 616-399-1411 000-111-222-111

n i gn to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Additional Practices and Solutions


Chapter 12 - Page 32
Organizacion Educativa Certificatic Sฺ C

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 x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o
f. BOOKSr a
s f er
o M ran Book _Name
n i g on t
n Book-_ID Author _ID Price Publisher _ID

Be 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
Organizacion Educativa Certificatic Sฺ C

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
s a
) h a
BN00012 War and Peace
ฺ m x
AN0004 150 PN0002

ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n
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
Organizacion Educativa Certificatic Sฺ C

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 a
h. ORDER _DETAILS ฺ m x
Order _ID Customer Shipping_ Date _of _Purchase Shoppingฺ c om _Cart
ฺ _ID
_ID Type r o
tu Gu i d e
r o f u t
OD0001 CN0001 USPS p
12-JUN-2001
e nSC0002
OD0002 CN0002 USPS l e s@ Stud SC0005
28-JUN-2005
OD0003 CN0003
ra this
FedEx mo 31-JUL-2004 SC0007
o ฺ s e
OD0004 CN0004
n i gn to u14-AUG-2006
FedEx SC0004
CN0005 (b
e FedExse
OD0005
u z e n 21-SEP-2006 SC0003
OD0006 C r e licDHL
CN0006 28-OCT-2007 SC0001
e s b l
o ral sfCN0007
OD0007 era DHL 11-AUG-2007 SC0006

o M
OD0008ran CN0008 DHL 18-SEP-2009 SC0008
i g n n - t
en o
nOD0009 CN0009 USPS 25-NOV-2009 SC0009
B

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

Additional Practices and Solutions


Chapter 12 - Page 35
Organizacion Educativa Certificatic Sฺ C

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

s a
6. Create a view named CUSTOMER_DETAILS to show the Customer Name, Customer
) h a
ฺ m x
Address, and the details of the order placed by the customer. Order the results by Customer
ID.
ฺ c om ฺ
CREATE VIEW customer_details AS
t u ro uide
SELECT c.customer_name, c.street_address, u
rof o.order_id,
t G
p n
e s @ tude
o.customer_id, o.shipping_type, o.date_of_purchase,

ral this oS
o.shopping_cart_id
FROM o
customer c JOIN order_details
m se
c.customer_idn=oฺo.customer_id;
g to u
ON
n i
SELECT * z (be ense
FROM C ru e lic
customer_details
l
ORDERaBY e r a bl
scustomer_id;
M or nsfe
i g no n-tra
Be
n no

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

Additional Practices and Solutions


Chapter 12 - Page 36
Organizacion Educativa Certificatic Sฺ C

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 x
ฺ c om ฺ
t u ro uide
u
rof ent G
p d
l e s@
b. Enter a shopping cart detail for the bookadetails that S tujust
you entered in 7(a).
o r this
n o ฺm se
n i g to u
( b e se
INSERT INTO shopping_cart(shopping_cart_id, book_id, price,

r u z licen
Shopping_cart_date,quantity)

C ble
VALUES ('SC0010','BN0013','200',TO_DATE('12-JUN-2006','DD-MON-
s
e
YYYY'),'12');
ral sfera
M rano
n o
8. Create
gincludeoathe-tcustomer
report that contains each customer’s history of purchasing books. Be sure to
n i n name, customer ID, book ID, date of purchase, and shopping cart ID.
Be Saventhe 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
Organizacion Educativa Certificatic Sฺ C
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2014, Oracle and/or its affiliatesฺ

s a
) h a
ฺ m x
ฺ c om ฺ
t u ro uide
u
rof ent G
p
l e s@ Stud
o ra this
n o ฺm se
n i g to u
z (be ense
C ru e lic
l e s abl
o r a
s f er
o M ran
n i g on-t
n
Be n

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

Additional Practices and Solutions


Chapter 12 - Page 38

You might also like