Professional Documents
Culture Documents
SQL 1-3 PDF
SQL 1-3 PDF
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
e to
cens
l i
a le
b
Oracle Database 11g: r
feSQL
n s
Fundamentals n -Itra
a no
h a s deGuide ฺ
)
Volume III i
• Student
u
o m t G
o o ฺc den
y ah s Stu
h n @ thi
r a j o use
( o gi
g i r a
n O
J o h
D49996GC11
Edition 1.1
April 2009
D59982
Computer Pride Limited
Brian Pottle 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
Technical Contributors 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
and Reviewers not use, share, download, upload, copy, print, display, perform, reproduce, publish,
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
Claire Bennett license, post, transmit, or distribute this document in whole or in part without the
express authorization of Oracle.
Tom Best
Purjanti Chang The information contained in this document is subject to change without notice. If you
Ken Cooper find any problems in the document, please report them in writing to: Oracle University,
László Czinkóczki 500 Oracle Parkway, Redwood Shores, California 94065 USA. This document is not
warranted to be error-free.
Burt Demchick
Mark Fleming Restricted Rights Notice
Gerlinde Frenzen
Nancy Greenberg 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
Chaitanya Koratamaddi applicable:
Wendy Lo
e to
Timothy Mcglue
Alan Paulson
U.S. GOVERNMENT RIGHTS
The U.S. Government’s rights to use, modify, reproduce, release, perform, display, or
ce ns
l i
disclose these training materials are restricted by the terms of the applicable Oracle
Bryan Roberts license agreement and/or the applicable U.S. Government contract.
a b le
Abhishek Singh
fe r
Lori Tritz Trademark Notice
a n s
Michael Versaci
Lex van der Werff n- t r
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other
no
names may be trademarks of their respective owners.
a
Editors
h a s deฺ
Raj Kumar
m ) G ui
Amitha Narayan
o ฺ co ent
Vijayalakshmi Narasimhan
y a ho Stud
Graphic Designer
n @ t h is
Satish Bettegowda
r a j oh use
( o gi
g ira
Publishers
n OSujatha Nagendra
Joh Syed Ali
Computer Pride Limited
Contents
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
Preface
I Introduction
Lesson Objectives I-2
Lesson Agenda I-3
Course Objectives I-4
Course Agenda I-5
Appendixes Used in the Course I-7 e to
Lesson Agenda I-8
cens
l i
Oracle Database 11g: Focus Areas I-9
a ble
Oracle Database 11g I-10
fe r
Oracle Fusion Middleware I-12 a ns
Oracle Enterprise Manager Grid Control 10g I-13 n- t r
Oracle BI Publisher I-14 a no
h a s deฺ
Lesson Agenda I-15
m ) G ui
o ฺ co ent
Relational and Object Relational Database Management Systems I-16
d
aho s Stu
Data Storage on Different Media I-17
y
Relational Database Concept I-18
@ thi
h n
Definition of a Relational Database I-19
o use
r a j
(o gi
Data Models I-20
Entity Relationship Model I-21
g i r aEntity Relationship Modeling Conventions I-23
n O
J o h Relating Multiple Tables I-25
Relational Database Terminology I-27
Lesson Agenda I-29
Using SQL to Query Your Database I-30
SQL Statements I-31
Development Environments for SQL I-32
Lesson Agenda I-33
The Human Resources (HR) Schema I-34
Tables Used in the Course I-35
Lesson Agenda I-36
Oracle Database 11g Documentation I-37
Additional Resources I-38
iii
Computer Pride Limited
Summary I-39
Practice I: Overview I-40
Objectives 1-2
Lesson Agenda 1-3
Capabilities of SQL SELECT Statements 1-4
Basic SELECT Statement 1-5
Selecting All Columns 1-6
Selecting Specific Columns 1-7
Writing SQL Statements 1-8
Column Heading Defaults 1-9
Lesson Agenda 1-10
e to
Arithmetic Expressions 1-11
cens
l i
Using Arithmetic Operators 1-12
a ble
Operator Precedence 1-13
fe r
Defining a Null Value 1-14
a ns
Null Values in Arithmetic Expressions 1-15 n- t r
Lesson Agenda 1-16 a no
Defining a Column Alias 1-17 h a s deฺ
Using Column Aliases 1-18 m ) G ui
o ฺ co ent
Lesson Agenda 1-19 d
Concatenation Operator 1-20 y aho s Stu
n @ thi
Literal Character Strings 1-21
h
r a j o use
Using Literal Character Strings 1-22
(o gi
Alternative Quote (q) Operator 1-23
g i r a
Duplicate Rows 1-24
n O
J o h Lesson Agenda 1-25
Displaying the Table Structure 1-26
Using the DESCRIBE Command 1-27
Quiz 1-28
Summary 1-29
Practice 1: Overview 1-30
iv
Computer Pride Limited
r a j o use
Lesson Agenda 2-34
gi
Using the DEFINE Command 2-35
(o the VERIFY Command
gi r a Using 2-36
n O Quiz 2-37
J o h Summary 2-38
Practice 2: Overview 2-39
v
Computer Pride Limited
vi
Computer Pride Limited
vii
Computer Pride Limited
viii
Computer Pride Limited
ix
Computer Pride Limited
g i r a
Lesson Agenda 9-13
Changing Data in a Table 9-14
O
o h n UPDATE Statement Syntax 9-15
J Updating Rows in a Table 9-16
Updating Two Columns with a Subquery 9-17
Updating Rows Based on Another Table 9-18
Lesson Agenda 9-19
Removing a Row from a Table 9-20
DELETE Statement 9-21
Deleting Rows from a Table 9-22
Deleting Rows Based on Another Table 9-23
TRUNCATE Statement 9-24
Lesson Agenda 9-25
Database Transactions 9-26
Database Transactions: Start and End 9-27
x
Computer Pride Limited
gira
Lesson Agenda 10-6
xi
Computer Pride Limited
xii
Computer Pride Limited
xiii
Computer Pride Limited
Summary C-22
Practice C: Overview C-23
Objectives D-2
SQL and SQL*Plus Interaction D-3
SQL Statements Versus SQL*Plus Commands D-4
Overview of SQL*Plus D-5
Logging In to SQL*Plus D-6
Displaying Table Structure D-8
SQL*Plus Editing Commands D-10
Using LIST, n, and APPEND D-12
Using the CHANGE Command D-13
e to
SQL*Plus File Commands D-14
cens
l i
Using the SAVE, START, and EDIT Commands D-15
a ble
SERVEROUTPUT Command D-17
fe r
Using the SQL*Plus SPOOL Command D-18 a ns
Using the AUTOTRACE Command D-19 n- t r
Summary D-20 a no
h a s deฺ
) u i
Appendix E: Using SQL Developer
c m
o ent G
o ฺ
Objectives E-2
y
o
ahE-3 S tud
What Is Oracle SQL Developer?
n @ t h is
a joh uE-5se
Specifications of SQL Developer
Installing SQLirDeveloper
E-4
xiv
Computer Pride Limited
Index
Additional Practices
e to
cens
Additional Practices: Solutions l i
a ble
fe r
a ns
n- t r
a no
h a s deฺ
m ) G ui
o ฺ co ent
d
y aho s Stu
h n @ thi
r a j o use
(o gi
g i r a
n O
J o h
xv
Computer Pride Limited
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
e to
cens
l i
a ble
fe r
a ns
n- t r
a no
h a s deฺ
m ) G ui
o ฺ co ent
d
y aho s Stu
h n @ thi
r a j o use
(o gi
g i r a
n O
J o h
Computer Pride Limited
__________________
Additional Practices
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
__________________
e to
cens
l i
a ble
fe r
a ns
n- t r
a no
h a s deฺ
m ) G ui
o ฺ co ent
d
y aho s Stu
h n @ thi
r a j o use
(o gi
g i r a
n O
J o h
Computer Pride Limited
Additional Practices
These exercises can be used for extra practice after you have discussed the following topics:
Basic SQL SELECT statement, basic SQL Developer commands, and SQL functions.
1. The HR department needs to find data for all of the clerks who were hired after the year
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
1997.
2. The HR department needs a report of employees who earn commission. Show the last name,
job, salary, and commission of those employees. Sort the data by salary in descending order.
e to
cens
l i
a ble
fe r
a ns
n- t r
a no
h a s deฺ
m ) G ui
o ฺ co ent
d
y aho s Stu
h n @ thi
r a j o use
(o gi
g i r a
n O
J o h
3. For budgeting purposes, the HR department needs a report on projected raises. The report
should display those employees who have no commission, but who have a 10% raise in
salary (round off the salaries).
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
e to
cens
l i
a ble
fe r
a ns
n- t r
a no
h a s deฺ
m ) G ui
o ฺ co ent
d
y aho s Stu
h n @ thi
r a j o use
(o gi
g i r a
n O
J o h
4. Create a report of employees and their length 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 length 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ฺ
… to
ns e
l i ce
a ble
fe r
a ns
n- t r
no
5. Show those employees who have a last name starting with the letters “J,” “K,” “L,” or “M.”
a
h a s deฺ
m ) G ui
o ฺ co ent
d
y aho s Stu
h n @ thi
r a j o use
(o gi
r a
gi a report that displays all employees, and indicate with the words Yes or No whether
6. Create
O
n they receive a commission. Use the DECODE expression in your query.
Joh Note: Results are continued on the next page.
6. (continued)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
e to
cens
l i
a ble
fe r
a ns
n- t r
a no
h a s deฺ
m ) G ui
o ฺ co ent
d
y aho s Stu
h n @ thi
r a j o use
(o gi
g i r a
n O
J o h
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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
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 the location. For
example, if the user enters 1800, these are the results:
8. Find the number of employees who have a last name that ends with the letter “n.” Create two
possible solutions. e to
ce ns
l i
a ble
fe r
a n s
n r
-t for each department.
9. Create a report that shows the name, location, and number of employees
o
a nemployees.
Make sure that the report also includes departments without
h a s
i d eฺ
m ) G u
o
ฺc den t
o o
y ah s Stu
h n @ thi
r a j o use
( o gi
g ira
nO
Joh
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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
11. Create a report that displays the jobs that are found in the Administration and Executive
departments. Also display the number of employees for these jobs. Show the job with the
highest number of employees first.
e to
ce ns
l i
a ble
fe r
a ns
n- t r
a no
h a s deฺ
m ) G ui
o ฺ co ent
d
y aho s Stu
h n @ thi
r a j o use
(o gi
g i r a
n O
J o h
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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
12. Show all the employees who were hired in the first half of the month (before the 16th of the
month).
e to
cens
l i
a ble
fe r
a ns
13. Create a report that displays the following for all employees: last name, salary, and salary
expressed in terms of thousands of dollars. n- t r
a no
h a s deฺ
Note: Results are continued on the next page.
m ) G ui
o ฺ co ent
d
y aho s Stu
h n @ thi
r a j o use
( o gi
g ira
nO
Joh
13. (continued)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
e to
14. Show all the employees who have managers with a salary higher than $15,000. Show the
cens
following data: employee name, manager name, manager salary, and salary grade of thel i
manager. a ble
fe r
a ns
n- t r
a no
h a s deฺ
m ) G ui
o ฺ co ent
d
y aho s Stu
h n @ thi
r a j o use
(o gi
g i r a
n O
J o h
15. Show the department number, name, number of employees, and average salary of all the
departments, together with the names, salaries, and jobs of the employees working in each
department.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
… to
ns e
l i ce
a ble
r
16. Create a report to display the department number and lowest salary of the department with
fe
the highest average salary.
a ns
n- t r
a no
h a s deฺ
m ) G ui
o ฺ co ent
d
y aho s Stu
h n @ thi
r a j o use
(o gi
g i r a
n O
J o h
17. Create a report that displays departments where no sales representatives work. Include the
department number, department name, manager ID, and the location in the output.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
18. Create the following statistical reports for the HR department: Include the department
e to
number, department name, and the number of employees working in each department that:
cens
l i
a. Employs fewer than three employees:
a ble
fe r
a ns
n- t r
a no
h a s deฺ
m ) G ui
b. Has the highest number of employees:
o ฺ co ent
d
y aho s Stu
h n @ thi
r a j o use
o i
glowest
c. Has (the number of employees:
g i r a
nO
Joh
19. Create a report that displays the employee number, last name, salary, department number,
and the average salary in their department for all employees.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
e to
cens
l i
ble
… s fe r a
t r a n
no n-
a
s deฺ
h a
)day of the i on which the highest number
m
20. Show all the employees who were hired on the G uweek
of employees were hired. o ฺ co ent
d
y aho s Stu
h n @ thi
r a j o use
( o gi
g ira
nO
Joh
21. 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ฺ
e to
cens
l i
a ble
… fe r
a ns
n- t r
a no
h a s deฺ
m ) G ui
o ฺ co ent
d
y aho s Stu
h n @ thi
r a j o use
(o gi
g i r a
n O
J o h
In this case study, you build a set of database tables for a video application. After you create the
tables, you insert, update, and delete records in a video store database and generate a report. The
database contains only the essential tables.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
The following is a diagram of the entities and attributes for the video application:
TITLE
for #* id
RESERVATION * title
#* res date the subject * description
of o rating
set up for o category
o release date
e to
available as ce ns
l i
a ble
fe r
a ns
responsible a copy
n- t r
for o
nTITLE_COPY
a
s #* ฺ
h a i d e
id
MEMBER
m ) G u * status
#* id o
ฺc den t
* last name o o
o first name y ah s Stu the subject of
o address th i
n@responsible
o city aj o h s e
g i r ufor made against
o phone
o
r a (
* join date
g i RENTAL
n O created #* book date
J o h for o act ret date
o exp ret date
Note: If you want to build the tables, you can execute the commands in the
buildtab.sql script in SQL Developer. If you want to drop the tables, you can execute
the commands in the dropvid.sql script in SQL Developer. Then you can execute the
commands in the buildvid.sql script in SQL Developer to create and populate the
tables. All the three sql scripts are present in the D:\labs\sql1\labs folder.
• If you use the buildtab.sql script to build the tables, start with step 4.
• If you use the dropvid.sql script to remove the video tables, start with step 1.
• If you use the buildvid.sql script to build and populate the tables, start with step
6(b).
1. Create the tables based on the following table instance charts. Choose the appropriate data
types and be sure to add integrity constraints.
Length 10 60 400 4 20
Key PK PK,FK
Type
Null/ NN,U NN,U NN
Unique
Check AVAILABLE,
DESTROYED,
RENTED,
RESERVED
FK Ref TITLE
Table
e to
FK Ref
ns
TITLE_ID
Col
l i ce
Data NUMBER NUMBER VARCHAR2
a b le
Type
fe r
Length 10 10 15
a n s
n- t r
a no
h a s deฺ
d. Table name: RENTAL
m ) G ui
o ฺ co ACT_RET_
e n t
Column BOOK_ MEMBER_
ho COPY_
t u d EXP_RET_ TITLE_
Name DATE ID
y a sSID DATE DATE ID
Key PK PK,FK1
n i
@ thPK,FK2 PK,FK2
h e
rajo us
Type
i
Default gSystem System Date
Value (o Date + 2 days
a
FKirRef
g MEMBER TITLE_ TITLE_
n O Table COPY COPY
J o h FK Ref MEMBER_I COPY_ TITLE_ID
Col D ID
Data DATE NUMBER NUMBER DATE DATE NUMBER
Type
Length 10 10 10
3. Create sequences to uniquely identify each row in the MEMBER table and the TITLE table.
a. Member number for the MEMBER table: Start with 101; do not allow caching of the
values. Name the sequence MEMBER_ID_SEQ.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
b. Title number for the TITLE table: Start with 92; do not allow caching of the values.
Name the sequence TITLE_ID_SEQ.
c. Verify the existence of the sequences in the Connections Navigator in SQL Developer.
e to
cens
l i
a ble
fe r
a ns
n- t r
a no
h a s deฺ
m ) G ui
o ฺ co ent
d
y aho s Stu
h n @ thi
r a j o use
(o gi
g i r a
n O
4. Add data to the tables. Create a script for each set of data to be added.
J o h
a. Add movie titles to the TITLE table. Write a script to enter the movie information.
Save the statements in a script named lab_apcs_4a.sql. Use the sequences to
uniquely identify each title. Enter the release dates in the DD-MON-YYYY format.
Remember that single quotation marks in a character field must be specially handled.
Verify your additions.
wish list.
Alien Again Yet another installation of R SCIFI 19-MAY-1995
science fiction history. Can
the heroine save the planet
from the alien life form?
The Glob A meteor crashes near a small NR SCIFI 12-AUG-1995
American town and unleashes
carnivorous goo in this classic.
My Day Off With a little luck and a lot of PG COMEDY 12-JUL-1995
ingenuity, a teenager skips
e to
Miracles on Ice
school for a day in New York.
A six-year-old has doubts PG DRAMA 12-SEP-1995 ce ns
l i
about Santa Claus, but she
a ble
discovers that miracles really
fe r
do exist.
a n s 01-JUN-1995
Soda Gang After discovering a cache of NR t
ACTION
n- r
drugs, a young couple find
themselves pitted against a a no
vicious gang.
h a s deฺ
m ) G ui
o inserten
b. Add data to the MEMBER table. Saveฺcthe t
statements in a script named
lab_apcs_4b.sql. Execute o
h Stuo
commands din the script. Be sure to use the sequence to
y a
add the member numbers.
n @ t h is
First_
r a j oh use
Name
( o gi Last_Name Address City Phone Join_Date
g ira
Carmen Velasquez 283 King
Street
Seattle 206-899-6666 08-MAR-1990
n O
J o h LaDoris Ngao 5 Modrany Bratislava 586-355-8882 08-MAR-1990
2 RENTED 2
h a s deฺ
m ) G ui
Note: The title number may be o o ฺco depending
d. Add the following rentals to the RENTAL
different
table:
d e n t
on the sequence number.
a h S t u
Title_ Id Copy_
@ y
Member_Id i s
Id hn 101se t h Book_date Exp_Ret_Date
92 1rajo u 3 days ago 1 day ago
g i
93 ira
(o 2 101 1 day ago 1 day from now
g
n O95
Joh
3 102 2 days ago Today
5. Create a view named TITLE_AVAIL to show the movie titles, the availability of each copy,
and its expected return date if rented. Query all rows from the view. Order the results by title.
Note: Your results may be different.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
e to
6. Make changes to the data in the tables.
ce ns
l i
a ble
a. Add a new title. The movie is “Interstellar Wars,” which is rated PG and classified as a
fe r
a ns
science fiction movie. The release date is 07-JUL-77. The description is “Futuristic
n- t r
interstellar action movie. Can the rebels save the humans from the evil empire?” Be sure
to add a title copy record for two copies.
a no
b. Enter two reservations. One reservation is for h a
Carmen
i d eฺ who wants to rent
s Velasquez,
m
“Interstellar Wars.” The other is for Mark ) G u who wants to rent “Soda Gang.”
Quick-to-See,
o
ฺc den t
o o
y ah s Stu
h n @ thi
r a j o use
( o gi
g ira
nO
Joh
e to
ce ns
l i
a ble
fe r
a ns
Title Price
n- t r
Willie and Christmas Too 25
a no
Alien Again 35
h a s deฺ
The Glob m )
35 G ui
My Day Off o ฺ co ent
35
d
Miracles on Ice y aho s Stu 30
Soda Gang
h n @ thi 35
r a j o use
Interstellar Wars 29
(o gi
r a
b.giCreate a script named lab_apcs_7b.sql that contains update statements that update
n O each video with a price according to the preceding list. Run the commands in the script.
Joh Note: Have the TITLE_ID numbers available for this exercise.
8. Create a report that contains each customer’s history of renting videos. Be sure to include the
customer name, movie rented, dates of the rental, and duration of rentals. Total the number of
rentals for all customers for the reporting period. Save the commands that generate the report
in a script file named lab_apcs_8.sql.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
e to
ce ns
l i
a ble
fe r
a ns
n- t r
a no
h a s deฺ
m ) G ui
o ฺ co ent
d
y aho s Stu
h n @ thi
r a j o use
(o gi
g i r a
n O
J o h
e to
cens
l i
a ble
fe r
a ns
n- t r
a no
h a s deฺ
m ) G ui
o ฺ co ent
d
y aho s Stu
h n @ thi
r a j o use
(o gi
g i r a
n O
J o h
Computer Pride Limited
__________________
Additional Practices:
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
Solutions
__________________
e to
cens
l i
a ble
fe r
a ns
n- t r
a no
h a s deฺ
m ) G ui
o ฺ co ent
d
y aho s Stu
h n @ thi
r a j o use
(o gi
g i r a
n O
J o h
Computer Pride Limited
These exercises can be used for extra practice after you have discussed the following topics:
Basic SQL SELECT statement, basic SQL Developer commands, and SQL functions.
1. The HR department needs to find data for all of the clerks who were hired after the year
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
1997.
SELECT *
FROM employees
WHERE job_id = 'ST_CLERK'
AND hire_date > '31-DEC-1997';
2. The HR department needs a report of employees who earn commission. Show the last name,
job, salary, and commission of those employees. Sort the data by salary in descending order.
SELECT last_name, job_id, salary, commission_pct e to
FROM employees
cens
l i
WHERE commission_pct IS NOT NULL
ORDER BY salary DESC;
a ble
fe r
a ns
3. For budgeting purposes, the HR department needs a report on projected raises. The report
n- t r
should display those employees who do not get a commission but who have a 10% raise in
salary (round off the salaries). a no
has au10% ฺ
SELECT 'The salary of '||last_name||' )after ideraise is '
|| ROUND(salary*1.10) "New
ฺ c omsalary"
n t G
FROM employees
a h oo tude
WHERE commission_pct IS NULL;
y i s S
@
hn sand t h
o
4. Create a report of jemployees e their duration of employment. Show the last names of all
o g ira with theunumber of years and the number of completed months that they
employees together
have a
r ( employed. Order the report by the duration of their employment. The employee
been
i
g has been employeed the longest should appear at the top of the list.
who
nO
Joh SELECT last_name,
TRUNC(MONTHS_BETWEEN(SYSDATE, hire_date) / 12) YEARS,
TRUNC(MOD(MONTHS_BETWEEN(SYSDATE, hire_date), 12)) MONTHS
FROM employees
ORDER BY years DESC, MONTHS desc;
5. Show those employees who have a last name starting with the letters “J,” “K,” “L,” or “M.”
SELECT last_name
FROM employees
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
6. Create a report that displays all employees, and indicate with the words Yes or No whether
they receive a commission. Use the DECODE expression in your query.
SELECT last_name, salary,
decode(commission_pct, NULL, 'No', 'Yes') commission
FROM employees;
e to
cens
l i
a ble
fe r
a ns
n- t r
a no
h a s deฺ
m ) G ui
o ฺ co ent
d
y aho s Stu
h n @ thi
r a j o use
(o gi
g i r a
n O
J o h
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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
7. Create a report that displays the department name, location ID, name, job title, and salary of
those employees who work in a specific location. Prompt the user for the location.
e to
8. Find the number of employees who have a last name that ends with the letter “n.” Create two
possible solutions. ce ns
l i
a ble
SELECT COUNT(*)
fe r
FROM employees
a ns
WHERE last_name LIKE '%n';
n- t r
no
--or
SELECT COUNT(*)
a
s deฺ
FROM employees
h a
WHERE SUBSTR(last_name, -1) = 'n';
m ) G ui
o ฺ co andenumber
n t
9. Create a report that shows the name,
h o location,
t u d of employees for each department.
a S
Make sure that the report alsoyincludes departments
s without employees.
@ h i
j
SELECT d.department_id,o hn sd.department_name,
e t
ira e RIGHT
d.location_id,
o g u COUNT(e.employee_id)
FROM
r a (
employees OUTER JOIN departments d
ON
g i BY d.department_id,d.department_id
e.department_id =
n O
GROUP d.department_name, d.location_id;
J oh 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.
SELECT DISTINCT job_id
FROM employees
WHERE department_id IN (10, 20);
11. Create a report that displays the jobs that are found in the Administration and Executive
departments. Also display the number of employees for these jobs. Show the job with the
highest number of employees first.
SELECT e.job_id, count(e.job_id) FREQUENCY
FROM employees e JOIN departments d
ON e.department_id = d.department_id
WHERE d.department_name IN ('Administration', 'Executive')
GROUP BY e.job_id
ORDER BY FREQUENCY DESC;
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.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
12. Show all employees who were hired in the first half of the month (before the 16th of the
month).
SELECT last_name, hire_date
FROM employees
WHERE TO_CHAR(hire_date, 'DD') < 16;
13. Create a report that displays the following for all employees: last name, salary, and salary
expressed in terms of thousands of dollars.
e to
ns
SELECT last_name, salary, TRUNC(salary, -3)/1000 Thousands
FROM employees;
l i ce
14. Show all employees who have managers with a salary higher than $15,000. Show the a ble
fe r
a ns
following data: employee name, manager name, manager salary, and salary grade of the
manager.
n- t r
SELECT
a no
e.last_name, m.last_name manager, m.salary, j.grade_level
FROM employees e JOIN employees m
h a s deฺ
ON e.manager_id = m.employee_id
m ) G ui
JOIN job_grades j
o ฺ co ent
d
aho s Stu
ON m.salary BETWEEN j.lowest_sal AND j.highest_sal
AND m.salary > 15000;
y
@ thi
h n
o number, e number of employees, and average salary of all
15. Show the department
i r a j u s name,
departments,
( o gtogether with the names, salaries, and jobs of the employees working in each
department.
g ira
n O
SELECT d.department_id, d.department_name,
J o h count(e1.employee_id) employees,
NVL(TO_CHAR(AVG(e1.salary), '99999.99'), 'No average' ) avg_sal,
e2.last_name, e2.salary, e2.job_id
FROM departments d RIGHT OUTER JOIN employees e1
ON d.department_id = e1.department_id
RIGHT OUTER JOIN employees e2
ON d.department_id = e2.department_id
GROUP BY d.department_id, d.department_name, e2.last_name, e2.salary,
e2.job_id
ORDER BY d.department_id, employees;
16. Create a report to display the department number and lowest salary of the department with
the highest average salary.
SELECT department_id, MIN(salary)
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
FROM employees
GROUP BY department_id
HAVING AVG(salary) = (SELECT MAX(AVG(salary))
FROM employees
GROUP BY department_id);
17. Create a report that displays the departments where no sales representatives work. Include the
department number, department name, and location in the output.
SELECT *
FROM departments
e to
WHERE department_id NOT IN(SELECT department_id
ce ns
FROM employees l i
WHERE job_id = 'SA_REP'
a b le
AND department_id IS NOT NULL);
fe r
a n s
r
-t the department
18. Create the following statistical reports for the HR department: Include
n
o
a n ฺ in each department that:
number, department name, and the number of employees working
s
a. Employs fewer than three employees: ) ha uide
ฺ c om ent G
SELECT d.department_id, d.department_name,
o o d COUNT(*)
FROM
ah s Stu
departments d JOIN employees
d.department_id =ye.department_id
e
hi
ON
h n @ d.department_name
t
GROUP BY d.department_id,
a j<o 3; us e
HAVING COUNT(*)
g i r
( o
a the highest number of employees:
b. ir
Has
g
O d.department_id, d.department_name, COUNT(*)
o h nSELECT
J FROM
ON
departments d JOIN employees e
d.department_id = e.department_id
GROUP BY d.department_id, d.department_name
HAVING COUNT(*) = (SELECT MAX(COUNT(*))
FROM employees
GROUP BY department_id);
ON d.department_id = e.department_id
GROUP BY d.department_id, d.department_name
HAVING COUNT(*) = (SELECT MIN(COUNT(*))
FROM employees
GROUP BY department_id);
19. Create a report that displays the employee number, last name, salary, department number,
and the average salary in their department for all employees.
SELECT e.employee_id, e.last_name, e.department_id, e.salary,
AVG(s.salary)
e to
FROM employees e JOIN employees s
cens
ON e.department_id = s.department_id l i
GROUP BY e.employee_id, e.last_name, e.department_id, e.salary;
a ble
fe r
ns
20. Show all employees who were hired on the day of the week on which the highest number of
a
employees were hired. n- t r
SELECT last_name, TO_CHAR(hire_date, 'DAY') day a no
h a s deฺ
ui
FROM employees
WHERE TO_CHAR(hire_date, 'Day') = m ) G
ฺ co ent
(SELECT TO_CHAR(hire_date, 'Day')
o d
FROM employees
y aho s Stu
GROUP BY TO_CHAR(hire_date, 'Day')
h n @ thi
HAVING COUNT(*) = (SELECT MAX(COUNT(*))
r a j o use
FROM employees
1. Create the tables based on the following table instance charts. Choose the appropriate data
types and be sure to add integrity constraints.
r a j o use
(rating IN ('G', 'PG', 'R', 'NC17', 'NR')),
gi
category VARCHAR2(20)
(o
CONSTRAINT title_category_ck CHECK
a
g i r(category IN ('DRAMA', 'COMEDY', 'ACTION',
J o h release_date DATE);
member_id NUMBER(10)
CONSTRAINT rental_member_id_fk REFERENCES member(member_id),
copy_id NUMBER(10),
act_ret_date DATE,
exp_ret_date DATE DEFAULT SYSDATE + 2,
title_id NUMBER(10),
CONSTRAINT rental_book_date_copy_title_pk
PRIMARY KEY (book_date, member_id, copy_id,title_id),
CONSTRAINT rental_copy_id_title_id_fk
FOREIGN KEY (copy_id, title_id)
REFERENCES title_copy(copy_id, title_id));
e to
cens
e. Table name: RESERVATION l i
a ble
CREATE TABLE reservation
fe r
(res_date DATE,
a ns
member_id NUMBER(10)
n- t r
no
CONSTRAINT reservation_member_id REFERENCES member(member_id),
a
title_id NUMBER(10)
h a s deฺ
ui
CONSTRAINT reservation_title_id REFERENCES title(title_id),
m ) G
CONSTRAINT reservation_resdate_mem_tit_pk PRIMARY KEY
o
(res_date, member_id, title_id)); ฺ co ent
y a ho Stud
n t h is by checking in the Connections Navigator in
2. Verify that the tables were created properly
@
SQL Developer.
r a j oh use
a. In the
( o gi
Connections Navigator, expand Connections > myconnection > Tables.
gi r a
n O
Joh
3. Create sequences to uniquely identify each row in the MEMBER table and the TITLE table.
a. Member number for the MEMBER table: Start with 101; do not allow caching of the
values. Name the sequence MEMBER_ID_SEQ.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
b. Title number for the TITLE table: Start with 92; do not allow caching of the values.
Name the sequence TITLE_ID_SEQ.
CREATE SEQUENCE title_id_seq
START WITH 92
NOCACHE;
e to
cens
c. Verify the existence of the sequences in the Connections Navigator in SQL Developer.l i
a ble
fe r
a. In the Connections Navigator, assuming that the myconnection node is expanded,
expand Sequences. a ns
n- t r
a no
h a s deฺ
m ) G ui
o ฺ co ent
d
y aho s Stu
h n @ thi
r a j o use
(o gi
g i r a
n O
J o h
4. Add data to the tables. Create a script for each set of data to be added.
a. Add movie titles to the TITLE table. Write a script to enter the movie information.
Save the statements in a script named lab_apcs_4a.sql. Use the sequences to
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
uniquely identify each title. Enter the release dates in the DD-MON-YYYY format.
Remember that single quotation marks in a character field must be specially handled.
Verify your additions.
INSERT INTO title(title_id, title, description, rating,
category, release_date)
VALUES (title_id_seq.NEXTVAL, 'Willie and Christmas Too',
'All of Willie''s friends make a Christmas list for
Santa, but Willie has yet to add his own wish list.',
'G', 'CHILD', TO_DATE('05-OCT-1995','DD-MON-YYYY'))
/
e to
INSERT INTO title(title_id , title, description, rating,
cens
category, release_date) l i
VALUES (title_id_seq.NEXTVAL, 'Alien Again', 'Yet another
a ble
installment of science fiction history. Can the
fe r
heroine save the planet from the alien life form?',
a ns
'R', 'SCIFI', TO_DATE( '19-MAY-1995','DD-MON-YYYY'))
n- t r
/
a no
h a s deฺ
INSERT INTO title(title_id, title, description, rating,
category, release_date)
m ) G ui
co ent
VALUES (title_id_seq.NEXTVAL, 'The Glob', 'A meteor crashes
o ฺ
near a small American town and unleashes carnivorous
d
aho s Stu
goo in this classic.', 'NR', 'SCIFI',
y
h n @ thi
TO_DATE( '12-AUG-1995','DD-MON-YYYY'))
/
r a j o use
INSERT INTO title(title_id, title, description, rating,
(o gicategory, release_date)
VALUES
g i r a
(title_id_seq.NEXTVAL, 'My Day Off', 'With a little
...
COMMIT
/
SELECT title
FROM title;
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
e to
cens
l i
a ble
fe r
a ns
n- t r
a no
h a s deฺ
m ) G ui
o ฺ co ent
d
y aho s Stu
h n @ thi
r a j o use
(o gi
g i r a
n O
J o h
b. Add data to the MEMBER table. Place the insert statements in a script named
lab_apcs_4b.sql. Execute the commands in the script. Be sure to use the sequence
to add the member numbers.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
r a j o use
'6921 King Way', 'Lagos', '63-559-7777', TO_DATE('07-APR-1990',
gi
'DD-MM-YYYY'))
/
a (o
i r
INSERT INTO member(member_id, first_name, last_name,
g
n O address, city, phone, join_date)
/
y a ho Stud
INSERT
@
INTO title_copy(copy_id,
n t h is title_id,status)
VALUES
r a j oh use
(1, 97, 'AVAILABLE')
/
( o gi
g ira
nO
Joh
SELECT *
FROM title_avail
ORDER BY title, copy_id;
a. Add a new title. The movie is “Interstellar Wars,” which is rated PG and classified as a
science fiction movie. The release date is 07-JUL-77. The description is “Futuristic
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
interstellar action movie. Can the rebels save the humans from the evil empire?” Be sure
to add a title copy record for two copies.
INSERT INTO title(title_id, title, description, rating,
category, release_date)
VALUES (title_id_seq.NEXTVAL, 'Interstellar Wars',
'Futuristic interstellar action movie. Can the
rebels save the humans from the evil empire?',
'PG', 'SCIFI', '07-JUL-77')
/
e to
ns
INSERT INTO title_copy (copy_id, title_id, status)
VALUES (1, 98, 'AVAILABLE')
l i ce
/
INSERT INTO title_copy (copy_id, title_id, status)
a ble
fe r
VALUES (2, 98, 'AVAILABLE')
a ns
/
n- t r
no
b. Enter two reservations. One reservation is for Carmen Velasquez, who wants to rent
a
a s deฺ
“Interstellar Wars.” The other is for Mark Quick-to-See, who wants to rent “Soda Gang.”
h
) i
utitle_id)
INSERT INTO reservation (res_date,om t
member_id,G
o ฺ c e n
ho Stud
VALUES (SYSDATE, 101, 98)
/
y a
INSERT INTO reservation
n @ h is member_id, title_id)
(res_date,
t
VALUES (SYSDATE, 104,
r a j oh use
97)
gi
/
( o
iraa modification to one of the tables.
7. Make
g
n O
J o h a. Run the script lab_apcs_7a.sql located in D:\labs\sql1\labs folder, to
add a PRICE column to the TITLE table to record the purchase price of the video.
Verify your modifications.
ALTER TABLE title
ADD (price NUMBER(8,2));
DESCRIBE title
b. Create a script named lab_apcs_7b.sql that contains update statements that update
each video with a price according to the list provided. Run the commands in the script.
Note: Have the TITLE_ID numbers available for this exercise.
Unauthorized reproduction or distribution prohibitedฺ Copyright© 2012, Oracle and/or its affiliatesฺ
8. Create a report that contains each customer’s history of renting videos. Be sure to include the
customer name, movie rented, dates of the rental, and duration of rentals. Total the number of
e to
rentals for all customers for the reporting period. Save the commands that generate the report
ce ns
in a script file named lab_apcs_8.sql. l i
Note: Your results may be different.
a ble
fe r
SELECT m.first_name||' '||m.last_name MEMBER, t.title,
a ns
r.book_date, r.act_ret_date - r.book_date DURATION
n- t r
FROM member m
JOIN rental r a no
ON r.member_id = m.member_id
h a s deฺ
JOIN title t
m ) G ui
ON r.title_id = t.title_id
o ฺ co ent
d
aho s Stu
ORDER BY member;
y
@ thi
h n
o use
r a j
(o gi
g i r a
n O
J o h
e to
cens
l i
a ble
fe r
a ns
n- t r
a no
h a s deฺ
m ) G ui
o ฺ co ent
d
y aho s Stu
h n @ thi
r a j o use
(o gi
g i r a
n O
J o h