You are on page 1of 144

NIIT LTD

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

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
AR le lic
AN feOracle Database 12c R2: SQL
K
H rab
S
NI -trans Workshop I
V A
BHA non

Activity Guide
D80190GC20
Edition 2.0 | November 2016 | D98631

Learn more from Oracle University at education.oracle.com


NIIT LTD

Copyright © 2016, 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© 2012, 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
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective ) h a
owners.
ฺ c om
Author
a h oo eฺ
Apoorva Srinivas @ y u id
b m nt G
Technical Contributors and Reviewers s r
(r tude
T S Bhujani
Nancy Greenberg, Suresh Rajan, Peckkwai Yap, BryanERoberts,sSharath
H
S et h i
H
A to us
T
This book was published using: oracletutor
N
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n
NIIT LTD

Table of Contents
Course Practice Environment: Security Credentials ............................................................................... I-1
Course Practice Environment: Security Credentials.................................................................................. I-2
Practices for Lesson 1: Introduction ........................................................................................................ 1-1
Practices for Lesson 1: Overview............................................................................................................. 1-2
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

Practice 1-1: Introduction......................................................................................................................... 1-3


Solution 1-1: Introduction......................................................................................................................... 1-5
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
s a
Practices for Lesson 4: Using Single-Row Functions to Customize Output ........................................... 4-1 ) h a
ฺ c om
Practices for Lesson 4: Overview............................................................................................................. 4-2

a h oo eฺ
Practice 4-1: Using Single-Row Functions to Customize Output................................................................ 4-3
y
Solution 4-1: Using Single-Row Functions to Customize Output................................................................ 4-8
@ u id
Practices for Lesson 5: Using Conversion Functions and Conditional Expressions
b m nt G
............................. 5-1

(rs tuder
Practices for Lesson 5: Overview............................................................................................................. 5-2
Practice 5-1: Using Conversion Functions and Conditional Expressions T S
E ....................................................
.................................................... 5-3
Solution 5-1: Using Conversion Functions and Conditional Expressions
S H t h i s 5-8
Practices for Lesson 6: Reporting Aggregated Data H theuGroup
TUsing se Functions................................... 6-1
A
N e to
Practices for Lesson 6: Overview............................................................................................................. 6-2
A M by Using s
RData byicUsing en Group Functions......................................................... 6-6
Practice 6-1: Reporting Aggregated Data Group Functions......................................................... 6-3
R l
KA bData
Solution 6-1: Reporting Aggregated
Practices for Lesson N
a
7: Displaying le from Multiple Tables Using Joins ............................................ 7-1
A
H 7: Overviewf er ............................................................................................................. 7-2
S
Practices for Lesson
I s
V AN7-1:
Practice
- tran Data
Displaying
7-1:nDisplaying
from Multiple Tables by Using Joins............................................................ 7-3

HA no
Solution Data from Multiple Tables by Using Joins............................................................ 7-8
B Practices for Lesson 8: Using Subqueries to Solve Queries ................................................................... 8-1
Practices for Lesson 8: Overview............................................................................................................. 8-2
Practice 8-1: Using Subqueries to Solve Queries ..................................................................................... 8-3
Solution 8-1: Using Subqueries to Solve Queries ..................................................................................... 8-6
Practices for Lesson 9: Using the Set Operators ..................................................................................... 9-1
Practices for Lesson 9: Overview............................................................................................................. 9-2
Practice 9-1: Using Set Operators ........................................................................................................... 9-3
Solution 9-1: Using Set Operators ........................................................................................................... 9-5
Practices for Lesson 10: Managing Tables Using DML Statements ........................................................ 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

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

Oracle Database 12c R2: SQL Workshop I Table of Contents


iii
NIIT LTD

Practices for Lesson 11: Introduction to Data Definition Language ........................................................ 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
Practices for Lesson 1: Overview............................................................................................................. 12-2
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

Practice 1-1: Additional Practice .............................................................................................................. 12-3


Solution 1-1: Additional Practice .............................................................................................................. 12-11
Case Study: Online Book Store ............................................................................................................... 12-16
Practice 1-2 ............................................................................................................................................ 12-17
Solution 1-2 ............................................................................................................................................ 12-22

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Oracle Database 12c R2: SQL Workshop I Table of Contents


iv
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
o
Course Practice yaho ideฺ
Environment: m @ t Gu
Security
b
rsr tuden
Credentials
T (
H E i s S
H S use t
Chapter I h
T
A to
N
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Course Practice Environment: Security Credentials


Chapter I - Page 1
NIIT LTD

Course Practice Environment: Security Credentials

For OS usernames and passwords, see the following:


• If you are attending a classroom-based or live virtual class, ask your instructor or LVC
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

producer for OS credential information.


• If you are using a self-study format, refer to the communication that you received from
Oracle University for this course.

For connection-specific credentials used in this course, see the following table:

Connection-Specific Credentials
Connection_Name Username Password
myconnection ora1 ora1 s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Course Practice Environment: Security Credentials


Chapter I - Page 2
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
Practices for Lesson a h oo eฺ
1:
y id
Introduction m@ t Gu
( r s rb den
Chapter 1 T
E S tu
S H this
A TH use
A MN se to
R R icen
K A le l
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 1
NIIT LTD

Practices for Lesson 1: Overview

Practice Overview
In this practice, you start Oracle 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© 2012, 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.

Note
• All written practices use Oracle SQL Developer as the development environment.
Although it is recommended that you use Oracle SQL Developer, you can also use
SQL*Plus that is available in this course.
s a
• For any query, the sequence of rows retrieved from the database may differ from the
) h a
screenshots shown.
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 2
NIIT LTD

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 the practices for each lesson. The practices are intended to cover most of the
topics that are presented in the corresponding lesson.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, 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 above location.

Tasks
s a
1. Start Oracle SQL Developer by Using the SQL Developer Desktop Icon
) h a
2. Create a New Oracle SQL Developer Database Connection
ฺ c om
a h oo eฺ
a. To create a new database connection, in the Connections Navigator, right-click
y id
Connections and select New Connection from the context menu. The New / Select
@ u
Database Connection dialog box appears.
b m nt G
s r
(r tude
b. Create a database connection by using the following information:
Connection Name: myconnection T
E is S
Username: ora1
H
S e th
H us Course Practice Environment:
T from the
Password: Enter the password
Security CredentialsMdocument N A t o
Hostname: localhost R A ense
Port: 1521 KA
R
l e lic
N PDBORCL
AName: r a b
H
Service
IS thatayou f e
sselect
N
Ensure
A thenOracle n
tr SQL Developer
the Save Password check box.
V -
BHA no
3. Test
a. Test the new connection.
Database Connection and Connect to the Database

b. If the status is Success, connect to the database by using this new connection.
4. Browse 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

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 3
NIIT LTD

b. Browse the structure of the EMPLOYEES table.


c. View the data of the DEPARTMENTS table.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 4
NIIT LTD

Solution 1-1: Introduction


1. Start Oracle SQL Developer by Using the SQL Developer Desktop Icon
Double-click the SQL Developer desktop icon.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

The SQL Developer interface appears.

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
AN
2. Create a New r a
Oracle SQL bDeveloper Database Connection
a. To
H e
sf database connection, in the Connections Navigator, right-click
IScreateaannew
N -tr and select New Connection from the context menu.
A VA Connections
o n
BH n

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 5
NIIT LTD

The New / Select Database Connection dialog box appears.


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

s a
) h a
ฺ c om
b. Create a database connection by using the following information: ho
o ฺ
i. Connection Name: myconnection @ y a
u ide
ii. Username: ora1 r b m nt G
(rs from u e
dthe
iii. T
Password: Enter the password
S t
E isCredentials Course
Practice Environment: H Security document
S t h
iv. TH use
Hostname: localhost
A
v.Port: 1521
M N e to
vi. R A
Service n
Name:
e sPDBORCL
Ensure that
K l e licthe Save Password check box.
ARyou select
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 6
NIIT LTD

3. Test the Oracle SQL Developer Database Connection and Connect to the Database
a. Test the new connection.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
a h oo eฺ
@ u id
b. If the status is Success, connect to the database by using this newyconnection.
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 7
NIIT LTD

When you create a connection, a SQL Worksheet for that connection opens automatically.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
4. Browse the Tables in the Connections Navigator s r
(r tude
a. In the Connections Navigator, view the objects
T S to you in the Tables
Ethat areisavailable
node. Verify that the following tables are S
H
present: t h
T H u se
COUNTRIES A
N e to
DEPARTMENTS
A M s
EMPLOYEES R
e n
AR le lic
JOB_GRADES
K
H AN ferab
JOB_HISTORY
JOBS
N IS LOCATIONS
a ns
V A t r
-REGIONS
BHA non

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 8
NIIT LTD

b. Browse the structure of the EMPLOYEES table.


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

c. View the data of the DEPARTMENTS table.

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 9
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 10
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
Practices for Lesson a h oo eฺ
2:
@ y u id
Retrieving Data Using
m nt Gthe
r b
SQL SELECT
T
s
(r Statement
t u de
H E2 i s S
H S use t
Chapter h
T
A to
N
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 1
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

• Describing the structure of tables


• Performing arithmetic calculations and specifying column names

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 2
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

Task 1
Test your knowledge:
1. The following SELECT statement executes successfully:
SELECT last_name, job_id, salary AS Sal
FROM employees;

True/False
2. The following SELECT statement executes successfully:
s a
SELECT *
FROM job_grades; ) h a
ฺ c om
True/False
a h oo eฺ
@
3. There are four coding errors in the following statement. Can you identifyythem? uid
r b m nt G
(rs tude
SELECT employee_id, last_name
sal x 12 ANNUAL SALARY T
E is S
FROM employees; H
S e th
H
Task 2 N AT to us
R AMbegin
Note the following points before you
e n sethe practices:
with

K AR files
• Save all your practice
l e licthe following location:
at
AN ferab
/home/oracle/labs/sql1/labs
H
N IS your
• Enter
a s statements in a SQL Worksheet. To open a new worksheet, click File
SQL
n
V A n-tr New. A New Gallery dialog window appears. Click Database Files under
menu, select

BHA nDatabase

o Tier on the left pane. Select SQL File on the right pane and click OK.
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 Run 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 data from the Human Resources tables.

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

Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 3
NIIT LTD

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

s a
) h a
ฺ c om
5.
a h oo eฺ
Your next task is to determine the structure of the EMPLOYEES table and its contents.
a. Determine the structure of the EMPLOYEES table.
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 4
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

in the same worksheet. Open a new worksheet.

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 5
NIIT LTD

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

s a
Task 3 ) h a
If you have time, complete the following exercises: ฺ c om
h oo eฺ
7. The HR department wants more descriptive column headings for its report on employees.
a
y u id
Copy the statement from lab_02_5b.sql to a new SQL Worksheet. Name the columns
@
b m nt G
Emp #, Employee, Job, and Hire Date, respectively. Then run the query again.
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 6
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
If you want an extra challenge, complete the following exercise:
a h oo eฺ
9. To familiarize yourself with the data in the EMPLOYEES table, create a query
@ u id all
y to display
the data from that table. Separate each column output by a comma.
b m Name n G
tthe column
THE_OUTPUT. s r
(r tud e
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A V…A on-tr
BH n

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

Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 7
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

SELECT last_name, job_id, salary AS Sal


FROM employees;

True/False
2. The following SELECT statement executes successfully:
SELECT *
FROM job_grades;

True/False
s a
3. There are four coding errors in the following statement. Can you identify them?
) h a
SELECT employee_id, last_name
ฺ c om
sal x 12 ANNUAL SALARY
a h oo eฺ
FROM employees;
@ y u id
• m nt G
The EMPLOYEES table does not contain a column called sal. The column is called
b
SALARY. s r
(r tude
• The multiplication operator is *, not x as shown T
E in iline S2.
• The ANNUAL SALARY alias cannot include
H
S spaces. h s
t The alias should read
ANNUAL_SALARY or should be A T H s e
u double quotation marks.
enclosed within
N t o
• A comma is missing after
R AMtheeLAST_NAME
n se column.

Task 2 K AR le lic
AN asfaeSQL
You have been hired
H rabprogrammer for Acme Corporation. Your first task is to create
IS based
some reports
N a nons data from the Human Resources tables.
A t r
4. VYour first -task is to determine the structure of the DEPARTMENTS table and its contents.
BHA non a. To determine the DEPARTMENTS table structure:
DESCRIBE departments
b. To view the data contained in the DEPARTMENTS table:
SELECT *
FROM departments;

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

Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 8
NIIT LTD

5. Your next 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© 2012, Oracle and/or its affiliatesฺ

STARTDATE for the HIRE_DATE column. Save your SQL statement to a file named
lab_02_5b.sql so that you can dispatch this file to the HR department. Test your
query in the lab_02_5b.sql file to ensure that it runs correctly.
SELECT employee_id, last_name, job_id, hire_date StartDate
FROM employees;
6. The HR department wants a query to display all unique job IDs from the EMPLOYEES table.
SELECT DISTINCT job_id
FROM employees;

s a
) h a
Task 3
ฺ c om
If you have time, complete the following exercises:
a h oo eฺ
y id
7. The HR department wants more descriptive column headings for its report on employees.
@ u
b m nt G
Copy the statement from lab_02_5b.sql to a new SQL Worksheet. Name the columns
s r
r tude
Emp #, Employee, Job, and Hire Date, respectively. Then run the query again.
("Employee",
T S
HE Date"
SELECT employee_id "Emp #", last_name
job_id "Job", hire_dateS"Hire h i s
T H use t
FROM employees;
N A to
R
last name concatenated with
AtheMjobeaIDnreport
8. The HR department has requested e of all employees and their job IDs. Display the
s(separated by a comma and space) and name the
column Employee A RTitle.lic
NK rable '||job_id "Employee and Title"
and
SELECTAlast_name||',
I S n s fe
H employees;
AN n-tra
FROM
V
BHA no
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.
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;

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

Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 9
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 2: Retrieving Data Using the SQL SELECT Statement
Chapter 2 - Page 10
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
Practices for Lesson a h oo eฺ
3:
@ y u id
Restricting and Sorting
m nt G Data
r b
r tude
s
Chapter 3 T (
H E is S
H S e th
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 1
NIIT LTD

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© 2012, 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
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 2
NIIT LTD

Practice 3-1: Restricting and Sorting Data

Overview
In this practice, you build reports by using statements with the WHERE clause and the ORDER BY
clause. You make the SQL statements more reusable and generic by including the ampersand
substitution.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

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
ฺ c om
a h oo eฺ
2. Open a new SQL Worksheet. Create a report that displays the last name
@ u id
y and department
number for employee number 176.
b m nt G
r
(r tude
s
T
E is S
H
S e th
H andslow-salaried employees. Modify
T and salary
3. The HR department needs to find high-salaried
u for any employee whose salary is not
lab_03_01.sql to display the lastN A
name t o
in the range $5,000 through A M Save
$12,000. se your SQL statement as lab_03_03.sql.
R e n
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 3
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

5. Display the last name and department ID of all employees in department 20 or department
50 in ascending alphabetical order by last_name.

s a
) h a
6. Modify lab_03_03.sql to display the last name and salary of employees who earn
between $5,000 and $12,000, and are in department 20 or department 50. Label theฺ c om
columns Employee and Monthly Salary, respectively. Save lab_03_03.sql as
a h oo eฺ
lab_03_06.sql. Run the statement in lab_03_06.sql.
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
7. The HR department needs a report thatT H S utheselastthname and hire date of all
displays
employees who were hired in 2010. N A to
R AM ense
K AR le lic
H AN ferab
N ISa report
8. Create a ntosdisplay the last name and job title of all employees who do not have a
A
Vmanager.- t r
BHA non
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.

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

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 4
NIIT LTD

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:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

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:
s a
manager_id = 103, sorted by last_name: ) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
manager_id = 201, sorted by salary: T
H E is S
H S e th
N AT to us
byA
M se
manager_id = 124, sortedR
R l i c en
employee_id:

N KA ble
H A fera
S
NI -trans
V A
BHA non
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.”

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

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

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 5
NIIT LTD

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


14. Display the last name, job, and salary for all employees whose jobs are either that of a
sales representative or a stock clerk, and whose salaries are not equal to $2,500, $3,500,
or $7,000.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

15. Modify lab_03_06.sql to display the last name, salary, and commission for all
employees whose commission is 20%. Save lab_03_06.sql as lab_03_15.sql. Rerun
the statement in lab_03_15.sql.

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 6
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

named lab_03_01.sql. Run your query.


SELECT last_name, salary
FROM employees
WHERE salary > 12000;
2. Open a new SQL Worksheet. Create a report that displays the last name and department
number for employee number 176.
SELECT last_name, department_id
FROM employees
WHERE employee_id = 176;
s a
3. The HR department needs to find high-salaried and low-salaried employees. Modify
) h a
ฺ c om
lab_03_01.sql to display the last name and salary for all employees whose salary is not

a h oo eฺ
in the range $5,000 through $12,000. Save your SQL statement as lab_03_03.sql.
SELECT last_name, salary
@ y u id
FROM employees
b m nt G
WHERE salary NOT BETWEEN 5000 AND 12000; s r
(r tude
T
Ehire date
4. Create a report to display the last name, job ID, and S employees with the last
for
names of Matos and Taylor. Order the query S
H h i s
t order by hire date.
in ascending
T H u s e
SELECT last_name, job_id,
N A hire_date
t o
FROM employeesAM s e
WHERE R e n
R INlic('Matos', 'Taylor')
last_name
A
NK rable
ORDER BY hire_date;
A
5. DisplaySthe
s feand department ID of all employees in department 20 or department
H last name
in Iascending
50 N n
V A n-tra alphabetical order by last_name.

BHA nSELECTo
FROM
last_name, department_id
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 department 50. Label the columns
Employee and Monthly Salary, respectively. Save lab_03_03.sql as
lab_03_06.sql. 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 © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 7
NIIT LTD

7. The HR department needs a report that displays the last name and hire date of all
employees who were hired in 2010.
SELECT last_name, hire_date
FROM employees
WHERE hire_date >= '01-JAN-10' AND hire_date < '01-JAN-11';
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, 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
ฺ c om
ORDER BY 2 DESC, 3 DESC;
h o ฺ
othat
10. Members of the HR department want to have more flexibility with the queries
writing. They would like a report that displays the last name and salary@
a
yof employees
u dewho
iyou are

b m(You can
n t G
earn more than an amount that the user specifies after a prompt.r de
rs lab_03_10.sql.
created in Task 1 and modify it.) Save this query to a file(named
use the query
T t u
H E is S
SELECT last_name, salary
H S e th
AT to us
FROM employees
WHERE salary > &sal_amt; N
Enter 12000 when prompted R AforMa value
e n sine a dialog box. Click OK.
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n
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
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;

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

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 8
NIIT LTD

If you have the time, complete the following exercises:


12. Display the last names of all employees where the third letter of the name is “a.”
SELECT last_name
FROM employees
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

WHERE last_name LIKE '__a%';


13. Display the last names of all employees who have both an “a” and an “e” in their last name.
SELECT last_name
FROM employees
WHERE last_name LIKE '%a%'
AND last_name LIKE '%e%';
If you want an extra challenge, complete the following exercises:
14. Display the last name, job, and salary for all employees whose job is that of a sales
representative or a stock clerk, and whose salary is not equal to $2,500, $3,500, or $7,000.
s a
SELECT last_name, job_id, salary
) h a
FROM employees
ฺ c om
oo eฺ
WHERE job_id IN ('SA_REP', 'ST_CLERK')
AND salary NOT IN (2500, 3500, 7000); a h
y for alluid
@
15. Modify lab_03_06.sql to display the last name, salary, and commission
m as t G
r b n
(rs tude
employees whose commission amount is 20%. Save lab_03_06.sql
T
lab_03_15.sql. Rerun the statement in lab_03_15.sql.
SELECT last_name "Employee",Ssalary h is S Salary",
HE t"Monthly
commission_pct TH se
A to u
FROM employees
A MN = s.20; e
WHERE
R icen
commission_pct
R
K A le l
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 9
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 3: Restricting and Sorting Data


Chapter 3 - Page 10
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
Practices for Lesson a h ooUsing
4: eฺ
y
@ t Gtou i d
Single-Row Functions
m
b
r den
rsOutput
Customize ( tu
E T S
S H 4 this
Chapter

A TH use
A MN se to
R R icen
K A le l
H AN ferab
N IS ans
A VA on-tr
BH n

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

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


Chapter 4 - Page 1
NIIT LTD

Practices for Lesson 4: Overview

Practice Overview
This practice covers the following topics:
• Writing a query that displays the system date
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, 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
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

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


Chapter 4 - Page 2
NIIT LTD

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

Overview
In this practice, you use 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© 2012, 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
3. Run your query in the lab_04_02.sql file.
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

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


Chapter 4 - Page 3
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
5. Perform the following tasks: AM se
R e n
a. Write a query that R
K A displays
l e licthe
the last name (with the first letter in uppercase and all the
other letters
nameH
in b “A,” or “M.”
lowercase)
ANwithfetheraletters
starts
and length of the last name for all employees whose
Give each column an appropriate label. Sort the
I S s
AN n-tran
results by the employees’ last names.
V
BHA no

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

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

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


Chapter 4 - Page 4
NIIT LTD

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

If you have time, complete the following exercises:


s a
6. The HR department wants to find the duration of employment for each employee. For each
) h a
ฺ c om
employee, display the last name and calculate the number of months between today and the
date on which the employee was hired. Label the column as MONTHS_WORKED. Order your
h oo eฺ
results by the number of months employed. The number of months must be rounded to the
a
closest whole number.
@ y u id
b m nt G
Note: Because this query depends on the date when it was executed, the values in the
s r
(r tude
MONTHS_WORKED column will differ for you.
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

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


Chapter 4 - Page 5
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

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


Chapter 4 - Page 6
NIIT LTD

8. 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 SALARIES_IN_ASTERISK.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H us of weeks employed for all
9. Create a query to display the last name
N ATand the
t o number
employees in department 90. Label
A M the number
s e of weeks column as TENURE. Truncate the
number of weeks value to R n
0 decimaleplaces. Show the records in descending order of the
employee’s tenure. AR
K l e lic
AN fvalue
Note: The TENURE
H e r abwill differ because it depends on the date on which you run the
query.IS
A N -trans
V
BHA non

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

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


Chapter 4 - Page 7
NIIT LTD

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© 2012, 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;
3. Run your query in the file lab_04_02.sql.
s a
SELECT employee_id, last_name, salary,
) h a
ROUND(salary * 1.155, 0) "New Salary"
ฺ c om
FROM employees;
h o ฺ
osalary
4. Modify your query in lab_04_02.sql to add a column that subtracts theaold
y i d efrom
the new salary. Label the column Increase. Save the contents of @ the file as u
b m n t G
lab_04_04.sql. Run the revised query. r
(rs tude
SELECT employee_id, last_name, salary, T
E Salary", S
ROUND(salary * 1.155, 0)H"New
h i s
ROUND(salary * 1.155,
T HS e
0) - salary
s
t "Increase"
FROM employees; N A to u
5. Perform the following tasks: A
M se
R R
l i c elastn name (with the first letter in uppercase and all the
a. Write a query that
K A le and the length of the last name for all employees whose
displays the
N
other letters b
in lowercase)
A withfethe raletters
name
I S H starts
s “A,” or “M.” Give each column an appropriate label. Sort the
ANresults t n employees’ last names.
byathe
r
V -
on INITCAP(last_name) "Name",
BHA nSELECT LENGTH(last_name) "Length"
FROM employees
WHERE last_name LIKE 'M%'
OR last_name LIKE 'A%'
ORDER BY last_name;

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

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


Chapter 4 - Page 8
NIIT LTD

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© 2012, 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
ฺ c om
If you have time, complete the following exercises:
a h oo eฺ
6. The HR department wants to find the duration of employment for each employee.
@ y u d each
iFor
employee, display the last name and calculate the number of months
b G
between today
m nt Order your and the
r de be rounded to the
(ofrsmonthstumust
date on which the employee was hired. Label the column MONTHS_WORKED.
results by the number of months employed. The number T
E is S
closest whole number.
S H h
Note: Because this query depends on theH date wheneit twas executed, the values in the
MONTHS_WORKED column will differ N for
T
Ayou. t o us
SELECT last_name, A M se
SYSDATE, R R
l i
hire_date)) en MONTHS_WORKED
ROUND(MONTHS_BETWEEN(
c
FROM
N KA ble
employees
H
ORDER
f ra
ABY months_worked;
e
S
NI a query nsdisplay the last name and salary for all employees. Format the salary to
7. Create
A t r ato
V n- long, left-padded with the $ symbol. Label the column SALARY.
HA be 15nocharacters
B SELECT last_name,
LPAD(salary, 15, '$') SALARY
FROM employees;
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 SALARIES_IN_ASTERISK.
SELECT last_name,
rpad(' ', (salary/1000)+1, '*')
SALARIES_IN_ASTERISK
FROM employees
ORDER BY salary DESC;

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

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


Chapter 4 - Page 9
NIIT LTD

9. Create a query to display the last name and the number of weeks employed for all
employees in department 90. Label the number of weeks column as TENURE. Truncate the
number of weeks value to 0 decimal places. Show the records in descending order of the
employee’s tenure.
Note: The TENURE value will differ because it depends on the date when you run the query.
SELECT last_name, trunc((SYSDATE-hire_date)/7) AS TENURE
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

FROM employees
WHERE department_id = 90
ORDER BY TENURE DESC;

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

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


Chapter 4 - Page 10
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
Practices for Lesson a h ooUsing
5: eฺ
y
@ t Gand u i d
Conversion Functions m
b en
rsrExpressions
Conditional ( u d
H E T
i s St
S 5 e th
Chapter
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 1
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

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

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 2
NIIT LTD

Practice 5-1: Using Conversion Functions and Conditional


Expressions

Overview
In this practice, you use the TO_CHAR and TO_DATE functions, and conditional expressions
such as CASE, searched CASE, and DECODE.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, 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
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 3
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T S amounts. If an
Eand commission
H
3. Create a query that displays employees’ last names
h i s
T H S uCommission.”
employee does not earn commission, show “No
s et Label the column COMM.

N A to
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 4
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

IT_PROG C
SA_REP D
ST_CLERK E
None of the above 0

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 5
NIIT LTD

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

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 6
NIIT LTD

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

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 7
NIIT LTD

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

the column Dream Salaries.


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'),
ฺ c om
FROM
'fmDay, "the" Ddspth "of" Month, YYYY') REVIEW
employees;
a h oo eฺ
@ y id
Ifuan
3. Create a query that displays employees’ last names and commission
employee does not earn commission, show “No Commission.”rb
G
amounts.
m the ncolumn
Label t COMM.
s
(r tud e
SELECT last_name, T S
E 'No iCommission')
NVL(TO_CHAR(commission_pct),
S H t h s COMM
FROM employees;
A TH use
MNthe 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,A using n s
following data:
R c e
Job
K AR le liGrade
AD_PRES
A N rab A
ST_MANI S H
n s fe B
N
A n-tr a
A VIT_PROG
o
C

BH n
SA_REP D
ST_CLERK E
None of the above 0

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

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 8
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

WHEN 'AD_PRES' THEN 'A'


ELSE '0' END GRADE
FROM employees;
5. Rewrite the statement in the preceding exercise by using the searched CASE syntax.
SELECT job_id, CASE
WHEN job_id = 'ST_CLERK' THEN 'E'
WHEN job_id = 'SA_REP' THEN 'D'
WHEN job_id = 'IT_PROG' THEN 'C'
WHEN job_id = 'ST_MAN' THEN 'B'
s a
WHEN job_id = 'AD_PRES' THEN 'A'
) h a
ELSE '0' END GRADE
ฺ c om
FROM employees;
a h oo eฺ
y
6. Rewrite the statement in the preceding exercise by using the DECODE syntax.
@ u id
b m nt G
SELECT job_id, decode (job_id,
s r
(r tude
'ST_CLERK', 'E',
T
E is S
'SA_REP', H
S e th
'D',
'IT_PROG',H 'C',
N
'ST_MAN',AT to'B',us
M se 'A',
A'AD_PRES',
R R
l i c en
N KA ble '0')GRADE
A fera
FROM employees;
H
S
NI -trans
V A
BHA non

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

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 9
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 5: Using Conversion Functions and Conditional Expressions


Chapter 5 - Page 10
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
Practices for Lesson a h oo eฺ
6:
@ y u id
Reporting Aggregated m nt G Data
s r b e
Using the(rGroup t u dFunctions
E6 T S
H h i s
H S use t
Chapter
T
A to
N
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 1
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

• Grouping by rows to achieve multiple results


• Restricting groups by using the HAVING clause

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 2
NIIT LTD

Practice 6-1: Reporting Aggregated Data by Using Group Functions

Overview
In this practice, you use group functions and select groups of data.

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

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
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.
ฺ c om
a h oo eฺ
@ y u id
m nsum,
5. Modify the query in lab_06_04.sql to display the minimum,bmaximum, G
t and average
s r e
(r tud Run the statement in
salary for each job type. Save lab_06_04.sql as lab_06_05.sql.
lab_06_05.sql. T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 3
NIIT LTD

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

s a
Generalize the query so that a user in the HR department is prompted for a job title.
) h a
Save the script to a file named lab_06_06.sql. Run the query. Enter IT_PROG when
prompted. ฺ c om
a h oo eฺ
@ y u id
b G
m ntNumber of
s
7. Determine the number of managers without listing them. Label r
(r tude the column
Managers. T
E the number S
H
S et
Hint: Use the MANAGER_ID column to determine h i s of managers.
H
N AT to us
R AM ense
8. Find the difference A
between c and lowest salaries. Label the column
R thelihighest
DIFFERENCE.NK l e
H A ferab
N IS ans
A VA on-tr
BH nIf 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 © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 4
NIIT LTD

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 2009, 2010, 2011, and 2012. Create appropriate column headings.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

11. Create a matrix query to display the job, the salary for that job based on the department
numbers 20, 50, 80, and 90, and the total salary for that job. Ensure to give each column an
appropriate heading.

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 5
NIIT LTD

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
2. Group functions include nulls in calculations.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

True/False
3. The WHERE clause restricts rows before inclusion in a group calculation.
True/False
The HR department needs the following reports:
4. Find the highest, lowest, sum, and average salary of all employees. Label the columns
Maximum, Minimum, Sum, and Average, respectively. Round your results to the nearest
whole number. Save your SQL statement as lab_06_04.sql. Run the query.
SELECT ROUND(MAX(salary),0) "Maximum",
ROUND(MIN(salary),0) "Minimum",
ROUND(SUM(salary),0) "Sum",
s a
ROUND(AVG(salary),0) "Average"
) h a
FROM employees;
ฺ c om
oand average
ahtheo statement
5. Modify the query in lab_06_04.sql to display the minimum, maximum, sum,
salary for each job type. Save lab_06_04.sql as lab_06_05.sql. y Run i d eฺ in
lab_06_05.sql.
m @ t Gu
r b
sr uden
SELECT job_id, ROUND(MAX(salary),0) "Maximum", (
ROUND(MIN(salary),0) T
H E "Minimum",
i s St
ROUND(SUM(salary),0)
H th
S e"Average"
"Sum",

AT to us
ROUND(AVG(salary),0)
FROM employees
GROUP BY job_id; AM
N
R e n se
6. Write a query to display
K e lic of people with the same job.
ARthe lnumber
N raCOUNT(*)
SELECTAjob_id, b
IS BY
FROM H sf e
employees
N a n
A o n -tr
VA Generalize
GROUP job_id;

BH n the query so that a 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.
SELECT job_id, COUNT(*)
FROM employees
WHERE job_id = '&job_title'
GROUP BY job_id;
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;

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

Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 6
NIIT LTD

8. Find the difference between the highest and lowest salaries. Label the column
DIFFERENCE.
SELECT MAX(salary) - MIN(salary) DIFFERENCE
FROM employees;

If you have time, complete the following exercises:


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

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.
SELECT manager_id, MIN(salary)
FROM employees
WHERE manager_id IS NOT NULL
GROUP BY manager_id
HAVING MIN(salary) > 6000
ORDER BY MIN(salary) DESC;
s a
) h a
If you want an extra challenge, complete the following exercises:
ฺ c om
a h oo eฺ
10. Create a query that displays the total number of employees and, of that total, the number of
employees hired in 2009, 2010, 2011, and 2012. Create appropriate column headings.
@ y u id
SELECT COUNT(*) total,
b m nt G
s r
r tude
SUM(DECODE(TO_CHAR(hire_date, 'YYYY'),2009,1,0))"2009",
('YYYY'),2010,1,0))"2010",
SUM(DECODE(TO_CHAR(hire_date, T S
E 'YYYY'),2011,1,0))"2011",
H h i s
H S use t'YYYY'),2012,1,0))"2012"
SUM(DECODE(TO_CHAR(hire_date,
T
A to
SUM(DECODE(TO_CHAR(hire_date,
employees; MN
A ense
FROM
R c job, the salary for that job based on the department
AR
11. Create a matrix query
K e
to display
l lithe
N 80, and
numbers 20,A50,
r a b and the total salary for that job. Ensure to give each column an
90,
H
IS heading.
appropriate sf e
N a n
A VA SELECT
o n -tr job_id "Job",

BH n SUM(DECODE(department_id , 20, salary)) "Dept 20",


SUM(DECODE(department_id , 50, salary)) "Dept 50",
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;

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

Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 7
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 6: Reporting Aggregated Data Using the Group Functions
Chapter 6 - Page 8
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
Practices for Lesson a h oo eฺ
7:
@ y u id
Displaying Data m ntfrom Multiple
G
r b
Tables Using
T
s
(r Joins t u de
H E7 i s S
H S use t
Chapter h
T
A to
N
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 1
NIIT LTD

Practices for Lesson 7: Overview

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

• Performing outer and self-joins


• Adding conditions

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 2
NIIT LTD

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

Overview
In this practice, you extract data from multiple tables using SQL:1999–compliant joins.

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

1. Write a query for the HR department to produce the addresses of all the departments. Use
the LOCATIONS and COUNTRIES tables. Show the location ID, street address, city, state or
province, and country in the output. Use a NATURAL JOIN to produce the results.

2. The HR department needs a report of all employees with corresponding departments. Write
s a
a query to display the last name, department number, and department name for these
) h a
employees.
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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.

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

Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 3
NIIT LTD

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

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 4
NIIT LTD

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

s a
) h a
ฺ c om
a h oo eฺ
@
6. Create a report for the HR department that displays employee last names, u id
y department
b G
m as a ngiven
t employee.
s r
numbers, and all the employees who work in the same department
(ra file namede
Give each column an appropriate label. Save the script to
T S t ud lab_07_06.sql.
S HE this
A TH use
A MN se to
R R icen
K A le l

H AN ferab
N IS ans
A VA on-tr
BH n
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.

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

Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 5
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
If you want an extra challenge, complete the followingTexercises:
H i s S who were hired after
Eof all employees
8. The HR department wants to determine the names
Hand h
S hireedatet of any employee hired after
A to us
Davies. Create a query to display the name
T
employee Davies. N
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 6
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 7
NIIT LTD

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.
SELECT location_id, street_address, city, state_province,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

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 these
employees.
SELECT last_name, department_id, department_name
FROM employees
JOIN departments
s a
USING (department_id);
) h a
3.
ฺ c
department number, and department name for all employees who work in Toronto.om
The HR department needs a report of employees in Toronto. Display the last name, job,

a h oo eฺ
SELECT e.last_name, e.job_id, e.department_id, d.department_name
@ y u id
FROM employees e JOIN departments d
b m nt G
ON (e.department_id = d.department_id) s r
(r tude
JOIN locations l T
E is S
USING (location_id) H
S e th
H
WHERE LOWER(l.city) = 'toronto';
N AT to us
AM enumbers.
4. Create a report to display employees’
managers’ last names andRmanager n
lastenames and employee numbers along with their
s Label the columns Employee, Emp#,
Manager, and Mgr#,
K AR licSave your SQL statement as lab_07_04.sql. Run the
respectively.
l e
query.
H AN ferab
N IS aw.last_name
SELECT
n s "Employee", w.employee_id "EMP#",

A VA on-tr m.last_name "Manager", m.employee_id "Mgr#"


BH nFROM 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 © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 8
NIIT LTD

6. Create a report for the HR department that displays employee last names, department
numbers, and all employees who work in the same department as a given employee. Give
each column an appropriate label. Save the script to a file named lab_07_06.sql. Run
the query.
SELECT e.department_id department, e.last_name employee,
c.last_name colleague
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

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
SELECT e.last_name, e.job_id, d.department_name, ) h a
e.salary, j.grade_level
ฺ c om
FROM employees e JOIN departments d
a h oo eฺ
ON (e.department_id = d.department_id)
@ y u id
b m nt G
JOIN
ON
job_grades j
r
(r tude
s
(e.salary BETWEEN j.lowest_sal AND j.highest_sal);
T
E exercises: S
H
If you want an extra challenge, complete the following
h i s
S ofeallt employees who were hired after
8. The HR department wants to determine the
T Hnames uhires date of any employee hired after
Davies. Create a query to display NtheA o
name and
t
employee Davies.
R AM ense
R
SELECT e.last_name,
A e l ic
e.hire_date
FROM K
N rab
employees l
e JOIN employees davies
A fe
ON H (davies.last_name
I S n s = 'Davies')

V ANWHEREn - tradavies.hire_date < e.hire_date;


BHA
9. ThenHRo 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 MANAGER,
m.hire_date "Manager_hire_date"
FROM employees w JOIN employees m
ON (w.manager_id = m.employee_id)
WHERE w.hire_date < m.hire_date;

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

Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 9
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 7: Displaying Data from Multiple Tables Using Joins
Chapter 7 - Page 10
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
Practices for Lesson a h ooUsing
8: eฺ
y
@ tQueriesu i d
Subqueries tom Solve G
b
rsr tuden
Chapter 8 T (
H E is S
H S e th
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 8: Using Subqueries to Solve Queries


Chapter 8 - Page 1
NIIT LTD

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© 2012, 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
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 8: Using Subqueries to Solve Queries


Chapter 8 - Page 2
NIIT LTD

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
produces the data that you anticipate before you code the outer query.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

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
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H uslast name, and salary of all employees
N ATSortnumber,
2. Create a report that displays the employee
who earn more than the average salary. t o
the results in ascending order by salary.
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 8: Using Subqueries to Solve Queries


Chapter 8 - Page 3
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

4. The HR department needs a report that displays the last name, department number, and
job ID of all employees whose department location ID is 1700.
s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T S
Modify the query so that the user is promptedS HaElocation
for t h i s
ID. Save this to a file named
H e
usand salary of every employee who
lab_08_04.sql.
N
5. Create a report for HR that displays
ATlast tname
the o
reports to King. R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n
6. Create a report for HR that displays the department number, last name, and job ID for every
employee in the Executive department.

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

Practices for Lesson 8: Using Subqueries to Solve Queries


Chapter 8 - Page 4
NIIT LTD

7. Create a report that displays a list of all employees whose salary is more than the salary of
any employee from department 60.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
a h oo eฺ
If you have time, complete the following exercise: @ y u id
b m last n G
t name, and
8. Modify the query in lab_08_03.sql to display the employee
s r
r and number,
e
salary of all employees who earn more than the average(salary,
T S t udwho work in a
E the
department with any employee whose last nameHcontains is letterin “u.” Save
lab_08_03.sql as lab_08_08.sql again.SRun the statement
t h
TH use
lab_08_08.sql.
A
A MN se to
R R icen
K A le l
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 8: Using Subqueries to Solve Queries


Chapter 8 - Page 5
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

--Execute the UNDEFINE command to remove a variable

UNDEFINE 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
FROM employees ) h a
WHERE last_name = '&&name') ฺ c om
AND last_name <> '&name';
a h oo eฺ
Note: UNDEFINE and SELECT are individual queries; execute them@
y u
one after the
d or
iother
b m nt G
press Ctrl + A + F9 to run them together.
s r
r and
(name, de of all employees
T
2. Create a report that displays the employee number, last t usalary
S order by salary.
E in iascending
who earn more than the average salary. Sort theHresults s
H Ssalary e t h
SELECT employee_id, last_name,
T
A to u s
FROM employees N
WHERE salary > (SELECT
R AM en se
AVG(salary)

K AR FROM l e lic employees)


ANsalary;
ORDER BY
r a b
3. Write IaS
H
query that f e
sdisplays the employee number and last name of all employees who work
A
in N t r
a departmenta n
A Vstatement
o n -as lab_08_03.sql. Runwhose
with any employee
your
last name contains the letter “u.” Save your SQL
query.
BH n
SELECT employee_id, last_name
FROM employees
WHERE department_id IN (SELECT department_id
FROM employees
WHERE last_name like '%u%');
4. The HR department needs a report that displays the last name, department number, and
job ID of all employees whose department location ID is 1700.
SELECT last_name, department_id, job_id
FROM employees
WHERE department_id IN (SELECT department_id
FROM departments
WHERE location_id = 1700);

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

Practices for Lesson 8: Using Subqueries to Solve Queries


Chapter 8 - Page 6
NIIT LTD

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

WHERE department_id IN (SELECT department_id


FROM departments
WHERE location_id =
&location);
5. Create a report for HR that displays the last name and salary of every employee who
reports to King.
SELECT last_name, salary
FROM employees
WHERE manager_id = (SELECT employee_id
s a
FROM employees
) h a
WHERE last_name = 'King');
ฺ c om
6.
employee in the Executive department. a h oo eฺ
Create a report for HR that displays the department number, last name, and job ID for every

@ y u id
SELECT department_id, last_name, job_id
b m nt G
FROM employees s r
(r tude
WHERE department_id IN (SELECT department_id T
E is S
FROM SH th
departments
T H us e
N AWHERE t o
department_name =

Aa M e
'Executive');
R
7. Create a report that displays list ofe n
all
semployees whose salary is more than the salary of
any employee fromA R
department l i
60.c
NK rabFROM
SELECTAlast_name
le employees
I S H salary
n s fe> ANY (SELECT salary
AN n-tra
WHERE
V
HA no
FROM employees
B WHERE department_id=60);

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

Practices for Lesson 8: Using Subqueries to Solve Queries


Chapter 8 - Page 7
NIIT LTD

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.
SELECT employee_id, last_name, salary
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

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
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 8: Using Subqueries to Solve Queries


Chapter 8 - Page 8
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
Practices for Lesson a h ooUsing
9: eฺ
y
@ t Gu i d
the Set Operators m
b
rsr tuden
Chapter 9 T (
H E is S
H S e th
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 9: Using the Set Operators


Chapter 9 - Page 1
NIIT LTD

Practices for Lesson 9: Overview

Practice Overview
In this practice, you create reports by using the following set operators:
• UNION
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

• INTERSECT
• MINUS

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 9: Using the Set Operators


Chapter 9 - Page 2
NIIT LTD

Practice 9-1: Using Set Operators

Overview
In this practice, you write queries by using the set operators UNION, INTERSECT, and MINUS.

Tasks
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, 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
2. ฺ c om
The HR department needs a list of countries that have no departments located in them.
h oo eฺ
Display the country IDs and the names of the countries. Use the set operators to create this
a
report.
@ y u id
b m nt G
r
(r tude
s
T
E is50Sand 80. Display the
in H
3. Produce a list of all the employees who work S
employee ID, job ID, and department ID byH using thee thoperators.
departments
set
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

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

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

Practices for Lesson 9: Using the Set Operators


Chapter 9 - Page 3
NIIT LTD

Write a compound query to accomplish this report.


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

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 9: Using the Set Operators


Chapter 9 - Page 4
NIIT LTD

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
FROM departments
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

MINUS
SELECT department_id
FROM employees
WHERE job_id = 'ST_CLERK';
2. The HR department needs a list of countries that have no departments located in them.
Display the country IDs and the names of the countries. Use the set operators to create this
report.
SELECT country_id,country_name
FROM countries
s a
MINUS
) h a
SELECT l.country_id,c.country_name
ฺ c om
FROM locations l JOIN countries c
a h oo eฺ
ON (l.country_id = c.country_id)
@ y u id
JOIN departments d
b m nt G
ON d.location_id=l.location_id; s r
(r tude
T
E is50Sand 80. Display the
3. Produce a list of all the employees who work in departments
employee ID, job ID, and department ID by using H
S esetthoperators.
the
H us
SELECT employee_id, job_id,
N AT department_id
t o
FROM EMPLOYEES
R AM ense
UNION ALL KA
R
WHERE department_id=50
l e lic
N rab job_id, department_id
Aemployee_id,
I S H
SELECT
n s fe
V ANWHERE
FROM
n - a
trdepartment_id=80;
EMPLOYEES

BHA no
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 © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using the Set Operators


Chapter 9 - Page 5
NIIT LTD

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
Write a compound query to accomplish this report.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

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
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 9: Using the Set Operators


Chapter 9 - Page 6
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
Practices for Lesson a h oo eฺ
10:
@ y u id
Managing Tables Using
m nt G DML
r b
Statements
T (r tude
s
H E10 is S
S e th
Chapter
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 10: Managing Tables Using DML Statements


Chapter 10 - Page 1
NIIT LTD

Practices for Lesson 10: Overview

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

• Updating and deleting rows in a table


• Controlling transactions

Note: Before starting this practice, execute the


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

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 10: Managing Tables Using DML Statements


Chapter 10 - Page 2
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

Note
• For all DML statements, use the Run Script icon (or press F5) to execute the query.
You can 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 the cleanup_10.sql script from /home/oracle/labs/sql1/code_ex
/cleanup_scripts/ before performing the following tasks.

s a
) h a
Tasks
ฺ c om
1.
h oo eฺ
Run the lab_10_01.sql script from /home/oracle/labs/sql1/labs/ to create the
MY_EMPLOYEE table. Describe the structure of the MY_EMPLOYEE table to identify the
a
column names. @ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 10: Managing Tables Using DML Statements


Chapter 10 - Page 3
NIIT LTD

2. 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© 2012, Oracle and/or its affiliatesฺ

1 Patel Ralph rpatel 895

2 Dancs Betty bdancs 860

3 Biri Ben bbiri 1100

4 Newman Chad cnewman 750 s a


) h a
5 Ropeburn Audrey aropebur ฺ c om 1550
a h oo eฺ
@ y u id
3. Populate the MY_EMPLOYEE table with the second row of the sample b G
m datantfrom the
s r
r tclause.
preceding list. This time, list the columns explicitly in the(INSERT de
T u
4. Confirm your addition to the table.
H E is S
H S e th
N AT to us
R AM ense
5. Write an INSERT statement
c
AR lein alidynamic reusable script file to load the next two rows of
N K b
sample dataA
H f e ra USERID,table.
into the MY_EMPLOYEE The script should prompt for all the columns (ID,
I S
LAST_NAME,
N n s
FIRST_NAME, and SALARY). Save this script to a lab_10_06.sql
A n-tr
file.
VPopulate a
H A
6. no the table with the next two rows of the sample data listed in step 3 by running the
B INSERT statement in the script that you created.
7. Confirm your additions to the table.

8. Make the data additions permanent.

Update and delete data in the MY_EMPLOYEE table.


9. Change the last name of employee 3 to Drexler.
10. Change the salary to $1,000 for all employees who have a salary less than $900.

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

Practices for Lesson 10: Managing Tables Using DML Statements


Chapter 10 - Page 4
NIIT LTD

11. Verify your changes to the table.


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

12. Delete Betty Dancs from the MY_EMPLOYEE table.


13. Confirm your changes to the table.

14. Commit all pending changes.


s a
Control the data transaction to the MY_EMPLOYEE table. ) h a
ฺ c om
15. Populate the table with the last row of the sample data listed in step 3 by using the
h oo eฺ
statements in the script that you created in step 6. Run the statements in the script.
a
Note: Perform the steps (17-23) in one session only.
@ y u id
b m nt G
16. Confirm your addition to the table. r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
AN fepoint
17. Mark an intermediate
H rabin the processing of the transaction.
18. DeleteIS ns from the MY_EMPLOYEE table.
all the rows
A N t r a
- the table is empty.
19.VConfirm that
BHA non
20. Discard the most recent DELETE operation without discarding the earlier INSERT operation.
21. Confirm that the new row is still intact.

22. Make the data addition permanent.


If you have time, complete the following exercise:
23. 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.

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

Practices for Lesson 10: Managing Tables Using DML Statements


Chapter 10 - Page 5
NIIT LTD

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

ID LAST_NAME FIRST_NAME USERID SALARY

6 Anthony Mark manthony 1230


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

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

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 10: Managing Tables Using DML Statements


Chapter 10 - Page 6
NIIT LTD

Solution 10-1: Managing Tables by Using DML Statements


Insert data into the MY_EMPLOYEE table.
1. Run the lab_10_01.sql script from /home/oracle/labs/sql1/labs/ to create the
MY_EMPLOYEE table. Describe the structure of the MY_EMPLOYEE table to identify the
column names.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

DESCRIBE my_employee
2. 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

1 Patel Ralph rpatel 895

s a
2 Dancs Betty bdancs 860 ) h a
ฺ c om
h o ฺ
o1100
a ide
3 Biri Ben bbiri
@ y u
r b m nt G
4 Newman Chad rs tude 750
(cnewman
T
E is S
H
S e tharopebur
5 Ropeburn Audrey
T H u s 1550
A
A MN se to
R
INSERT INTO my_employee R icen
K A 'Patel',l e l 'Ralph', 'rpatel', 895);
N rab
VALUES (1,
3. PopulateHtheAMY_EMPLOYEE
fe table with the second row of the sample data from the
I S n s
V AN n-tra
preceding list. This time, list the columns explicitly in the INSERT clause.

BHA nINSERT
o INTO my_employee (id, last_name, first_name,
userid, salary)
VALUES (2, 'Dancs', 'Betty', 'bdancs', 860);
4. Confirm your additions to the table.
SELECT *
FROM my_employee;
5. Write an INSERT statement in a dynamic reusable script file to load the next two rows of
sample data into the MY_EMPLOYEE table. The script should prompt for all the columns (ID,
LAST_NAME, FIRST_NAME, USERID, and SALARY). Save this script to a file named
lab_10_06.sql.
INSERT INTO my_employee
VALUES (&id, '&last_name', '&first_name',
'&userid', &salary);

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

Practices for Lesson 10: Managing Tables Using DML Statements


Chapter 10 - Page 7
NIIT LTD

6. Populate the table with the next two rows of the sample data listed in step 3 by running the
INSERT statement in the script that you created.
INSERT INTO my_employee
VALUES (&id, '&last_name', '&first_name',
'&userid', &salary);
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

7. Confirm your additions to the table.


SELECT *
FROM my_employee;
8. Make the data additions permanent.
COMMIT;

Update and delete data in the MY_EMPLOYEE table.


9. Change the last name of employee 3 to Drexler.
s a
UPDATE my_employee
) h a
om
SET last_name = 'Drexler'
ฺ c
oo eฺ
WHERE id = 3;
a
10. Change the salary to $1,000 for all employees with a salary less than $900.h
@ y u id
UPDATE my_employee
b m nt G
SET salary = 1000
( r
r tude
s
WHERE salary < 900; T
E is S
11. Verify your changes to the table.
H
S e th
H
SELECT *
N AT to us
FROM my_employee;
R AM ense
12. Delete Betty DancsA
K
from
l e lic
R the MY_EMPLOYEE table.
DELETEAN
r a b
H sf
IS my_employeee
N FROM
a n
A VA WHEREo n -trlast_name = 'Dancs';
BH 13. Confirm
n your changes to the table.
SELECT *
FROM my_employee;
14. Commit all pending changes.
COMMIT;
Control the data transaction to the MY_EMPLOYEE table.
15. Populate the table with the last row of the sample data listed in step 3 by using the
statements in the script that you created in step 6. Run the statements in the script.
INSERT INTO my_employee
VALUES (&id, '&last_name', '&first_name',
'&userid', &salary);
Note: Perform the steps (17-23) in one session only.

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

Practices for Lesson 10: Managing Tables Using DML Statements


Chapter 10 - Page 8
NIIT LTD

16. Confirm your addition to the table.


SELECT *
FROM my_employee;
17. Mark an intermediate point in the processing of the transaction.
SAVEPOINT step_17;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

18. Delete all the rows from the MY_EMPLOYEE table.


DELETE
FROM my_employee;
19. Confirm that the table is empty.
SELECT *
FROM my_employee;
20. Discard the most recent DELETE operation without discarding the earlier INSERT operation.
ROLLBACK TO step_17;
s a
21. Confirm that the new row is still intact.
) h a
SELECT *
ฺ c om
FROM my_employee;
a h oo eฺ
22. Make the data addition permanent. @ y u id
b m nt G
COMMIT;
s r
(r tude
If you have time, complete the following exercise: T S
theH
E isisgenerated
23. Modify the lab_10_06.sql script such that S USERID
H anduthe e h automatically by
t seven characters
concatenating the first letter of the first T
A name s first of the last
name. The generated USERID must
M N e to
be in lowercase. The script should, therefore, not
prompt for the USERID. SaveAthis scriptsto a file named lab_10_24.sql.
R R licen
INSERT INTOAmy_employee
a b le
NK '&&last_name',
H A
VALUES (&id,
e r '&&first_name',

N a sf
ISlower(substr('&first_name',
n 1, 1) ||

A -tr
VA onsubstr('&last_name', 1, 7)), &salary);

BH n
UNDEFINE first_name
UNDEFINE last_name
24. Run the lab_10_24.sql script to insert the following record:

ID LAST_NAME FIRST_NAME USERID SALARY

6 Anthony Mark manthony 1230


25. Confirm that the new row was added with the correct USERID.
SELECT *
FROM my_employee
WHERE ID='6';

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

Practices for Lesson 10: Managing Tables Using DML Statements


Chapter 10 - Page 9
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 10: Managing Tables Using DML Statements


Chapter 10 - Page 10
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
Practices for Lesson a h oo eฺ
11:
@ y u id
Introduction to Data
m nt G
r b
T
s
Definition(rLanguage
t u de
H E11 is S
S e th
Chapter
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 11: Introduction to Data Definition Language


Chapter 11 - Page 1
NIIT LTD

Practices for Lesson 11: Overview

Lesson Overview
This practice covers the following topics:
• Creating new tables
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, 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

Note: Before starting this practice, execute the s a


/home/oracle/labs/sql1/code_ex/cleanup_scripts/cleanup_11.sql script. ) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 11: Introduction to Data Definition Language


Chapter 11 - Page 2
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

Notes
• For all 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. ฺ c om
Create the DEPT table based on the following table instance chart. Save the statement in
h oo eฺ
the lab_11_01.sql script, and then execute the statement in the script to create the
a
table. Confirm that the table is created.
@ y u id
b m nt G
Column Name ID
( r
r tude
s NAME
Key Type Primary key T
E is S
Nulls/Unique
H
S e th
H
FK Table N AT to us
FK Column R AM ense
Data type K AR leNUMBERlic VARCHAR2
LengthHA
N b
ra 7
I S s f e 25

V AN n-tran
BHA no

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

Practices for Lesson 11: Introduction to Data Definition Language


Chapter 11 - Page 3
NIIT LTD

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


Key Type
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

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

s a
) h a
ฺ c om
a h oo eฺ
3. Modify the EMP table. Add a COMMISSION column of the NUMBER data @ type, id 2
y withuprecision
and scale 2. Confirm your modification. b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A n-EMP
4. VModifyothe
tr table to allow for longer employee last names. Confirm your modification.
H A n
B

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

Practices for Lesson 11: Introduction to Data Definition Language


Chapter 11 - Page 4
NIIT LTD

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© 2012, 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
ฺ c om
a h oo eฺ
@ y u id
b m nt G
7. Drop all of the UNUSED columns from the EMP table. s r
(r tude
T S
E of theisEMPLOYEES
8. Create the EMPLOYEES2 table based on the structure table. Include only
the EMPLOYEE_ID, FIRST_NAME, LAST_NAME, S H h
SALARY,t and DEPARTMENT_ID columns.
H use LAST_NAME, SALARY, and
TFIRST_NAME,
DEPT_ID, respectively. ConfirmM
A
Name the columns in your new table ID,
tois created.
Nthe table
that
A s e
R R icen
K A le l
H AN ferab
N IS ans
A VA on-tr
BH n
9. Alter the status of the EMPLOYEES2 table to READ ONLY.
10. Try to delete all rows in the EMPLOYEES2 table.
Note: You will get the “Update operation not allowed on table” error message. You will not
be allowed to delete data from the table because it is assigned a READ ONLY status.

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

Practices for Lesson 11: Introduction to Data Definition Language


Chapter 11 - Page 5
NIIT LTD

11. Revert the EMPLOYEES2 table to the READ WRITE status. Now try to truncate the rows
again.
Now, because the table is assigned a READ WRITE status, you will be allowed to truncate
rows in the table.
You should get the following messages:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

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

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 11: Introduction to Data Definition Language


Chapter 11 - Page 6
NIIT LTD

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 ID NAME


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

Key Type Primary key


Nulls/Unique
FK Table
FK Column
Data type NUMBER VARCHAR2
Length 7 25

s a
) h a
om
CREATE TABLE dept
ฺ c
oo eฺ
(id NUMBER(7)CONSTRAINT department_id_pk PRIMARY KEY,
name VARCHAR2(25)); a h
To confirm that the table was created and to view its structure, issue@
y u id
b m nt G
the following command:
DESCRIBE dept; s r
(r tude
E T S Save the statement in a
H
2. Create the EMP table based on the following table instanceh i s
chart.
script called lab_11_02.sql, and then T H S uthe
execute s
t
estatement in the script to create the
A
MN se to
table. Confirm that the table is created.
A
R icen
Column Name A R
ID l LAST_NAME FIRST_NAME DEPT_ID
K l e
Key Type
H AN ferab
N IS ans
Nulls/Unique
A VA FK o n -tr
Table DEPT
BH n
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 © 2016, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Introduction to Data Definition Language


Chapter 11 - Page 7
NIIT LTD

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.
ALTER TABLE emp
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

ADD commission NUMBER(2,2);

DESCRIBE emp
4. Modify the EMP table to allow for longer employee last names. Confirm your modification.
ALTER TABLE emp
MODIFY last_name VARCHAR2(50);

DESCRIBE emp
5. Drop the FIRST_NAME column from the EMP table. Confirm your modification by checking s a
the description of the table. ) h a
ALTER TABLE emp ฺ c om
DROP COLUMN first_name;
a h oo eฺ
DESCRIBE emp @ y u id
b n t G
myour modification
( s r
6. In the EMP table, mark the DEPT_ID column as UNUSED. Confirm
r tud e by
checking the description of the table.
H ET is S
H S e th
ALTER TABLE emp
N AT to us
AM ense
SET UNUSED (dept_id);
R
DESCRIBEAemp
K
R
l e lic
N rcolumns
AUNUSED
7. Drop all of the a b from the EMP table.
H
ISALTER e
sf emp
N a nTABLE
A VA on-trDROP UNUSED COLUMNS;
BH n
8. Create the EMPLOYEES2 table based on the structure of the EMPLOYEES table. Include only
the EMPLOYEE_ID, FIRST_NAME, LAST_NAME, SALARY, and DEPARTMENT_ID columns.
Name the columns in your new table ID, FIRST_NAME, LAST_NAME, SALARY, and
DEPT_ID, respectively. Confirm that the table is created.
CREATE TABLE employees2 AS
SELECT employee_id id, first_name, last_name, salary,
department_id dept_id
FROM employees;
DESCRIBE employees2
9. Alter the EMPLOYEES2 table status to READ ONLY.
ALTER TABLE employees2 READ ONLY;

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

Practices for Lesson 11: Introduction to Data Definition Language


Chapter 11 - Page 8
NIIT LTD

10. Try to delete all rows in the EMPLOYEES2 table.


Note: You will get the “Update operation not allowed on table” error message. You will not
be allowed to delete data from the table because it is assigned a READ ONLY status.
TRUNCATE TABLE employees2;
11. Revert the EMPLOYEES2 table to the READ WRITE status. Now try to truncate the rows
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

again.
Now, because the table is assigned a READ WRITE status, you will be allowed to truncate
rows in the table.
ALTER TABLE employees2 READ WRITE;

TRUNCATE TABLE employees2;


SELECT * from employees2;
12. Drop the EMP, DEPT, and EMPLOYEES2 table.
Note: You can even drop a table that is in the READ ONLY status. To test this, alter the table
s a
again to READ ONLY status, and then issue the DROP TABLE command. The tables will be
) h a
dropped.
ฺ c om
DROP TABLE emp;
a h oo eฺ
DROP TABLE dept;
@ y u id
DROP TABLE employees2;
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 11: Introduction to Data Definition Language


Chapter 11 - Page 9
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Practices for Lesson 11: Introduction to Data Definition Language


Chapter 11 - Page 10
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
Additional Practices a h oo eฺ
and
@ y u id
Solutions m nt G
r b
r tude
s
Chapter 12T (
H E is S
H S e th
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Additional Practices and Solutions


Chapter 12 - Page 1
NIIT LTD

Practices for Lesson 1: Overview

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© 2012, Oracle and/or its affiliatesฺ

• Basic SQL Developer commands


• SQL functions

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Additional Practices and Solutions


Chapter 12 - Page 2
NIIT LTD

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

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

2. The HR department needs a report of employees who earn a commission. Show the last
name, job, salary, and commission of these employees. Sort the data by salary in
descending order.
s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
s r de raises. The report
(r on projected
3. For budgeting purposes, the HR department needs aT
report t u
H E isbutSwho have a 10% raise in
should display those employees who have no commission,
salary (round off the salaries). H S e th
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Additional Practices and Solutions


Chapter 12 - Page 3
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
s r de“K,” “L,” or “M.”
(r the letters
T t u
H E is S
5. Show those employees who have a last name starting with

H S e th
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Additional Practices and Solutions


Chapter 12 - Page 4
NIIT LTD

6. Create a report that displays all employees, and indicate whether they receive a
commission by using the words Yes or No. Use the DECODE expression in your query.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
These exercises can be used R AforMextra
e n se after you have discussed the following
practice
topics: basic SQL SELECT
K l e lic basic SQL Developer commands, SQL functions,
AR statements,
rab the department name, location ID, last name, job title, and
joins, and group functions.
7. Create a H ANthatfedisplays
report
N
salaryISof those a s
nemployees who work in a specific location. Prompt the user for a location.
V A - t r
HA non
For example, if the user enters 1800, results are as follows:
B

8. Find the number of employees who have a last name that ends with the letter “n.” Create
two possible solutions.

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

Additional Practices and Solutions


Chapter 12 - Page 5
NIIT LTD

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© 2012, 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
ฺ c om
a h oo eฺ
11. Create a report that displays the jobs that are found in the Administration
@ u d
y and Executive
iwith
departments. Also display the number of employees for these jobs.
b m nt
Show G
the job the
highest number of employees first. r
(rs tude
T
E is S
H
S e th
H
N AT to us
R AM ense
K AbeR
l e licextra practice after you have discussed the following
These exercises can
N SELECT
ASQL r a bstatements, basic SQL Developer commands, SQL functions,
used for
H
topics: basic e
sf and subqueries.
S functions,
Igroup
joins,
N a n
A -tremployees who were hired in the first half of the month (before the 16th of the
12.VShow allnthe
A o
BH month, n irrespective of the year).

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

Additional Practices and Solutions


Chapter 12 - Page 6
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
AT towithuassalary higher than $15,000. Show the
14. Show all the employees who have managers
N
following data: employee name,M
manager. R A manager
e n sename, manager salary, and salary grade of the
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Additional Practices and Solutions


Chapter 12 - Page 7
NIIT LTD

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

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H th salary of the department with
S ande lowest
16. Create a report to display the department number
H
the highest average salary.
N AT to us
R AM ense
R
KAdisplays l e lic
17. Create a reportNthat
A r a b departments where no sales representatives work. Include the
department
I S H sfe
number, department name, manager ID, and location in the output.

V AN n-tran
BHA no

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

Additional Practices and Solutions


Chapter 12 - Page 8
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

b. Has the highest number of employees:

c. Has the lowest number of employees:

s a
19. Create a report that displays the employee number, last name, salary, department number,
) h a
and the average salary in their department for all employees.
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Additional Practices and Solutions


Chapter 12 - Page 9
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Additional Practices and Solutions


Chapter 12 - Page 10
NIIT LTD

Solution 1-1: Additional Practice

Overview
Solutions to Additional Practice 1-1 are given as follows.

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

1. The HR department needs to find data for all the clerks who were hired after 2010.
SELECT *
FROM employees
WHERE job_id = 'ST_CLERK'
AND hire_date > '31-DEC-2010';
2. The HR department needs a report of employees who earn a commission. Show the last
name, job, salary, and commission of these employees. Sort the data by salary in
descending order.
SELECT last_name, job_id, salary, commission_pct s a
FROM employees ) h a
WHERE commission_pct IS NOT NULL ฺ c om
ORDER BY salary DESC;
a h oo eฺ
3. For budgeting purposes, the HR department needs a report on projected @ id report
y raises.uThe
should display those employees who do not get a commission b mwho have
but n G
t a 10% raise in
salary (round off the salaries). s
(r tudr e
T
E after Sa 10% raise is '
SELECT 'The salary of '||last_name||' H h i s
|| ROUND(salary*1.10)
T H S "New s e t
salary"
FROM employees N A to u
WHERE commission_pct
R AM ISenNULL;se
R and
KA with
4. Create a report of employees
l e licthe duration of their employment. Show the last names of
all employees,N
A together
r a b number of years and the number of completed months that
the
they haveH
I S e Order the report by the duration of their employment. The
fbeen
been employed.
s
ANSELECT
employee who
t r a n
has employed the longest should appear at the top of the list.
V -
BHA non last_name, TRUNC(MONTHS_BETWEEN(SYSDATE, hire_date) / 12) YEARS,
TRUNC(MOD(MONTHS_BETWEEN(SYSDATE, hire_date), 12))
MONTHS
FROM employees
ORDER BY years DESC, MONTHS desc;
5. Show those employees who have a last name that starts with the letters “K,” “L,” or “M.”
SELECT last_name
FROM employees
WHERE SUBSTR(last_name, 1,1) IN ('K', 'L', 'M');

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

Additional Practices and Solutions


Chapter 12 - Page 11
NIIT LTD

6. Create a report that displays all employees, and indicate whether they receive a
commission by using the words Yes or No. Use the DECODE expression in your query.
SELECT last_name, salary,
decode(commission_pct, NULL, 'No', 'Yes') commission
FROM employees;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

These exercises can be used for extra practice after you have discussed the following
topics: basic SQL SELECT statement, basic SQL Developer commands, SQL functions,
joins, and group functions.
7. Create a report that displays the department name, location ID, last name, job title, and
salary of those employees who work in a specific location. Prompt the user for a location.
Enter 1800 for location_id when prompted.
SELECT d.department_name, d.location_id, e.last_name, e.job_id,
e.salary
FROM employees e JOIN departments d s a
ON e.department_id = d.department_id ) h a
AND d.location_id = &location_id;
ฺ c om
o Create
o“n.”
y a h
8. Find the number of employees who have a last name that ends with the letter
i d eฺ
two possible solutions.
m @ t Gu
SELECT COUNT(*) b
rsr tuden
(
ET is S
FROM employees
WHERE last_name LIKE '%n'; H
S e th
H
AT to us
--or
SELECT COUNT(*)
M se N
employees A
FROM
R R
l i c en-1) = 'n';
A le
WHERE SUBSTR(last_name,
K
A N
9. Create a report a
that shows
r bthe name, location, and number of employees for each
H
IS Make
department. e
f that the report also includes department_IDs without employees.
ssure
N a n
A VA SELECT
o n -tr d.department_id, d.department_name,
BH n d.location_id, COUNT(e.employee_id)
FROM employees e RIGHT OUTER JOIN departments d
ON e.department_id = d.department_id
GROUP BY d.department_id, d.department_name, d.location_id;
10. The HR department needs to find the job titles in departments 10 and 20. Create a report to
display the job IDs for these departments.
SELECT DISTINCT job_id
FROM employees
WHERE department_id IN (10, 20);

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

Additional Practices and Solutions


Chapter 12 - Page 12
NIIT LTD

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

WHERE d.department_name IN ('Administration', 'Executive')


GROUP BY e.job_id
ORDER BY FREQUENCY DESC;

These exercises can be used for extra practice after you have discussed the following
topics: basic SQL SELECT statements, basic SQL Developer commands, SQL functions,
joins, group functions, and subqueries.
12. Show all employees who were hired in the first half of the month (before the 16th of the
s a
month, irrespective of the year).
) h a
SELECT last_name, hire_date
ฺ c om
FROM employees
a h oo eฺ
WHERE TO_CHAR(hire_date, 'DD') < 16;
@ y u id
13. Create a report that displays the following for all employees: lastm
b G
t and salary
name, salary,
n
expressed in terms of thousands of dollars. s r
(r tud e
T
E i-3)/1000 S
SELECT last_name, salary, TRUNC(salary,
H h s Thousands
FROM employees;
T H S use t
14. Show all employees who have managers
N A withtoa salary higher than $15,000. Show the
manager. R AMmanager
following data: employee name,
e n sename, manager salary, and salary grade of the
ic
AR le lm.last_name
K
N rab
SELECT e.last_name, manager, m.salary,
A fe e JOIN employees m
H employees
j.grade_level
I S n s
ANON n-trae.manager_id = m.employee_id
FROM
V
BHA no JOIN job_grades j
ON m.salary BETWEEN j.lowest_sal AND j.highest_sal
AND m.salary > 15000;

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

Additional Practices and Solutions


Chapter 12 - Page 13
NIIT LTD

15. Show the department number, department name, number of employees, and average
salary of all departments, together with the employee names, salaries, and jobs of the
employees working in each department.
SELECT d.department_id, d.department_name,
count(e1.employee_id) employees,
NVL(TO_CHAR(AVG(e1.salary), '99999.99'), 'No average' )
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

avg_sal,
e2.last_name, e2.salary, e2.job_id
FROM departments d RIGHT OUTER JOIN employees e1
ON d.department_id = e1.department_id
RIGHT OUTER JOIN employees e2
ON d.department_id = e2.department_id
GROUP BY d.department_id, d.department_name, e2.last_name,
e2.salary,
e2.job_id
s a
ORDER BY d.department_id, employees;
) h a
ฺ c om
the highest average salary. a h oo eฺ
16. Create a report to display the department number and lowest salary of the department with

@ y u id
SELECT department_id, MIN(salary)
b m nt G
FROM employees s r
(r tude
GROUP BY department_id T
E is S
H
S e th
HAVING AVG(salary) = (SELECT MAX(AVG(salary))
H us
N AT employees
FROM
t o
A M GROUPseBY department_id);
17. Create a report that displays
R l en
R theidepartments
c where no sales representatives work. Include
A
K bl
the department number, e
department name, manager ID, and location in the output.
A N a
I S H * sfer
SELECT

ANFROM t r n
adepartments
V -
HA non
WHERE department_id NOT IN(SELECT department_id
B FROM employees
WHERE job_id = 'SA_REP'
AND department_id IS NOT NULL);
18. Create the following statistical reports for the HR department. Include the department
number, department name, and the number of employees working in each department that:
a. Employs fewer than three employees:
SELECT d.department_id, d.department_name, COUNT(*)
FROM departments d JOIN employees e
ON d.department_id = e.department_id
GROUP BY d.department_id, d.department_name
HAVING COUNT(*) < 3;

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

Additional Practices and Solutions


Chapter 12 - Page 14
NIIT LTD

b. Has the highest number of employees:


SELECT d.department_id, d.department_name, COUNT(*)
FROM departments d JOIN employees e
ON d.department_id = e.department_id
GROUP BY d.department_id, d.department_name
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

HAVING COUNT(*) = (SELECT MAX(COUNT(*))


FROM employees
GROUP BY department_id);
c. Has the lowest number of employees:
SELECT d.department_id, d.department_name, COUNT(*)
FROM departments d JOIN employees e
ON d.department_id = e.department_id
GROUP BY d.department_id, d.department_name
HAVING COUNT(*) = (SELECT MIN(COUNT(*))
s a
FROM employees
) h a
GROUP BY department_id);
ฺ c om
a h oo number,
19. Create a report that displays the employee number, last name, salary, department
eฺ
and the average salary in their department for all employees. y u
@ te.salary, i d
b m G
rsr tuden
SELECT e.employee_id, e.last_name, e.department_id,
AVG(s.salary)
sT
(
FROM employees e JOIN employees E
H i s S
ON S
e.department_id = s.department_id t h
GROUP BY e.employee_id, A TH use e.department_id,
e.last_name,
e.salary;
A MN se to
20. Create an anniversaryR R ibased
overview
l c enon the hire date of employees. Sort the
KA border.
anniversaries in ascending
N le
A
H last_name,
SELECT f a
er TO_CHAR(hire_date, 'Month DD') BIRTHDAY
I S n s
V ANFROM - t r aemployees
BHA nORDER on BY TO_CHAR(hire_date, 'DDD');

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

Additional Practices and Solutions


Chapter 12 - Page 15
NIIT LTD

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© 2012, 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
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
ISwant atonbuild
Note: If you
N s the tables, you can execute the commands in the
VA youocan r
-texecute
Online_Book_Store_Create_Table.sql
n script in SQL Developer. If you want to drop the
H A
tables,
n the commands in the Online_Book_Store_Drop_Tables.sql
B 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 © 2016, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 16
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

Tasks
1. Table Details
a. Table Name: AUTHOR
Column Data type Key Table Dependent Type
Author_ID VARCHAR2 PK
Author_Name VARCHAR2
b. Table Name: BOOKS
Column Datatype Key Table Dependent On a
Book_ID VARCHAR2 PK
h a s
)
Book_Name VARCHAR2
ฺ c om
Author_ID
Price
VARCHAR2
NUMBER a h oo eฺ
FK AUTHORS

PUBLISHER@
y u id
Publisher_ID VARCHAR2 FK
b m nt G
c. Table Name: CUSTOMER
( s r
r tude
Column Name Data type Key E T Table SDependent On
H h i s
Customer_ID VARCHAR2
T H S use t
PK
Customer_Name VARCHAR2
N A to
Street_Address
City R AM ense
VARCHAR2
VARCHAR2
Phone_Number
K ARVARCHAR2
l e lic
H ab
AN ferVARCHAR2
Credit_Card_Number FK Credit_Card_Details
I S ns
d.NCREDIT_CARD_DETAILS
A
V Name- t r a
HA non
Column Data type Key Table Dependent On
B 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 © 2016, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 17
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

Column Data type Key Table Dependent Type


Customer_ID VARCHAR2 FK CUSTOMER
Order_ID NUMBER FK ORDER_DETAILS
h. Table Name: SHIPPING_TYPE
Column Data type Key Table Dependent Type
Shipping_Type VARCHAR2 PK
Shipping_Price NUMBER
i. Table Name: SHOPPING_CART
Column Data type Key Table Dependent On s a
Shopping_Cart_ID NUMBER PK ) h a
Book_ID VARCHAR2 FK
ฺ c omBOOKS
Price NUMBER
a h oo eฺ
Shopping_Cart_Date DATE
@ y u id
Quantity NUMBER
b m nt G
r
(r tude
s
T S
E tablesiscreated.
H
2. Add additional Referential Integrity constraints to the
h
HbySchecking
3. Verify that the tables were created properly
T s e tin the Connections Navigator in
SQL Developer.
N A to u
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Additional Practices and Solutions


Chapter 12 - Page 18
NIIT LTD

4. Create a sequence to uniquely identify each row in the ORDER_DETAILS table.


a. Start with 100; do not allow caching of the values. Name the sequence
ORDER_ID_SEQ.
b. Verify the existence of the sequences in the Connections Navigator in SQL Developer.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H usof data to be added.
T each set
N Afor
5. Add data to the tables. Create a script t o
AM ense
Add data to the following tables:
R
a. AUTHOR AR
K l e lic
AN ferab
b. PUBLISHER
H
N Ic.S SHIPPING_TYPE
a ns
A t r
V d. -CUSTOMER
BHA non e. CREDIT_CARD_DETAILS
f. BOOKS
g. SHOPPING_CART
h. ORDER_DETAILS
i. PURCHASE_HISTORY
Note: Save the scripts by using the task number. For example, to save the script created
for the AUTHOR table, you can save it as labs_apcs_5a_1.sql. Ensure that you save
the scripts in /home/oracle/labs/sql1/labs folder.

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

Additional Practices and Solutions


Chapter 12 - Page 19
NIIT LTD

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© 2012, 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
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
AR c the book details that you just entered in 7(a).
lifor
b. Enter a shopping
K e
cart detail
l
H AN ferab
N IS ans
A VA on-tr
BH n

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

Additional Practices and Solutions


Chapter 12 - Page 20
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Additional Practices and Solutions


Chapter 12 - Page 21
NIIT LTD

Solution 1-2

Overview
The solution to Practice 1-2 is given as follows.

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

1. Table Details
a. AUTHOR
CREATE TABLE AUTHOR
(
Author_ID VARCHAR2 (10) NOT NULL ,
Author_Name VARCHAR2 (20)
)
;
s a
) h a
ฺ c om
COMMENT ON TABLE AUTHOR IS 'Author'
a h oo eฺ
@ y u id
;
b m nt G
r
(r tude
s
T
E is S
ALTER TABLE AUTHOR H
S e KEYth (Author_ID);
H
ADD CONSTRAINT AUTHOR_PK
N AT to us
PRIMARY

b. BOOKS
R AM ense
K AR BOOKS
CREATE TABLE
l e lic
( N
A r a b
H
IS Book_ID e
sf VARCHAR2 (10) NOT NULL ,
N
A n-tr a n
V Book_Name VARCHAR2 (50) ,

BHA no 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 © 2016, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 22
NIIT LTD

c. CUSTOMER
CREATE TABLE CUSTOMER
(
Customer_ID VARCHAR2 (6) NOT NULL ,
Customer_Name VARCHAR2 (40) ,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, 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
ฺ c om
ALTER TABLE CUSTOMER
a h oo eฺ
y id
ADD CONSTRAINT Customer_PK PRIMARY KEY ( Customer_ID ) ;
@ u
b m nt G
r
(r tude
s
d. CREDIT_CARD_DETAILS T
E is S
H
S e th
CREATE TABLE CREDIT_CARD_DETAILSH
(
N AT to us
R AM eVARCHAR2
Credit_Card_Number
n se (20) NOT NULL ,
R
Credit_Card_Type
A e l icVARCHAR2 (15) ,
NK rabDATE
Expiry_Date
A
l
I S H) sfe
V AN; n-tran
BHA no COMMENT ON TABLE CREDIT_CARD_DETAILS IS 'Credit Card Details'
;

ALTER TABLE CREDIT_CARD_DETAILS


ADD CONSTRAINT Credit_Card_Details_PK PRIMARY KEY (
Credit_Card_Number) ;

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

Additional Practices and Solutions


Chapter 12 - Page 23
NIIT LTD

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© 2012, 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
ฺ c om
f. PUBLISHER
a h oo eฺ
CREATE TABLE PUBLISHER
@ y u id
( b m nt G
s
Publisher_ID VARCHAR2 (10) NOT (NULL
r
r , tude
Publisher_Name VARCHAR2 (50)E
T S
H h i s
)
T H S use t
;
N A to
R AM ense
K AR le lic
H e rabPUBLISHER IS 'Publisher'
ANON fTABLE
N IS ans
COMMENT

VA on-tr
;

H A n
B
ALTER TABLE PUBLISHER
ADD CONSTRAINT PUBLISHER_PK PRIMARY KEY ( Publisher_ID) ;

g. PURCHASE_HISTORY
CREATE TABLE PURCHASE_HISTORY
(
Customer_ID VARCHAR2 (6) NOT NULL ,
Order_ID VARCHAR2 (6) NOT NULL
)
;

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

Additional Practices and Solutions


Chapter 12 - Page 24
NIIT LTD

COMMENT ON TABLE PURCHASE_HISTORY IS 'Purchase History'


;

h. SHIPPING_TYPE
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

CREATE TABLE SHIPPING_TYPE


(
Shipping_Type VARCHAR2 (10) NOT NULL ,
Shipping_Price NUMBER (6)
)
;

COMMENT ON TABLE SHIPPING_TYPE IS 'Shipping Type'


;
s a
) h a
ALTER TABLE SHIPPING_TYPE
ฺ c om
a h oo eฺ
ADD CONSTRAINT SHIPPING_TYPE_PK PRIMARY KEY ( Shipping_Type
) ;
@ y u id
b m nt G
r
(r tude
s
i. SHOPPING _CART T
E is S
H
S e th
CREATE TABLE SHOPPING_CART H
( N AT to us
Shopping_Cart_ID
R AM VARCHAR2
e n se (6) NOT NULL ,
Book_ID R
A VARCHAR2
e l ic(10) NOT NULL ,
NKNUMBER
Price
A r a bl (10) ,
I S n s fe
HShopping_Cart_Date DATE ,

V AN n-tQuantity
ra NUMBER (6)

BHA no ) ;

COMMENT ON TABLE SHOPPING_CART IS 'Shopping Cart'


;

ALTER TABLE SHOPPING_CART


ADD CONSTRAINT SHOPPING_CART_PK PRIMARY KEY (SHOPPING_CART_ID)
;

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

Additional Practices and Solutions


Chapter 12 - Page 25
NIIT LTD

2. Adding Additional Referential Integrity Constraints to the Table Created

a. Include a Foreign Key constraint in the CUSTOMER table.

ALTER TABLE CUSTOMER


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

ADD CONSTRAINT CREDIT_CARD_FK FOREIGN KEY


(
Credit_Card_Number
)
REFERENCES CREDIT_CARD_DETAILS
(
Credit_Card_Number
)
;
s a
) h a
b. Include a Foreign Key constraint in the BOOKS table.ฺ c om
a h oo eฺ
@ y u id
ALTER TABLE BOOKS
b m t G
s r KEY en
(r tud
ADD CONSTRAINT BOOKS_AUTHOR_FK FOREIGN
T
(
H E is S
Author_ID
H S e th
)
N AT to us
AM ense
REFERENCES AUTHOR
( R
K AR le lic
Author_ID
) AN r a b
;IS
H sf e
N a n
A VA on-tr
BH nALTER TABLE BOOKS
ADD CONSTRAINT BOOKS_PUBLISHER_FK FOREIGN KEY
(
Publisher_ID
)
REFERENCES PUBLISHER
(
Publisher_ID
);

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

Additional Practices and Solutions


Chapter 12 - Page 26
NIIT LTD

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

ALTER TABLE ORDER_DETAILS


ADD CONSTRAINT Order_ID_FK FOREIGN KEY
(
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

Customer_ID
)
REFERENCES CUSTOMER
(
Customer_ID
)
;

s a
ALTER TABLE ORDER_DETAILS
) h a
ADD CONSTRAINT FK_Order_details FOREIGN KEY
ฺ c om
(
a h oo eฺ
Shipping_Type
@ y u id
)
b m nt G
REFERENCES SHIPPING_TYPE s r
(r tude
( T
E is S
Shipping_Type H
S e th
H
)
N AT to us
;
R AM ense
K AR le lic
ALTER A
N rab
I S H
n s fe
TABLE ORDER_DETAILS

A N -traADD CONSTRAINT Order_Details_fk FOREIGN KEY


V
HA non
(
B Shopping_Cart_ID
)
REFERENCES SHOPPING_CART
(
Shopping_Cart_ID
)
;
d. Include a Foreign Key constraint in the PURCHASE_HISTORY table.

ALTER TABLE PURCHASE_HISTORY


ADD CONSTRAINT Pur_Hist_ORDER_DETAILS_FK FOREIGN KEY
(
Order_ID
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 27
NIIT LTD

)
REFERENCES ORDER_DETAILS
(
Order_ID
)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

;
ALTER TABLE PURCHASE_HISTORY
ADD CONSTRAINT Purchase_History_CUSTOMER_FK FOREIGN KEY
(
Customer_ID
)
REFERENCES CUSTOMER
(
Customer_ID
s a
) ;
) h a
e. ฺ c om
Include a Foreign Key constraint in the SHOPPING_CART table.
a h oo eฺ
@ y u id
ALTER TABLE SHOPPING_CART
b m nKEY t G
s r
(r tud
ADD CONSTRAINT SHOPPING_CART_BOOKS_FK e
FOREIGN
( T
E is S
Book_ID H
S e th
T H us
)
REFERENCES BOOKSM N A t o
R A ense
AR le lic
(
K
Book_ID
N rab
)A
I S H
n s fe
AN n-tra
;
V
BHA no
3. Verify that the tables were created properly by checking in the Connections Navigator in
SQL Developer. In the Connections Navigator, expand Connections > myconnection >
Tables.

4. Create a sequence to uniquely identify each row in the ORDER_DETAILS table.


a. Start with 100; do not allow caching of the values. Name the sequence ORDER_ID_SEQ.
CREATE SEQUENCE order_id_seq
START WITH 100
NOCACHE;

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

Additional Practices and Solutions


Chapter 12 - Page 28
NIIT LTD

b. Verify the existence of the sequences in the Connections Navigator in SQL Developer.
In the Connections Navigator, assuming that the myconnection node is expanded,
expand Sequences.
Alternatively, you can also query the user_sequences data dictionary view:
SELECT * FROM user_sequences;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

5. Add data to the tables.


a. AUTHOR Table
Author_ID Author_Name
AN0001 Oliver Goldsmith
AN0002 Oscar Wilde
AN0003 George Bernard Shaw
AN0004 Leo Tolstoy
s a
AN0005 Percy Shelley ) h a
AN0006 ฺ c om Lord Byron
AN0007 John Keats a h oo eฺ
@ y u id
AN0008 Rudyard Kipling
b m nt G
AN0009 s r
(r tude
P. G. Wodehouse
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

b. PUBLISHER Table

Publisher_ID Publisher_Name
PN0001 Elsevier
PN0002 Penguin Group
PN0003 Pearson Education
PN0004 Cambridge University Press
PN0005 Dorling Kindersley

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

Additional Practices and Solutions


Chapter 12 - Page 29
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

c. SHIPPING _TYPE

Shipping_Type Shipping_Price
USPS 200
FedEx 250
DHL 150
s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
d. CUSTOMER T
E is S
H
S e th
Customer Customer _Name A T H
Street us City Phone Credit _Card
_ ID N
M se t
_Address o _number _Number
A n
CN0001
A R R lice 283
VelasquezCarmen King Seattle 587-99-6666 000-111-222-333
NK rabl e Street
CN0002A
H Ngao fe LaDoris 5 Modrany Bratislav 586-355-8882 000-111-222-444
I S n s
V AN n-tra a

BHA nCN0003
o Nagayama Midori 68 Via Sao 254-852-5764 000-111-222-555
Centrale Paolo
CN0004 Quick-To-See 6921 King Way Lagos 63-559-777 000-111-222-666
Mark
CN0005 Ropeburn Audry 86 Chu Street Hong 41-559-87 000-111-222-777
Kong
CN0006 Urguhart Molly 3035 Laurier Quebec 418-542-9988 000-111-222-888
Blvd.
CN0007 Menchu Roberta Boulevard de Brussels 322-504-2228 000-111-222-999
Waterloo 41
CN0008 Biri Ben 398 High St. Columbu 614-455-9863 000-111-222-222
s
CN0009 Catchpole 88 Alfred St. Brisbane 616-399-1411 000-111-222-111
Antoinette
Copyright © 2016, Oracle and/or its affiliates. All rights reserved.

Additional Practices and Solutions


Chapter 12 - Page 30
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

e. CREDIT_CARD_DETAILS

Credit _Card_ Number Credit _Card _Type Expiry _Date


000-111-222-333 Platinum 17-JUN-2019
s a
000-111-222-444 SpecialCard 24-SEP-2025
) h a
000-111-222-555 PayM ฺ c om 11-JUL-2017
000-111-222-666 Platinum 22-OCT-2018 a h oo eฺ
@ y u id
000-111-222-777 PayM 26-AUG-2020
b m nt G
000-111-222-888 SpecialCard
r
(r tude
s
15-MAR-2018
T
E 4-AUG-2019 S
000-111-222-999 Platinum H h i s
S e27-SEP-2021
t
000-111-222-111 MaestroTH s
N A to u 9-AUG-2024
000-111-222-222
R AM ense
PayM

K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

f. BOOKS
Book _ID Book _Name Author _ID Price Publisher _ID
BN0001 Florentine Tragedy AN0002 150 PN0002
BN0002 A Vision AN0002 100 PN0003
BN0003 Citizen of the World AN0001 100 PN0001

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

Additional Practices and Solutions


Chapter 12 - Page 31
NIIT LTD

BN0004 The Complete Poetical AN0001 300 PN0001


Works of Oliver
Goldsmith
BN0005 Androcles and the Lion AN0003 90 PN0004
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

BN0006 An Unsocial Socialist AN0003 80 PN0004

BN0007 A Thing of Beauty is a AN0007 100 PN0002


Joy Forever

BN0008 Beyond the Pale AN0008 75 PN0005

s a
BN0009 The Clicking of AN0009 175 PN0005
) h a
Cuthbert
ฺ c om
oo eฺ
200 yahPN0001
BN00010 Bride of Frankenstein AN0006
@ u id
b m nt G
BN00011 Shelley's Poetry and AN0005(r s r de PN0003
150
T t u
Prose
H E is S
H S e th
BN00012 War and Peace
s
AT to uAN0004 150 PN0002
M N e
R A ens
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

g. SHOPPING_CART
Shopping _Cart Book _ID Price Shopping _Cart Quantity
_ID _Date
SC0001 BN0002 200 12-JUN-2011 10

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

Additional Practices and Solutions


Chapter 12 - Page 32
NIIT LTD

SC0002 BN0003 90 31-JUL-2014 8


SC0003 BN0003 175 28-JUN-2015 7
SC0004 BN0001 80 14-AUG-2016 9
SC0005 BN0001 175 21-SEP-2016 4
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

SC0006 BN0004 100 11-AUG-2012 6


SC0007 BN0005 200 28-OCT-2012 5
SC0008 BN0006 100 25-NOV-2013 7
SC0009 BN0006 150 18-SPET-2013 8

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
h. ORDER _DETAILS H us
Order _ID Customer MN
AT
Shipping_to Date _of _Purchase Shopping _Cart _ID
_ID RA n
Type
e se
OD0001 K AR le licUSPS
CN0001 12-JUN-2011 SC0002
N
A fCN0002 ra b
I S H
OD0002
s e USPS 28-JUN-2015 SC0005

V ANOD0003
- t r an CN0003 FedEx 31-JUL-2014 SC0007
n
HA nOD0004
o CN0004 FedEx 14-AUG-2016 SC0004
B
OD0005 CN0005 FedEx 21-SEP-2016 SC0003
OD0006 CN0006 DHL 28-OCT-2012 SC0001
OD0007 CN0007 DHL 11-AUG-2012 SC0006
OD0008 CN0008 DHL 18-SEP-2013 SC0008
OD0009 CN0009 USPS 25-NOV-2013 SC0009

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

Additional Practices and Solutions


Chapter 12 - Page 33
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ

i. PURCHASE_HISTORY
s a
Customer _ID Order _ID
) h a
CN0001
ฺ om
OD0001
c
CN0003 OD0002
a h oo eฺ
CN0004 OD0005 @ y u id
b m nt G
CN0009 s
OD0007 r
(r tude
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
6. CreateIS s CUSTOMER_DETAILS to show the Customer Name, Customer
a view named
N
A n-tr
Address, and a n
details of the order placed by the customer. Order the results by Customer ID.
V
BHA nCREATEo VIEW customer_details AS
SELECT c.customer_name, c.street_address, o.order_id,
o.customer_id, o.shipping_type, o.date_of_purchase,
o.shopping_cart_id
FROM customer c JOIN order_details o
ON c.customer_id = o.customer_id;

SELECT *
FROM customer_details
ORDER BY customer_id;

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

Additional Practices and Solutions


Chapter 12 - Page 34
NIIT LTD
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, 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.

INSERT INTO books(book_id, book_name, author_id, price,


s a
publisher_id)
) h a
ฺ c om
VALUES ('BN0013','Two States','AN0009','150','PN0005');

a h oo eฺ
SELECT * FROM books;
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

b. Enter a shopping cart detail for the book details that you just entered in 7(a).

INSERT INTO shopping_cart(shopping_cart_id, book_id, price,


Shopping_cart_date,quantity)
VALUES ('SC0010','BN0013','200',TO_DATE('12-JUN-2016','DD-MON-
YYYY'),'12');

SELECT * FROM shopping_cart;

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

Additional Practices and Solutions


Chapter 12 - Page 35
NIIT LTD

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© 2012, Oracle and/or its affiliatesฺ

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;

s a
) h a
ฺ c om
a h oo eฺ
@ y u id
b m nt G
r
(r tude
s
T
E is S
H
S e th
H
N AT to us
R AM ense
K AR le lic
H AN ferab
N IS ans
A VA on-tr
BH n

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

Additional Practices and Solutions


Chapter 12 - Page 36

You might also like