You are on page 1of 122

M/sSeed Infotech Ltd

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

s a
Oracle Database 12c: a
) h SQL
Workshop II lco m e
i i d
g ma nt Gu
@ tude
Activity7Guide
5
i
m his S
t a
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

D80194GC11
Edition 1.1
July 2014
D87272
M/sSeed Infotech Ltd

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

Disclaimer

This document contains proprietary information and is protected by copyright and other intellectual property laws. You may copy and
print this document solely for your own use in an Oracle training course. The document may not be modified or altered in any way.
Except where your use constitutes "fair use" under copyright law, you may not use, share, download, upload, copy, print, display,
perform, reproduce, publish, license, post, transmit, or distribute this document in whole or in part without the express authorization
of Oracle.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

The information contained in this document is subject to change without notice. If you find any problems in the document, please
report them in writing to: Oracle University, 500 Oracle Parkway, Redwood Shores, California 94065 USA. This document is not
warranted to be error-free.

Restricted Rights Notice

If this documentation is delivered to the United States Government or anyone using the documentation on behalf of the United
States Government, the following notice is applicable:

U.S. GOVERNMENT RIGHTS


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

Trademark Notice

a
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective
s
owners.

) h a
Author m
co uide
i l
ma nt G
Dimpi Rani Sarmah
g
Technical Contributors and Reviewers
i 5 7@ tude
Nancy Greenberg, Swarnapriya Shridhar, Bryan Roberts,
a m Laszlo i s S
Czinkoczki, KimSeong Loh,
u t
Brent Dayley, Jim Spiller, Christopher Wensley, Maheshwari t h
Krishnamurthy, Daniel Milne,
a se Bennett, Yanti Chang,
Michael Almeida, Diganta Choudhury, Manish h g Pawar,uClair
Joel Goodman, Gerlinde Frenzen, Madhavi
b r ijes Siddireddy
e to
(
i cen s
m
ut ble li
a
Editors
Raj Kumar, MalavikaaJinka
h G era
r i
Publishers je ransf
s
B n-tPavithran Adka
Jobi Varghese,
no
This book was published using: Oracle Tutor
M/sSeed Infotech Ltd

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

Practices for Lesson 2: Introduction to Data Dictionary Views ...................................................................2-1


Practices for Lesson 2: Overview ...................................................................................................................2-2
Practice 2-1: Introduction to Data Dictionary Views .......................................................................................2-3
Solution 2-1: Introduction to Data Dictionary Views .......................................................................................2-6
Practices for Lesson 3: Creating Sequences, Synonyms, and Indexes ......................................................3-1
Practices for Lesson 3: Overview ...................................................................................................................3-2
Practice 3-1: Creating Sequences, Synonyms, and Indexes .........................................................................3-3
Solution 3-1: Creating Sequences, Synonyms, and Indexes .........................................................................3-5
Practices for Lesson 4: Creating Views .........................................................................................................4-1
Practices for Lesson 4: Overview ...................................................................................................................4-2
Practice 4-1: Creating Views ..........................................................................................................................4-3
s a
h a
Solution 4-1: Creating Views ..........................................................................................................................4-6
)
o
Practices for Lesson 5: Managing Schema Objects .....................................................................................5-1m
c uide
i l
ma nt G
Practices for Lesson 5: Overview ...................................................................................................................5-2
g
Practice 5-1: Managing Schema Objects .......................................................................................................5-3

5 7@ tude
Solution 5-1: Managing Schema Objects .......................................................................................................5-8
i
Practices for Lesson 6: Retrieving Data by Using Subqueries
t a m his S
....................................................................6-1

g au se t
Practices for Lesson 6: Overview ...................................................................................................................6-2
h
Practice 6-1: Retrieving Data by Using Subqueries
j e t o u
s .......................................................................................6-3
Solution 6-1: Retrieving Data by Using b r i e
i ( Subqueries e n s.......................................................................................6-8
a m Datalibyc Using Subqueries ...............................................................7-1
Practices for Lesson 7: Manipulating
t
u le
Practices for Lesson 7:aOverview ...................................................................................................................7-2
b
G
h sfData a
er by Using Subqueries ...................................................................................7-3
j e s
Practice 7-1: Manipulating

B ri7-1: Manipulating
Solution
t r an Data by Using Subqueries ...................................................................................7-5
-
non
Practices for Lesson 8: Controlling User Access .........................................................................................8-1
Practices for Lesson 8: Overview ...................................................................................................................8-2
Practice 8-1: Controlling User Access ............................................................................................................8-3
Solution 8-1: Controlling User Access ............................................................................................................8-6
Practices for Lesson 9: Manipulating Data ....................................................................................................9-1
Practices for Lesson 9: Overview ...................................................................................................................9-2
Practice 9-1: Manipulating Data .....................................................................................................................9-3
Solution 9-1: Manipulating Data .....................................................................................................................9-8
Practices for Lesson 10: Managing Data in Different Time Zones...............................................................10-1
Practices for Lesson 10: Overview .................................................................................................................10-2
Practice 10-1: Managing Data in Different Time Zones..................................................................................10-3
Solution 10-1: Managing Data in Different Time Zones..................................................................................10-6
Additional Practices and Solutions ................................................................................................................11-1
Additional Practices and Solutions .................................................................................................................11-2
Additional Practices........................................................................................................................................11-3

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

Oracle Database 12c: SQL Workshop II Table of Contents


M/sSeed Infotech Ltd

Additional Practices Solutions ........................................................................................................................11-9


Additional Practices: Case Study ...................................................................................................................11-15
Additional Practices Solution: Case Study .....................................................................................................11-18
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Oracle Database 12c: SQL Workshop II Table of Contents


M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
Practices for Lesson o m
c uide
1:
i l
Introduction ma t G
g
@ tude n
Chapter 1 i57
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 1
M/sSeed Infotech Ltd

Practices for Lesson 1: Overview


Practice Overview
You also learn about your user account that you use in this course. You then start SQL
Developer, create a new database connection, and browse your HR tables. You also set some
SQL Developer preferences, execute SQL statements, and execute an anonymous PL/SQL
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

block by using SQL Worksheet.

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 2
M/sSeed Infotech Ltd

Practice 1-1: Using SQL Developer


Tasks
1. Start SQL Developer by using the desktop icon.
2. Create a database connection using the following information:
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Connection Name: myconnection


Username: ora21
Password: ora21
Hostname: localhost
Port: 1521
SID: orcl (or the value provided to you by the instructor)
3. Test the new connection. If the status is Success, connect to the database by using this
new connection.
a. Click the Test button in the New/Select Database Connection window.
b. If the status is Success, click the Connect button.
s a
4. Browse the structure of the EMPLOYEES table and display its data.
)h a
a. Expand the myconnection connection by clicking the plus sign next to it.
o m
b. Expand the Tables icon by clicking the plus sign next to it.
a ilc Guide
c. Display the structure of the EMPLOYEES table.
@ gm ent
d. View the data of the DEPARTMENTS table. i 5 7
S t ud
5. Execute some basic SELECT statements to query
u t am
the data
t h iins the EMPLOYEES table in the
SQL Worksheet area. Use both the Execute
h a
g Statement e (or press F9) and the Run Script (or
sReview
s u
b r ijeon the eappropriate
press F5) icons to execute the SELECT
to
statements. the results of both methods of
executing the SELECT statements
i ( ens tabbed pages.
a. Write a query to a
t m the last
select l ic name and salary for any employee whose salary is less
than or equal u
a abl
to $3,000. e
b. Write a
G
h stofedisplay
query r last name, job ID, and commission for all employees who are
j es
B rinot entitled
t r anto receive a commission.
6.
o -
Set yournscript pathing preference to /home/oracle/labs/sql2.
a. nSelect Tools > Preferences > Database > Worksheet.
b. Enter the value in the Select default path to look for scripts field.
7. Enter the following in the Enter SQL Statement box.
SELECT employee_id, first_name, last_name
FROM employees;

8. Save the SQL statement to a script file by using the File > Save menu item.
a. Select File > Save.
b. Name the file intro_test.sql.
c. Place the file under your /home/oracle/labs/sql2/labs folder.
9. Open and run confidence.sql from your /home/oracle/labs/sql2/labs folder,
and observe the output.

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 3
M/sSeed Infotech Ltd

Solution 1-1: Using SQL Developer


1. Start SQL Developer by using the desktop icon.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

2. Create a database connection using the following information:


Connection Name: myconnection
Username: ora21
Password: ora21
Hostname: localhost
Port: 1521
SID: orcl (or the value provided to you by the instructor)
s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 4
M/sSeed Infotech Ltd

3. Test the new connection. If the status is Success, connect to the database by using this
new connection.
a. Click the Test button in the New/Select Database Connection window.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
a m his S
b. If the status is Success, click the Connecttbutton.
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
e s h sfer
j
Bri n-tran
no

4. Browse the structure of the EMPLOYEES table and display its data.
Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 5
M/sSeed Infotech Ltd

a. Expand the myconnection connection by clicking the plus sign next to it.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

b. Expand the Tables icon by clicking the plus sign next to it.

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 6
M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

c. Display the structure of the EMPLOYEES table.


Click the EMPLOYEES table. The Columns tab displays the columns in the EMPLOYEES table
as follows:

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
o
d. nView the data of the DEPARTMENTS table.
In the Connections navigator, click the DEPARTMENTS table. Then click the Data tab.

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 7
M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

5. Execute some basic SELECT statements to query the data in the EMPLOYEES table in the
SQL Worksheet area. Use both the Execute Statement (and press F9) and the Run Script
icons (or press F5) to execute the SELECT statements. Review the results of both methods
of executing the SELECT statements on the appropriate tabbed pages. s a
) h a
a. Write a query to select the last name and salary for any employee whose salary is less
than or equal to $3,000. o m
c uide
i l
a tG
SELECT last_name, salary
g m
FROM employees
7 @ u d en
WHERE salary <= 3000;
a m i5
i s St
g a ut e th
e s h o us
b j
ri se t
(
i cen
m
a ut ble li
a
h G era
r i je ransf
s
B n-t
no


b. Write a query to display last name, job ID, and commission for all employees who are
not entitled to receive a commission.
SELECT last_name, job_id, commission_pct
FROM employees
WHERE commission_pct IS NULL;

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 8
M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

6. Set your script pathing preference to /home/oracle/labs/sql2.


a. Select Tools > Preferences > Database > Worksheet. s a
) h a
b. Enter the value in the Select default path to look for scripts field. Then, click OK.
o m
c uide
Note: To view the number of rows selected, enable the feedback option and set it to 1.
i l
set feedback on;
g ma nt G
set feedback 1;
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 9
M/sSeed Infotech Ltd

7. Enter the following SQL statement:


SELECT employee_id, first_name, last_name
FROM employees;

8. Save the SQL statement to a script file by using the File > Save As menu item.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a. Select File > Save.

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
t am e lic
b. Name the file intro_test.sql.
u
a abl in the File_name text box.
Enter intro_test.sql
G
j es
c. Place er the /home/oracle/labs/sql2/labs folder.
hthe filesunder
f
Bri n-tran
no

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 10
M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
a
)h
o m
a ilc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
Then, click Save. r i j es e to u
i (b from e n syour /home/oracle/labs/sql2/labs folder and
9. m
Open and run confidence.sql
uta ble lic
observe the output.
a
h G era
r i je ransf
s
B n-t
no

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 11
M/sSeed Infotech Ltd

Open the confidence.sql script file by using the File > Open menu item.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
u
r ijes e to
Then, press F5 to execute thebscript.
i ( result:
e n s
m
uta ble lic
The following is the expected
a
G era
h
r i je ransf
s
B n-t
no

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 12
M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 13
M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 1: Introduction


Chapter 1 - Page 14
M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
Practices for Lesson o m
c uide
2:
i
a tGl
Introduction to mData
@ g en
Dictionary 7 Views u d
a m i5
i s St
g a ut 2 e th
Chapter

e s h o us
b j
ri se t
(
i cen
m
a ut ble li
a
h G era
r i je ransf
s
B n-t
no

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

Practices for Lesson 2: Introduction to Data Dictionary Views


Chapter 2 - Page 1
M/sSeed Infotech Ltd

Practices for Lesson 2: Overview


Practice overview
This practice covers the following topics:
Querying the dictionary views for table and column information
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Querying the dictionary views for constraint information


Adding a comment to a table and querying the dictionary views for comment information

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 2: Introduction to Data Dictionary Views


Chapter 2 - Page 2
M/sSeed Infotech Ltd

Practice 2-1: Introduction to Data Dictionary Views


Overview
In this practice, you query the dictionary views to find information about objects in your schema.

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

1. Query the USER_TABLES data dictionary view to see information about the tables that you
own.


2. Query the ALL_TABLES data dictionary view to see information about all the tables that you
s a
can access. Exclude the tables that you own.
) h a
Note: Your list may not exactly match the following list:
o m
c uide
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 2: Introduction to Data Dictionary Views


Chapter 2 - Page 3
M/sSeed Infotech Ltd

3. For a specified table, create a script that reports the column names, data types, and data
types lengths, as well as whether nulls are allowed. Prompt the user to enter the table
name. Give appropriate aliases to the DATA_PRECISION and DATA_SCALE columns.
Save this script in a file named lab_02_03.sql.
For example, if the user enters DEPARTMENTS, the following output results:
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
a
)h
m
a i l co uide
4. m ntype,
Create a script that reports the column name, constraint name, constraint
g t G search
condition, and status for a specified table. You must join the
7 @ u d e
USER_CONSTRAINTS and

a m i5 Prompt
USER_CONS_COLUMNS tables to obtain all this information.
i s St the user to enter the
g
For example, if the user enters DEPARTMENTS, a utthe following
table name. Save the script in a file named lab_02_04.sql.
e th output results:
e s h o us
b j
ri se t
(
i cen
m
a ut ble li
a
h G era
r i je ransf
s
B n-t
5. Addnaocomment to the DEPARTMENTS table. Then query the USER_TAB_COMMENTS view to
verify that the comment is present.

6. Run the lab_02_06_tab.sql script as a prerequisite for exercises 6 through 9.


Alternatively, open the script file to copy the code and paste it into your SQL Worksheet.
Then execute the script. This script:
Drops the existing DEPT2 and EMP2 tables
Creates the DEPT2 and EMP2 tables
Note: In Practice 2, you should have already dropped the DEPT2 and EMP2 tables so that
they cannot be restored.

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

Practices for Lesson 2: Introduction to Data Dictionary Views


Chapter 2 - Page 4
M/sSeed Infotech Ltd

7. Confirm that both the DEPT2 and EMP2 tables are stored in the data dictionary.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

8. Confirm that the constraints were added, by querying the USER_CONSTRAINTS view. Note
the types and names of the constraints.

9. Display the object names and types from the USER_OBJECTS data dictionary view for the
EMP2 and DEPT2 tables.

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 2: Introduction to Data Dictionary Views


Chapter 2 - Page 5
M/sSeed Infotech Ltd

Solution 2-1: Introduction to Data Dictionary Views


Solution
1. Query the data dictionary to see information about the tables you
own.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

SELECT table_name
FROM user_tables;

2. Query the dictionary view to see information about all the tables that you can access.
Exclude tables that you own.
SELECT table_name, owner
FROM all_tables
WHERE owner <>'ORAxx';

3. For a specified table, create a script that reports the column names, data types, and data
types lengths, as well as whether nulls are allowed. Prompt the user to enter the table
name. Give appropriate aliases to the DATA_PRECISION and DATA_SCALE columns. Save s a
this script in a file named lab_02_03.sql. )h a
m
SELECT column_name, data_type, data_length,
a i lco uide
data_precision PRECISION, data_scale m
g t G
SCALE, nullable
n
FROM user_tab_columns
5 7 @ tude
WHERE table_name = UPPER('&tab_name'); i
m his S
t a
To test, run the script and enter DEPARTMENTS
h g au as sthee table
t name.
4. Create a script that reports the column
j e u name, constraint type, search
s name,toconstraint
r i
USER_CONS_COLUMNSm i (bto obtain
condition, and status for a specified
tables e salleYou
table.
n this
must join the USER_CONSTRAINTS and
information. Prompt the user to enter the
table name. Save u t a l i c
G a the script
a b linea file named lab_02_04.sql.
s
SELECT
j e s f er
h ucc.column_name, uc.constraint_name, uc.constraint_type,

BriFROM - t r n
auc.search_condition, uc.status

nONon uc.table_name = ucc.table_name


user_constraints uc JOIN user_cons_columns ucc

AND uc.constraint_name = ucc.constraint_name


AND uc.table_name = UPPER('&tab_name');
To test, run the script and enter DEPARTMENTS as the table name.

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

Practices for Lesson 2: Introduction to Data Dictionary Views


Chapter 2 - Page 6
M/sSeed Infotech Ltd

5. Add a comment to the DEPARTMENTS table. Then query the USER_TAB_COMMENTS view to
verify that the comment is present.
COMMENT ON TABLE departments IS
'Company department information including name, code, and
location.';
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

SELECT COMMENTS
FROM user_tab_comments
WHERE table_name = 'DEPARTMENTS';

6. Run the lab_02_06_tab.sql script as a prerequisite for exercises 6 through 9.


Alternatively, open the script file to copy the code and paste it into your SQL Worksheet.
Then execute the script. This script:
Drops the DEPT2 and EMP2 tables
Creates the DEPT2 and EMP2 tables
s a
7. Confirm that both the DEPT2 and EMP2 tables are stored in the data dictionary. h
) a
SELECT table_name o m
c uide
FROM user_tables i
a tGl
table_name IN ('DEPT2', 'EMP2'); gm
WHERE
7 @ u d en
a m i5
i s St
Query the data dictionary to find out the g a ut names
e thand types for both the tables.
8.
j e s t o us
constraint
hconstraint_type
i
(br ense
SELECT constraint_name,
FROM i
user_constraints
WHERE
t am e lINic ('EMP2', 'DEPT2');
table_name
u
G a abl
es h sfer
j
9. Bri nthe-trobject
Display an names and types from the USER_OBJECTS data dictionary view for the
EMP2o
n and DEPT2 tables.
SELECT object_name, object_type
FROM user_objects
WHERE object_name= 'EMP2'
OR object_name= 'DEPT2';

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

Practices for Lesson 2: Introduction to Data Dictionary Views


Chapter 2 - Page 7
M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 2: Introduction to Data Dictionary Views


Chapter 2 - Page 8
M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
Practices for Lesson o m
c uide
3:
i l
Creating Sequences,
g ma nt G
Synonyms,
i 5 de
7@andtuIndexes
a m i s S
t
au se t
Chapter 3 h
h g
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 3: Creating Sequences, Synonyms, and Indexes


Chapter 3 - Page 1
M/sSeed Infotech Ltd

Practices for Lesson 3: Overview


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

Using sequences
Querying the dictionary views for sequence information
Creating synonyms
Querying the dictionary views for synonyms information
Creating indexes
Querying the dictionary views for indexes information

Note: Before starting this practice, execute


/home/oracle/sql2/code_ex/code_ex_scripts/clean_up_scripts/cleanup_03.sql script.

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 3: Creating Sequences, Synonyms, and Indexes


Chapter 3 - Page 2
M/sSeed Infotech Ltd

Practice 3-1: Creating Sequences, Synonyms, and Indexes


Overview
This practice provides you with a variety of exercises in creating and using a sequence, an
index, and a synonym.
Note: Execute cleanup_03.sql script from
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

/home/oracle/sql2/code_ex/code_ex_scripts/clean_up_scripts/ before performing the following


tasks.
Tasks
1. Create the DEPT table based on the following table instance chart. Confirm that the table
is created.
Column Name ID NAME
Key Type Primary key
Null/Unique
FK Table
FK Column
s a
Data Type NUMBER VARCHAR2 )h a
o m
Length 7 25
a ilc Guide
@ gm ent
2. You need a sequence that can be used with the PRIMARY
i 5 d of the DEPT
7 KEYtucolumn
table. The sequence should start at 200 and a m a maximum
have S
is value of 1,000. Have your
sequence increment by 10. Name the sequence u
a set t h
DEPT_ID_SEQ.
3. To test your sequence, write a script h g
s insert
to utwo rows in the DEPT table. Name your
r i j e t o
script lab_03_03.sql. Be
i e n setheandsequence
(bsureEducation
to use that you created for the ID

t a m
column. Add two departments:
l i c Administration. Confirm your additions.

G auof your
Run the commands in
a le
your
b
script.
4. Find the
s h names
f e r sequences. Write a query in a script to display the following
r i j e ans
information about your sequences: sequence name, maximum value, increment size,
Band lastn r
-tnumber. Name the script lab_03_04.sql. Run the statement in your script.
n o

5. Create a synonym for your EMPLOYEES table. Call it EMP1. Then find the names of all
synonyms that are in your schema.

6. Drop the EMP1 synonym.


7. Create a nonunique index on the NAME column in the DEPT table.

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

Practices for Lesson 3: Creating Sequences, Synonyms, and Indexes


Chapter 3 - Page 3
M/sSeed Infotech Ltd

8. Create the SALES_DEPT table based on the following table instance chart. Name the
index for the PRIMARY KEY column SALES_PK_IDX. Then query the data dictionary
view to find the index name, table name, and whether the index is unique.
Column Name Team_Id Location

Primary Key Yes


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

Data Type Number VARCHAR2


Length 3 30

9. Drop the tables and sequences created in this practice.

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 3: Creating Sequences, Synonyms, and Indexes


Chapter 3 - Page 4
M/sSeed Infotech Ltd

Solution 3-1: Creating Sequences, Synonyms, and Indexes


1. Create the DEPT table based on the following table instance chart. Confirm that the table is
created.
Column Name ID NAME
Key Type Primary key
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Null/Unique
FK Table
FK Column
Data Type NUMBER VARCHAR2
Length 7 25

CREATE TABLE dept


(id NUMBER(7)CONSTRAINT department_id_pk PRIMARY KEY,
s a
name VARCHAR2(25));
a
) hcommand:
To confirm that the table was created and to view its structure, issue the following
m
co uide
DESCRIBE dept; i l
2. You need a sequence that can be used with the primary key column g maof thentDEPT
G table. The
sequence should start at 200 and have a maximum value7of
i 5 de your sequence
@1,000.tuHave
increment by 10. Name the sequence DEPT_ID_SEQ.
t a m his S
CREATE SEQUENCE dept_id_seq au e t
h g s
START WITH 200
r i j es e to u
INCREMENT BY 10 (b
m i cens
uta ble li
MAXVALUE 1000;
a
G era
h
3. To test
r i je ransBef sure
s
your sequence, write a script to insert two rows in the DEPT table. Name your script
B n-t
lab_03_03.sql. to use the sequence that you created for the ID column. Add two
o Education and Administration. Confirm your additions. Run the commands in
departments:
yournscript.
INSERT INTO dept
VALUES (dept_id_seq.nextval, 'Education');
INSERT INTO dept
VALUES (dept_id_seq.nextval, 'Administration');

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

Practices for Lesson 3: Creating Sequences, Synonyms, and Indexes


Chapter 3 - Page 5
M/sSeed Infotech Ltd

4. Find the names of your sequences. Write a query in a script to display the following
information about your sequences: sequence name, maximum value, increment size, and
last number. Name the script lab_03_04.sql. Run the statement in your script.

SELECT sequence_name, max_value, increment_by, last_number


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

FROM user_sequences;

5. Create a synonym for your EMPLOYEES table. Call it EMP1. Then find the names of all
synonyms that are in your schema.
CREATE SYNONYM emp1 FOR EMPLOYEES;
SELECT *
FROM user_synonyms;

6. Drop the EMP1 synonym.


DROP SYNONYM emp1;
s a
7. Create a nonunique index on the NAME column in the DEPT table.
)h a
CREATE INDEX dept_name_idx ON dept (name);
o m
a ilc Guide
8. Create the SALES_DEPT table based on the following table instance
@ gm chart.
e n tName the index
for the PRIMARY KEY column SALES_PK_IDX. Then query
i 5 7 the data
S t uddictionary view to find
the index name, table name, and whether the index
u t amis unique.
t h is
h a
g use
Column Name
s
ije e to
( b rTeam_Id s
Location

Primary Key m
i Yes c e n
a l
ut ble Number i
G a
Data Type
a VARCHAR2
h sfe r
r i jesLength
a n 3 30
B nTABLE
CREATE
o -tr SALES_DEPT
n PRIMARY KEY USING INDEX
(team_id NUMBER(3)

(CREATE INDEX sales_pk_idx ON


SALES_DEPT(team_id)),
location VARCHAR2(30));
SELECT INDEX_NAME, TABLE_NAME, UNIQUENESS
FROM USER_INDEXES
WHERE TABLE_NAME = 'SALES_DEPT';

9. Drop the tables and sequences created in this practice.


DROP TABLE DEPT;
DROP TABLE SALES_DEPT;
DROP SEQUENCE dept_id_seq;

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

Practices for Lesson 3: Creating Sequences, Synonyms, and Indexes


Chapter 3 - Page 6
M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
Practices for Lesson o m
c uide
4:
i l
Creating Views
g ma nt G
Chapter 4 i57
@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 4: Creating Views


Chapter 4 - Page 1
M/sSeed Infotech Ltd

Practices for Lesson 4: Overview


Practices Overview
This practice covers the following topics:
Creating a simple view
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Creating a complex view


Creating a view with a check constraint
Attempting to modify data in the view
Querying the dictionary views for view information
Removing views

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 4: Creating Views


Chapter 4 - Page 2
M/sSeed Infotech Ltd

Practice 4-1: Creating Views


Overview:
This lessons practice provides you with a variety of exercises in creating, using, querying data
dictionary views for view information, and removing views.
Tasks:
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

1. The staff in the HR department wants to hide some of the data in the EMPLOYEES table.
Create a view called EMPLOYEES_VU based on the employee numbers, employee last
names, and department numbers from the EMPLOYEES table. The heading for the
employee name should be EMPLOYEE.
2. Confirm that the view works. Display the contents of the EMPLOYEES_VU view.

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
3. u t am view,
Using your EMPLOYEES_VU e licwrite a query for the HR department to display all
a b l
G anderdepartment
employee names a numbers.
s h s f
je
Bri n-tran
no

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

Practices for Lesson 4: Creating Views


Chapter 4 - Page 3
M/sSeed Infotech Ltd

4. Department 80 needs access to its employee data. Create a view named DEPT50 that
contains the employee numbers, employee last names, and department numbers for all
employees in department 80. You have been asked to label the view columns EMPNO,
EMPLOYEE, and DEPTNO. For security purposes, do not allow an employee to be
reassigned to another department through the view.
5. Display the structure and contents of the DEPT80view.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
6. Test your h GaAttempt
view. r a bl
to reassign Abel to department 80.
r i jes ransfe
B n-t
no

7. Run lab_04_07.sql to create the dept50 view for this exercise.


You need to determine the names and definitions of all the views in your schema.
Create a report that retrieves view information: the view name and text from the
USER_VIEWS data dictionary view.
Note: The EMP_DETAILS_VIEW was created as part of your schema.
Note: You can see the complete definition of the view if you use Run Script (or press F5) in
SQL Developer. If you use Execute Statement (or press F9) in SQL Developer, scroll
horizontally in the result pane. If you use SQL*Plus, to see more contents of a LONG column,
use the SET LONG n command, where n is the value of the number of characters of the
LONG column that you want to see.

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

Practices for Lesson 4: Creating Views


Chapter 4 - Page 4
M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

8. Remove the views created in this practice.

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 4: Creating Views


Chapter 4 - Page 5
M/sSeed Infotech Ltd

Solution 4-1: Creating Views


1. The staff in the HR department wants to hide some of the data in the EMPLOYEES table.
Create a view called EMPLOYEES_VU based on the employee numbers, employee last
names, and department numbers from the EMPLOYEES table. The heading for the
employee name should be EMPLOYEE.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

CREATE OR REPLACE VIEW employees_vu AS


SELECT employee_id, last_name employee, department_id
FROM employees;

2. Confirm that the view works. Display the contents of the EMPLOYEES_VU view.
SELECT *
FROM employees_vu;

3. Using your EMPLOYEES_VU view, write a query for the HR department to display all
employee names and department numbers.
s a
SELECT employee, department_id
)h a
FROM employees_vu;
o m
a ilc Guide
4. Department 80 needs access to its employee data. Create a view
@ gmnamed e n t
DEPT80 that
contains the employee numbers, employee last names,
i57and d
tuthe viewnumbers
department for all
employees in department 80. They have requested mthat you
ado nottallow S
is an employee to be EMPNO,
label columns
EMPLOYEE, and DEPTNO. For security purposes, u t
a se h
reassigned to another department through h g u
s thetoview.
r i j e
CREATE VIEW dept80(bAS
i e n se
SELECT
t a m lic empno, last_name employee,
employee_id
u le
a department_id
b deptno
G
h sfe r a
jesWHERE
FROM employees
i
r
B nWITH - tranCHECKdepartment_id = 80

no OPTION CONSTRAINT emp_dept_80;

5. Display the structure and contents of the DEPT80 view.


DESCRIBE dept80

SELECT *
FROM dept80;

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

Practices for Lesson 4: Creating Views


Chapter 4 - Page 6
M/sSeed Infotech Ltd

6. Test your view. Attempt to reassign Abel to department 50.


UPDATE dept80
SET deptno = 50
WHERE employee = 'Abel';
The error is because the DEPT50 view has been created with the WITH CHECK OPTION
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

constraint. This ensures that the DEPTNO column in the view is protected from being
changed.
7. Run lab_04_07.sql to create the dept50 view for this exercise. You need to determine
the names and definitions of all the views in your schema. Create a report that retrieves
view information: the view name and text from the USER_VIEWS data dictionary view.
Note: The EMP_DETAILS_VIEW was created as part of your schema.
Note: You can see the complete definition of the view if you use Run Script (or press F5) in
SQL Developer. If you use Execute Statement (or press F9) in SQL Developer, scroll
horizontally in the result pane. If you use SQL*Plus to see more contents of a LONG column,
use the SET LONG n command, where n is the value of the number of characters of the
LONG column that you want to see.
s a
SELECT view_name, text
) h a
FROM user_views;
o m
c uide
i l
8. Remove the views created in this practice. g ma nt G
DROP VIEW employees_vu;
i 5 7@ tude
DROP VIEW dept80; t a m his S
DROP VIEW dept50;
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 4: Creating Views


Chapter 4 - Page 7
M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 4: Creating Views


Chapter 4 - Page 8
M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
Practices for Lesson o m
c uide
5:
i l
Managing Schema
g ma nObjects
t G
Chapter 5 i57
@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 5: Managing Schema Objects


Chapter 5 - Page 1
M/sSeed Infotech Ltd

Practices for Lesson 5: Overview


Practice Overview
This practice covers the following topics:
Adding and dropping constraints
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Deferring constraints
Creating external tables

Note: Before starting this practice, execute /home/oracle/labs/sql2/code_ex/


/cleanup_scripts/cleanup_05.sql script.

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 5: Managing Schema Objects


Chapter 5 - Page 2
M/sSeed Infotech Ltd

Practice 5-1: Managing Schema Objects


Overview
In this practice, you add, drop, and defer constraints. You create external tables.
Note: Execute cleanup_05.sql script from /home/oracle/labs/sql2/code_ex/
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

/cleanup_scripts/ before performing the following tasks.

Tasks

1. Create the DEPT2 table based on the following table instance chart. Enter the syntax in the
SQL Worksheet. Then, execute the statement to create the table. Confirm that the table is
created.

Column Name ID NAME


Key Type
Nulls/Unique
s a
FK Table
) h a
FK Column
c o m e
i l i d
Data type NUMBER
ma nt Gu
VARCHAR2
g
Length 7
i 5 7@25 tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 5: Managing Schema Objects


Chapter 5 - Page 3
M/sSeed Infotech Ltd

2. Populate the DEPT2 table with data from the DEPARTMENTS table. Include only the
columns that you need. Confirm that the rows are inserted.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
)h a
o m
a ilc Guide
3. gm Enter
Create the EMP2 table based on the following table instance chart.
@ e n t
the syntax in the
SQL Worksheet. Then execute the statement to create i 5the
S ud that the table is
7 table.tConfirm
created.
u t am this
h g a sFIRST_NAME
e
Column Name ID
j e s
LAST_NAME
t o u DEPT_ID
i
Key Type
i (br ense
Nulls/Unique
u t am e lic
FK Table G
a abl
es h sfer
FKj
ri tran
Column
BData -
n ontype NUMBER VARCHAR2 VARCHAR2 NUMBER
Length 7 25 25 7

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

Practices for Lesson 5: Managing Schema Objects


Chapter 5 - Page 4
M/sSeed Infotech Ltd

4. Add a table-level PRIMARY KEY constraint to the EMP2 table on the ID column. The
constraint should be named at creation. Name the constraint my_emp_id_pk.
5. Create a PRIMARY KEY constraint to the DEPT2 table using the ID column. The constraint
should be named at creation. Name the constraint my_dept_id_pk.
6. Add a foreign key reference on the EMP2 table that ensures that the employee is not
assigned to a nonexistent department. Name the constraint my_emp_dept_id_fk.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

7. Modify the EMP2 table. Add a COMMISSION column of the NUMBER data type, precision 2,
scale 2. Add a constraint to the COMMISSION column that ensures that a commission value
is greater than zero.
8. Drop the EMP2 and DEPT2 tables so that they cannot be restored.
9. Create an external table library_items_ext. Use the ORACLE_LOADER access driver.
Note: The emp_dir directory and library_items.dat file are already created for this
exercise. library_items.dat has records in the following format:
2354, 2264, 13.21, 150,
2355, 2289, 46.23, 200,
2355, 2264, 50.00, 100,
s a
a. Open the lab_05_09.sql file. Observe the code snippet to create the
)h a
library_items_ext external table. Then replace <TODO1>, <TODO2>, <TODO3>,
o m
ilc Guide
and <TODO4> as appropriate and save the file as lab_05_09_soln.sql. Run the
a
script to create the external table.
g m nt
b. Query the library_items_ext table.
i 5 7 @ t u de
t a m his S
h g au se t
r i j es e to u
i (b ens
10. am a ereport
The HR department tneeds
u lic of the addresses of all departments. Create an external
a
G ID,estreet
table as dept_add_ext using
a l
b the ORACLE_DATAPUMP access driver. The report should
h
show theslocation f r address, city, state or province, and country in the output. Use
r i j e n s
n - t a to produce the results.
aBNATURAL rJOIN
Note:oThe emp_dir directory is already created for this exercise.
n
a. Open the lab_05_10.sql file. Observe the code snippet to create the
dept_add_ext external table. Then, replace <TODO1>, <TODO2>, and <TODO3>
with the appropriate code. Replace <oraxx_emp4.exp> and <oraxx_emp5.exp> with
the appropriate file names. For example, if you are the ora21 user, your file names are
ora21_emp4.exp and ora21_emp5.exp. Save the script as
lab_05_10_soln.sql.
b. Run the lab_05_10_soln.sql script to create the external table.
c. Query the dept_add_ext table.

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

Practices for Lesson 5: Managing Schema Objects


Chapter 5 - Page 5
M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Note: When you perform the preceding step, two files oraxx_emp4.exp and
oraxx_emp5.exp are created under the default directory emp_dir.
11. Create the emp_books table and populate it with data. Set the primary key as deferred and
observe what happens at the end of the transaction.
a. Run the lab_05_11_a.sql file to create the emp_books table. Observe that the
emp_books_pk primary key is not created as deferrable.

s a
b. h a
Run the lab_05_11_b.sql file to populate data into the emp_books table. What do
)
you observe?
o m
c uide
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
ri tran
B - emp_books_pk constraint as deferred. What do you observe?
c. Setnthe
no

d. Drop the emp_books_pk constraint.

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

Practices for Lesson 5: Managing Schema Objects


Chapter 5 - Page 6
M/sSeed Infotech Ltd

e. Modify the emp_books table definition to add the emp_books_pk constraint as


deferrable this time.

f. Set the emp_books_pk constraint as deferred.


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

g. Run the lab_05_11_g.sql file to populate data into the emp_books table. What do
you observe?

h. Commit the transaction. What do you observe?


s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 5: Managing Schema Objects


Chapter 5 - Page 7
M/sSeed Infotech Ltd

Solution 5-1: Managing Schema Objects


Solution
1. Create the DEPT2 table based on the following table instance chart. Enter the syntax in the
SQL Worksheet. Then, execute the statement to create the table. Confirm that the table is
created.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Column Name ID NAME


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

s a
CREATE TABLE dept2
)h a
(id NUMBER(7),
o m
name VARCHAR2(25));
a ilc Guide
g m nt
DESCRIBE dept2
i 5 7 @ t u de
t a m his S
h g au se t
2. Populate the DEPT2 table with data from
r i j ou
es ethetDEPARTMENTS table. Include only the columns
that you need.
i ( b ns
a m dept2
INSERT INTO
t l i c e
G au adepartment_id,
SELECT
b le department_name

es h sfer
FROM departments;
j
Bri n-tran
3. nothe EMP2 table based on the following table instance chart. Enter the syntax in the
Create
SQL Worksheet. Then execute the statement to create the table. Confirm that the table is
created.
Column ID LAST_NAME FIRST_NAME DEPT_ID
Name
Key Type
Nulls/Unique
FK Table
FK Column
Data type NUMBER VARCHAR2 VARCHAR2 NUMBER
Length 7 25 25 7

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

Practices for Lesson 5: Managing Schema Objects


Chapter 5 - Page 8
M/sSeed Infotech Ltd

CREATE TABLE emp2


(id NUMBER(7),
last_name VARCHAR2(25),
first_name VARCHAR2(25),
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

dept_id NUMBER(7));

DESCRIBE emp2

4. Add a table-level PRIMARY KEY constraint to the EMP2 table on the ID column. The
constraint should be named at creation. Name the constraint my_emp_id_pk.
ALTER TABLE emp2
ADD CONSTRAINT my_emp_id_pk PRIMARY KEY (id);

5. Create a PRIMARY KEY constraint to the DEPT2 table using the ID column. The constraint
s a
should be named at creation. Name the constraint my_dept_id_pk.
) h a
ALTER TABLE dept2 m
co uide
i l
ma nt G
ADD CONSTRAINT my_dept_id_pk PRIMARY KEY(id);
g e
6. i 5
Add a foreign key reference on the EMP2 table that ensures 7@that the
t u demployee is not
a m i s S
assigned to a nonexistent department. Name the
g a ut e th
constraint my_emp_dept_id_fk.
s
esh e to u
ALTER TABLE emp2
j
ADD CONSTRAINTrimy_emp_dept_id_fk
b ns REFERENCES dept2(id);
i ((dept_id)
FOREIGN KEY
t a m lice
G au able
7. Modify thehEMP2 table.
j e s s f erAddto the
a COMMISSION column of the NUMBER data type, precision 2,
ri than
scale 2.
Bgreater
Add
t r
a
a n
constraint COMMISSION column that ensures that a commission value
is - zero.
non ALTER TABLE emp2
ADD commission NUMBER(2,2)
CONSTRAINT my_emp_comm_ck CHECK (commission > 0);

8. Drop the EMP2 and DEPT2 tables so that they cannot be restored.
DROP TABLE emp2 PURGE;
DROP TABLE dept2 PURGE;

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

Practices for Lesson 5: Managing Schema Objects


Chapter 5 - Page 9
M/sSeed Infotech Ltd

9. Create an external table library_items_ext. Use the ORACLE_LOADER access driver.


Note: The emp_dir directory and library_items.dat are already created for this
exercise. Ensure that the external file and the database are on the same machine.

library_items.dat has records in the following format:


2354, 2264, 13.21, 150,
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

2355, 2289, 46.23, 200,


2355, 2264, 50.00, 100,
a. Open the lab_05_09.sql file. Observe the code snippet to create the
library_items_ext external table. Then, replace <TODO1>, <TODO2>,
<TODO3>, and <TODO4> as appropriate and save the file as lab_05_09_soln.sql.
Run the script to create the external table.
CREATE TABLE library_items_ext ( category_id number(12)
, book_id number(6)
, book_price number(8,2)
, quantity number(8)
s a
)
)h a
ORGANIZATION EXTERNAL
o m
(TYPE ORACLE_LOADER
a ilc Guide
DEFAULT DIRECTORY emp_dir
@ gm ent
ACCESS PARAMETERS (RECORDS DELIMITED BY NEWLINE
i 5 7
S t ud
u t am this
FIELDS TERMINATED BY ',')
LOCATION ('library_items.dat')
h g a se
)
r i j es e to u
(b ens
REJECT LIMIT UNLIMITED;
i
u t am e lic table.
b. Query the library_items_ext
SELECT G*a
FROM a
r bl
library_items_ext;
h
r i jes ransfe
10. B HR ndepartment
The -t needs a report of addresses of all the departments. Create an external
o
n as dept_add_ext using the ORACLE_DATAPUMP access driver. The report should
table
show the location ID, street address, city, state or province, and country in the output. Use
a NATURAL JOIN to produce the results.
Note: The emp_dir directory is already created for this exercise. Ensure that the external
file and the database are on the same machine.
a. Open the lab_05_10.sql file. Observe the code snippet to create the
dept_add_ext external table. Then, replace <TODO1>, <TODO2>, and <TODO3>
with appropriate code. Replace <oraxx_emp4.exp> and <oraxx_emp5.exp> with
appropriate file names. For example, if you are user ora21, your file names are
ora21_emp4.exp and ora21_emp5.exp. Save the script as lab_5_10_soln.sql.

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

Practices for Lesson 5: Managing Schema Objects


Chapter 5 - Page 10
M/sSeed Infotech Ltd

CREATE TABLE dept_add_ext (location_id,


street_address, city,
state_province,
country_name)
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

ORGANIZATION EXTERNAL(
TYPE ORACLE_DATAPUMP
DEFAULT DIRECTORY emp_dir
LOCATION ('oraxx_emp4.exp','oraxx_emp5.exp'))
PARALLEL
AS
SELECT location_id, street_address, city, state_province,
country_name
FROM locations
NATURAL JOIN countries;
Note: When you perform the preceding step, two files oraxx_emp4.exp and s a
oraxx_emp5.exp are created under the default directory emp_dir.
)h a
b. Run the lab_05_10_soln.sql script to create the external table.co m
a i l u i de
c. Query the dept_add_ext table.
g m nt G
SELECT * FROM dept_add_ext;
i 5 7@ tude
t a m his S
h g au se t
11. Create the emp_books table and populate
j e s ittwith
o udata. Set the primary key as deferred and
r i
observe what happens at the b
i ( e n se
end of the transaction.

t m licscript to create the emp_books table. Observe that the


a. Run the lab_05_11_a.sql
aprimary
emp_books_pk u
a ablekey is not created as deferrable.
G
h sfer
j e s
BriDROP - t r an emp_books CASCADE CONSTRAINTS;
TABLE
on TABLE emp_books (book_id number,
nCREATE title varchar2(20), CONSTRAINT
emp_books_pk PRIMARY KEY (book_id));

b. Run the lab_05_11_b.sql script to populate data into the emp_books table.
What do you observe?
INSERT INTO emp_books VALUES(300,'Organizations');
INSERT INTO emp_books VALUES(300,'Change Management');
The first row is inserted. However, you see the ora-00001 error with the second row
insertion.
c. Set the emp_books_pk constraint as deferred. What do you observe?
SET CONSTRAINT emp_books_pk DEFERRED;
You see the following error: ORA-02447: Cannot defer a constraint that is not deferrable.

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

Practices for Lesson 5: Managing Schema Objects


Chapter 5 - Page 11
M/sSeed Infotech Ltd

d. Drop the emp_books_pk constraint.


ALTER TABLE emp_books DROP CONSTRAINT emp_books_pk;
e. Modify the emp_books table definition to add the emp_books_pk constraint as
deferrable this time.
ALTER TABLE emp_books ADD (CONSTRAINT emp_books_pk PRIMARY KEY
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

(book_id) DEFERRABLE);
f. Set the emp_books_pk constraint as deferred.
SET CONSTRAINT emp_books_pk DEFERRED;
g. Run the lab_05_11_g.sql script to populate data into the emp_books table.
What do you observe?
INSERT INTO emp_books VALUES (300,'Change Management');
INSERT INTO emp_books VALUES (300,'Personality');
INSERT INTO emp_books VALUES (350,'Creativity');
You see that all the rows are inserted.
h. Commit the transaction. What do you observe?
s a
COMMIT;
) h a
m
c uide
o
i l
a point,t because
You see that the transaction is rolled back by the database at this
g m G the
COMMIT failed due to the constraint violation.
7 @ u d en
a m i5
i s St
g a ut e th
e s h o us
b j
ri se t
(
i cen
m
a ut ble li
a
h G era
r i je ransf
s
B n-t
no

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

Practices for Lesson 5: Managing Schema Objects


Chapter 5 - Page 12
M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
Practices for Lesson o m
c uide
6:
i l
Retrieving Data
g maby nUsing
t G
Subqueries
i 5 7@ tude
a m i s S
t
au se t
Chapter 6 h
h g
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 6: Retrieving Data by Using Subqueries


Chapter 6 - Page 1
M/sSeed Infotech Ltd

Practices for Lesson 6: Overview


Practice Overview
This practice covers the following topics:
Creating multiple-column subqueries
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Writing correlated subqueries


Using the EXISTS operator
Using scalar subqueries
Using the WITH clause

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 6: Retrieving Data by Using Subqueries


Chapter 6 - Page 2
M/sSeed Infotech Ltd

Practice 6-1: Retrieving Data by Using Subqueries


Overview
In this practice, you write multiple-column subqueries, and correlated and scalar subqueries.
You also solve problems by writing the WITH clause.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Tasks
1. Write a query to display the last name, department number, and salary of any employee
whose department number and salary both match the department number and salary of any
employee who earns a commission.

s a
a
)h
o m
a ilc Guide
@ gm ent
i 5 7
S t ud
u t am this

h g a se
i j e s to u
2. r
(bjob_ID
Display the last name, department sofeany
name, and salary of any employee whose salary and
job_ID match the salary i
m lic
and e n employee located in location ID 1700.
t a
G au able
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 6: Retrieving Data by Using Subqueries


Chapter 6 - Page 3
M/sSeed Infotech Ltd

3. Create a query to display the last name, hire date, and salary for all employees who have
the same salary and manager_ID as Kochhar.
Note: Do not display Kochhar in the result set.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

4. Create a query to display the employees who earn a salary that is higher than the salary of
all the sales managers (JOB_ID = 'SA_MAN'). Sort the results from the highest to the
lowest.

5. Display details such as the employee ID, last name, and department ID of those s a
employees who live in cities the names of which begin with T. )h a
o m
a ilc Guide
@ gm ent
i 5 7
S t ud
u t am this
6. Write a query to find all employees who earn
h g a moresthan
e the average salary in their
departments. Display last name, salary,
j e u
s to ID, and the average salary for the
department
r i
department. Sort by average b
retrieved by the query as i (salary e n se output.
and round to two decimals. Use aliases for the columns

u t
shown
am e lic in the sample

G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 6: Retrieving Data by Using Subqueries


Chapter 6 - Page 4
M/sSeed Infotech Ltd

7. Find all employees who are not supervisors.


a. First, do this by using the NOT EXISTS operator.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
)h a
m
co uide
a i l

g m nt G
another solution. i 5 de If not, try out using
7@or whytunot?
b. Can this be done by using the NOT IN operator? How,

t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 6: Retrieving Data by Using Subqueries


Chapter 6 - Page 5
M/sSeed Infotech Ltd

8. Write a query to display the last names of the employees who earn less than the average
salary in their departments.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
)h a

o m
a ilc Guide
9. Write a query to display the last names of the employees whog m one nortmore coworkers
have
7 @
in their departments with later hire dates but higher salaries.
i 5 t u de
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 6: Retrieving Data by Using Subqueries


Chapter 6 - Page 6
M/sSeed Infotech Ltd

10. Write a query to display the employee ID, last names, and department names of all the
employees.
Note: Use a scalar subquery to retrieve the department name in the SELECT statement.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
)h a
o m
a ilc Guide
@ gm ent
i 5 7
S t ud
u t am this
h g a se
r i j es e to u
i (b ens
u t am e lic
G a abl
e s h sfer
j
11. Bri a nquery
Write - tratondisplay the department names of those departments whose total salary
costnisoabove one-eighth (1/8) of the total salary cost of the whole company. Use the WITH
clause to write this query. Name the query SUMMARY.

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

Practices for Lesson 6: Retrieving Data by Using Subqueries


Chapter 6 - Page 7
M/sSeed Infotech Ltd

Solution 6-1: Retrieving Data by Using Subqueries


Solution
1. Write a query to display the last name, department number, and salary of any employee
whose department number and salary match the department number and salary of any
employee who earns a commission.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

SELECT last_name, department_id, salary


FROM employees
WHERE (salary, department_id) IN
(SELECT salary, department_id
FROM employees
WHERE commission_pct IS NOT NULL);

2. Display the last name, department name, and salary of any employee whose salary and
job_ID match the salary and job_ID of any employee located in location ID 1700.
SELECT e.last_name, d.department_name, e.salary
s a
FROM employees e JOIN departments d a
)h
o m
ilc Guide
ON e.department_id = d.department_id
AND (salary, job_id) IN a
(SELECT e.salary, e.job_id
@ gm ent
FROM employees e JOINi 5 7
S t ud
departments d
u t am this
ON g a se
e.department_id =
h
d.department_id
r i j es e to u
i (b ens
AND d.location_id = 1700);

u t am e lic
3. Create a query G a displayabthel last name, hire date, and salary for all employees who have
to
the same s hsalary andf r
emanager_ID as Kochhar.
r i j e n s
B Don-not
Note: tradisplay Kochhar in the result set.
o
nSELECT last_name, hire_date, salary
FROM employees
WHERE (salary, manager_id) IN
(SELECT salary, manager_id
FROM employees
WHERE last_name = 'Kochhar')
AND last_name != 'Kochhar';

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

Practices for Lesson 6: Retrieving Data by Using Subqueries


Chapter 6 - Page 8
M/sSeed Infotech Ltd

4. Create a query to display the employees who earn a salary that is higher than the salary of
all the sales managers (JOB_ID = 'SA_MAN'). Sort the results on salary from the highest
to the lowest.

SELECT last_name, job_id, salary


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

WHERE salary > ALL


(SELECT salary
FROM employees
WHERE job_id = 'SA_MAN')
ORDER BY salary DESC;

5. Display details such as the employee ID, last name, and department ID of those
employees who live in cities the names of which begin with T.
SELECT employee_id, last_name, department_id
FROM employees
WHERE department_id IN (SELECT department_id
s a
FROM departments
)h a
o m
ilc Guide
WHERE location_id IN
(SELECT location_id a
FROM locations
@ gm ent
i 5 7
WHERE city LIKE 'T%'));
S t ud
u t am this
6. Write a query to find all employees who h g a moresthan
earn e the average salary in their
s u
department. Sort by average ( r jeandsdepartment
departments. Display last name, isalary,
b
salary e to ID, and the average salary for the
round to two decimals. Use aliases for the columns
retrieved by the queryaasm i cethensample output.
shownliin
a ut e.last_name
b le
h G
SELECT
r a ename, e.salary salary,

r i jes ransfee.department_id deptno, ROUND(AVG(a.salary),2)


B n-t FROM employees e, employees a
dept_avg

no WHERE e.department_id = a.department_id


AND e.salary > (SELECT AVG(salary)
FROM employees
WHERE department_id = e.department_id )
GROUP BY e.last_name, e.salary, e.department_id
ORDER BY AVG(a.salary);

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

Practices for Lesson 6: Retrieving Data by Using Subqueries


Chapter 6 - Page 9
M/sSeed Infotech Ltd

7. Find all employees who are not supervisors.


a. First, do this by using the NOT EXISTS operator.
SELECT outer.last_name
FROM employees outer
WHERE NOT EXISTS (SELECT 'X'
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

FROM employees inner


WHERE inner.manager_id =
outer.employee_id);
b. Can this be done by using the NOT IN operator? How, or why not?
SELECT outer.last_name
FROM employees outer
WHERE outer.employee_id
NOT IN (SELECT inner.manager_id
FROM employees inner);

s a
)h a
This alternative solution is not a good one. The subquery picks up a NULL value, so the
m
entire query returns no rows. The reason is that all conditions that compare a NULL
o
ilc Guide
value result in NULL. Whenever NULL values are likely to be part of the value set, do
a
subquery like the following: @ gm ent
not use NOT IN as a substitute for NOT EXISTS. A much better solution would be a

i 5 7
S t ud
SELECT last_name
FROM employees u t am this
WHERE employee_id NOT IN h g a manager_id
se WHERE manager_id IS NOT
s (SELECT
u
( b rije se to
FROM employees
NULL);
m i cen
u t a
l e li
8. Write a queryG a
to displaya b last names of the employees who earn less than the average
the
h e r
salary instheir
r i je ranSELECTsf
departments.
B n-t last_name
no FROM employees outer
WHERE outer.salary < (SELECT AVG(inner.salary)
FROM employees inner
WHERE inner.department_id
= outer.department_id);

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

Practices for Lesson 6: Retrieving Data by Using Subqueries


Chapter 6 - Page 10
M/sSeed Infotech Ltd

9. Write a query to display the last names of employees who have one or more coworkers in
their departments with later hire dates but higher salaries.
SELECT last_name
FROM employees outer
WHERE EXISTS (SELECT 'X'
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

FROM employees inner


WHERE inner.department_id =
outer.department_id
AND inner.hire_date > outer.hire_date
AND inner.salary > outer.salary);

10. Write a query to display the employee ID, last names, and department names of all
employees.
Note: Use a scalar subquery to retrieve the department name in the SELECT statement.

SELECT employee_id, last_name,


s a
(SELECT department_name
)h a
o m
ilc Guide
FROM departments d
WHERE e.department_id = a
d.department_id ) department
@ gm ent
FROM employees e i 5 7
S t ud
ORDER BY department;
u t am this
h g a se
r i j es e to u
b nsnames of those departments whose total salary
i (department
11. Write a query to displaym
t a the
l i c e
a u ble
cost is above one-eighth (1/8) of the total salary cost of the whole company. Use the WITH
Gthis query.
clause to write
h e ra Name the query SUMMARY.
s
je rans f
Brisummary
WITH

o n -t AS (
n SELECT d.department_name, SUM(e.salary) AS dept_total
FROM employees e JOIN departments d
ON e.department_id = d.department_id
GROUP BY d.department_name)
SELECT department_name, dept_total
FROM summary
WHERE dept_total > ( SELECT SUM(dept_total) * 1/8
FROM summary )
ORDER BY dept_total DESC;

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

Practices for Lesson 6: Retrieving Data by Using Subqueries


Chapter 6 - Page 11
M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 6: Retrieving Data by Using Subqueries


Chapter 6 - Page 12
M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
Practices for Lesson o m
c uide
7:
i l
Manipulating Data
g ma by n t Using
G
Subqueries
i 5 7@ tude
a m i s S
t
au se t
Chapter 7 h
h g
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 7: Manipulating Data by Using Subqueries


Chapter 7 - Page 1
M/sSeed Infotech Ltd

Practices for Lesson 7: Overview


Practices Overview
This practice covers the following topics:
Using subqueries to manipulate data
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Inserting by using a subquery as a target


Using the WITH CHECK OPTION keyword on DML statements
Using correlated subqueries to update and delete rows

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 7: Manipulating Data by Using Subqueries


Chapter 7 - Page 2
M/sSeed Infotech Ltd

Practice 7-1: Manipulating Data by Using Subqueries


Overview
In this practice, you test your knowledge about using subqueries to manipulate data, using the
WITH CHECK OPTION keyword on DML statements, and correlated subqueries to update and
delete rows.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Tasks
1. Which of the following statements are true?
a. Subqueries are used to retrieve data by using an inline view.
b. Subqueries cannot be used to copy data from one table to another.
c. Subqueries update data in one table based on the values of another table.
d. Subqueries delete rows from one table based on rows in another table.

2. Fill in the blanks:


a. You can use a subquery in place of the table name in the ______ clause of the
INSERT statement. s a
)h a
Options:
o m
1) FROM
a ilc Guide
2) INTO
@ gm ent
3) FOR UPDATE
i 5 7
S t ud
4) VALUES
u t am this
h g a se
3. The WITH CHECK OPTION keyword
r i j es e to uyou from changing rows that are not in the
prohibits
subquery.
i (b ens
a. TRUE
t a m lic
b. FALSE u
a able
G
h sfer
j es
ri SELECT
4.BThe
t r anlist of this subquery must have the same number of columns as the
-
noa.n TRUE
column list of the VALUES clause.

b. FALSE

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

Practices for Lesson 7: Manipulating Data by Using Subqueries


Chapter 7 - Page 3
M/sSeed Infotech Ltd

5. You can use a correlated subquery to delete only those rows that also exist in another
table.
a. TRUE
b. FALSE
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

6. To understand the concepts of WITH CHECK OPTION and correlated subqueries, run
the demo files for this practice.

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 7: Manipulating Data by Using Subqueries


Chapter 7 - Page 4
M/sSeed Infotech Ltd

Solution 7-1: Manipulating Data by Using Subqueries


1. Which of the following statements are true?
a. Subqueries are used to retrieve data by using an inline view.
b. Subqueries cannot be used to copy data from one table to another.
c. Subqueries update data in one table based on the values of another table.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

d. Subqueries delete rows from one table based on rows in another table.

Answer: a, c, and d

2. Fill in the blanks:


a. You can use a subquery in place of the table name in the ______ clause of the
INSERT statement.
Options:
1) FROM
2) INTO
s a
3) FOR UPDATE
)h a
4) VALUES
o m
a ilc Guide
Answer: 2
@ gm ent
i 5 7
S t ud
3. The WITH CHECK OPTION keyword prohibits t m fromhichanging
ayou s rows that are not in the
subquery. a u
g use t
s h
a. TRUE
b. FALSE ( b rije se to
m i cen
u t a
l e li
Answer: a G a a b
h e r
r i jes ransf
4.BThe SELECT
-tlist of the
list of this subquery must have the same number of columns as the
o
column
n n VALUES clause.
a. TRUE
b. FALSE

Answer: a

5. You can use a correlated subquery to delete only those rows that also exist in another
table.
a. TRUE
b. FALSE

Answer: a

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

Practices for Lesson 7: Manipulating Data by Using Subqueries


Chapter 7 - Page 5
M/sSeed Infotech Ltd

6. To understand the concepts of WITH CHECK OPTION and correlated subqueries, run
the demo files for this practice.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 7: Manipulating Data by Using Subqueries


Chapter 7 - Page 6
M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
Practices for Lesson o m
c uide
8:
i l
Controlling User
g ma Access
n t G
Chapter 8 i57
@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 8: Controlling User Access


Chapter 8 - Page 1
M/sSeed Infotech Ltd

Practices for Lesson 8: Overview


Practice Overview:
This practice covers the following topics:
Granting other users privileges to your table
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Modifying another users table through the privileges granted to you

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 8: Controlling User Access


Chapter 8 - Page 2
M/sSeed Infotech Ltd

Practice 8-1: Controlling User Access


Overview
You grant query privilege on your table to another user. You learn how to control access to
database objects.
Tasks
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

1. What privilege should a user be given to log on to the Oracle server? Is this a system
privilege or an object privilege?
_________________________________________________________________
2. What privilege should a user be given to create tables?
_________________________________________________________________
3. If you create a table, who can pass along privileges to other users in your table?
_________________________________________________________________
4. You are the DBA. You create many users who require the same system privileges.
What should you use to make your job easier?
_________________________________________________________________
5. What command do you use to change your password?
s a
_________________________________________________________________
)h a
o m
ilc Guide
6. User21 is the owner of the EMP table and grants the DELETE privilege to User22 by using
a
the WITH GRANT OPTION clause. User22 then grants the DELETE privilege on EMP to
gm ent
User23. User21 now finds that User23 has the privilege and revokes it from User22.
@
Which user can now delete from the EMP table?
i 5 7
S t ud
u t am this
_________________________________________________________________
g a se
7. You want to grant SCOTT the privilege to update data in the DEPARTMENTS table. You also
h
r i j es e to u
want to enable SCOTT to grant this privilege to other users. What command do you use?
(b ens
_________________________________________________________________
i
u t am e lic
To complete questionG a 8 and
r a bthel subsequent ones, you need to connect to the database
by using SQL
i j eshDeveloper.
n s fe If you are already not connected, do the following to connect:
r
1.BClick therSQL
t a Developer desktop icon.
2. In o n -
n the Connections Navigator, use the ora21 account and the corresponding
password provided by your instructor to log on to the database.
3. Open another SQL Developer session and connect as ora22.

8. Grant another user query privilege on your table. Then, verify whether that user can use the
privilege.
Note: For this exercise, open another SQL Developer session and connect as a different
user. For example, if you are currently using ora21, open another SQL Developer session
and connect as ora22. Here onwards we would refer the first SQL Developer session as
Team 1 and the second SQL Developer session as Team 2.
a. Grant another user (for example, ora22) privilege to view records in your REGIONS
table. Include an option for this user to further grant this privilege to other users.

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

Practices for Lesson 8: Controlling User Access


Chapter 8 - Page 3
M/sSeed Infotech Ltd

b. Have the user query your REGIONS table.


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

c. Have the user pass on the query privilege to a third user, ora23.
d. Take back the privilege from the user who performs step b.
9. Grant another user query and data manipulation privileges on your COUNTRIES table. Make
sure that the user cannot pass on these privileges to other users.
10. Take back the privileges on the COUNTRIES table granted to another user.
11. Grant another user access to your DEPARTMENTS table. Have the user grant you query
access to his or her DEPARTMENTS table.
12. Query all the rows in your DEPARTMENTS table.

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

...
13. Add a new row to your DEPARTMENTS table. Team 1 should add Education as department
number 500. Team 2 should add Human Resources as department number 510. Query the
other teams table.
14. Create a synonym for the other teams DEPARTMENTS table.
15. Query all the rows in the other teams DEPARTMENTS table by using your synonym.

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

Practices for Lesson 8: Controlling User Access


Chapter 8 - Page 4
M/sSeed Infotech Ltd

Team 1 SELECT statement results:


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

s a
) h a
m
c uide
o
Team 2 SELECT statement results: i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

16. Revoke the SELECT privilege from the other team.


17. Remove the row that you inserted into the DEPARTMENTS table in step 13 and save the
changes.
18. Drop the synonyms team 1 and team 2.

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

Practices for Lesson 8: Controlling User Access


Chapter 8 - Page 5
M/sSeed Infotech Ltd

Solution 8-1: Controlling User Access

1. What privilege should a user be given to log on to the Oracle server? Is this a system or
an object privilege?
The CREATE SESSION system privilege
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

2. What privilege should a user be given to create tables?


The CREATE TABLE privilege

3. If you create a table, who can pass along privileges to other users in your table?
You can, or anyone you have given those privileges to, by using WITH GRANT
OPTION

4. You are the DBA. You create many users who require the same system privileges.
What should you use to make your job easier?
Create a role containing the system privileges and grant the role to the users.
s a
)h a
5. What command do you use to change your password?
o m
The ALTER USER statement
a ilc Guide
g m nt
6. User21 is the owner of the EMP table and grants DELETE
i 5 @ deto User22
privileges
7 DELETEtuprivileges by using
the WITH GRANT OPTION clause. User22 then grants
a m i s S on EMP to
User23. User21 now finds that User23 u
a t the privilege
has th and revokes it from User22.
Which user can now delete data from g
h o us
the EMP e
table?
j e s
Only User21
( b ri se t
i the privilege
7. You want to grant SCOTT
m c e n to update data in the DEPARTMENTS table. You
a
ut SCOTT
also want to enable l i
e to grant this privilege to other users. What command do you
use? a
G era b l
s h sf ON departments TO scott WITH GRANT OPTION;
r i je rUPDATE
GRANT
a n
B n-t
no

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

Practices for Lesson 8: Controlling User Access


Chapter 8 - Page 6
M/sSeed Infotech Ltd

8. Grant another user query privilege on your table. Then, verify whether that user can use
the privilege.
Note: For this exercise, open another SQL Developer session and connect as a different
user. For example, if you are currently using ora21, open another SQL Developer session
and connect as ora22. Here onwards we would refer the first SQL Developer session as
Team 1 and the second SQL Developer session as Team 2.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

a. Grant another user privilege to view records in your REGIONS table. Include an
option for this user to further grant this privilege to other users.
Note: Replace <team2_oraxx> with ora22, <team1_oraxx> with ora21, and
<team3_oraxx> with ora23.
Team 1 executes this statement:
GRANT select
ON regions
TO <team2_oraxx> WITH GRANT OPTION;
b. Have the user query your REGIONS table.
Team 2 executes this statement:
s a
SELECT * FROM <team1_oraxx>.regions;
h a
c. Have the user pass on the query privilege to a third user, ora23. m)
Team 2 executes this statement. i l co uide
GRANT select g ma nt G
ON <team1_oraxx>.regions
5 7 @ tude
TO <team3_oraxx>; i
m his S
t a
h g auwho performs
d. Take back the privilege from the user
s e t step b.
Team 1 executes this statement.s
r i j e e to u
REVOKE select
i ( b ns
ON regions
t a m lice
au able
FROM <team2_oraxx>;
G
h suser
9. Grantsanother
j e f erquery and data manipulation privileges on your COUNTRIES table.
i surerathe
BrMake n user cannot pass on these privileges to other users.
- t
on 1 executes this statement.
Team
nGRANT select, update, insert
ON COUNTRIES
TO <team2_oraxx>;
10. Take back the privileges on the COUNTRIES table granted to another user.
Team 1 executes this statement.
REVOKE select, update, insert ON COUNTRIES FROM <team2_oraxx>;
11. Grant another user access to your DEPARTMENTS table. Have the user grant you query
access to his or her DEPARTMENTS table.
a. Team 2 executes the GRANT statement.
GRANT select
ON departments
TO <team1_oraxx>;

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

Practices for Lesson 8: Controlling User Access


Chapter 8 - Page 7
M/sSeed Infotech Ltd

b. Team 1 executes the GRANT statement.


GRANT select
ON departments
TO <team2_oraxx>;

Here, <team1_oraxx> is the username of Team 1 and <team2_oraxx> is the username of


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

Team 2.
12. Query all the rows in your DEPARTMENTS table.
SELECT *
FROM departments;

13. Add a new row to your DEPARTMENTS table. Team 1 should add Education as
department number 500. Team 2 should add Human Resources as department number
510. Query the other teams table.
a. Team 1 executes this INSERT statement.
INSERT INTO departments(department_id, department_name)
s a
VALUES (500, 'Education'); a
)h
COMMIT; m
co uide
a i l
b. Team 2 executes this INSERT statement.
g m nt G
INSERT INTO departments(department_id,
i 5 7 de
@ tudepartment_name)
VALUES (510, 'Human Resources');
t a m his S
COMMIT;
h g au se t
i j s to u
eteams
14. Create a synonym for the other
( r
b nseDEPARTMENTS table.
a. Team 1 createsm i
a synonym c enamed team 2.
t a l i
au ateam2
CREATE SYNONYM
G b le
s h FOR f r
e<team2_oraxx>.DEPARTMENTS;
j e s
Brb.i nTeam
- tra2ncreates a synonym named team 1.
o
nCREATE SYNONYM team1
FOR <team1_oraxx>. DEPARTMENTS;

15. Query all the rows in the other teams DEPARTMENTS table by using your synonym.
a. Team 1 executes this SELECT statement.
SELECT *
FROM team2;
b. Team 2 executes this SELECT statement.
SELECT *
FROM team1;

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

Practices for Lesson 8: Controlling User Access


Chapter 8 - Page 8
M/sSeed Infotech Ltd

16. Revoke the SELECT privilege from the other team.


a. Team 1 revokes the privilege.
REVOKE select
ON departments
FROM <team2_oraxx>;
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

b. Team 2 revokes the privilege.


REVOKE select
ON departments
FROM <team1_oraxx>;

17. Remove the row that you inserted into the DEPARTMENTS table in step 13 and save the
changes.
a. Team 1 executes this DELETE statement.
DELETE FROM departments
WHERE department_id = 500;
s a
COMMIT;
) h a
b. Team 2 executes this DELETE statement. o m
c uide
i l
DELETE FROM departments
g ma nt G
WHERE department_id = 510;
5 7 @ tude
COMMIT; i
m his S
t a
h g au se t
i j e s to u
18. Drop the synonyms team(b r
1 and team se2.
i
m lic
DROP SYNONYM ateam1; e n
u t
a team2; le
G
DROP SYNONYM
a b
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 8: Controlling User Access


Chapter 8 - Page 9
M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 8: Controlling User Access


Chapter 8 - Page 10
M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
Practices for Lesson o m
c uide
9:
i l
Manipulating Data
g ma nt G
Chapter 9 i57
@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 9: Manipulating Data


Chapter 9 - Page 1
M/sSeed Infotech Ltd

Practices for Lesson 9: Overview


Practice overview:
This practice covers the following topics:
Performing multitable INSERTs
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Performing MERGE operations


Performing flashback operations
Tracking row versions

Note: Before starting this practice, execute /home/oracle/labs/sql2/code_ex/


cleanup_scripts/cleanup_09.sql script.

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 9: Manipulating Data


Chapter 9 - Page 2
M/sSeed Infotech Ltd

Practice 9-1: Manipulating Data


Overview
In this practice, you perform multitable INSERT and MERGE operations, flashback operation, and
track row versions.
Note: Execute cleanup_09.sql script from /home/oracle/labs/sql2/code_ex/
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

cleanup_scripts/ before performing the following tasks.

Tasks
1. Run the lab_09_01.sql script in the lab folder to create the SAL_HISTORY table.
2. Display the structure of the SAL_HISTORY table.

s a
) h a
3. Run the lab_09_03.sql script in the lab folder to create the MGR_HISTORY o mtable. e
4. Display the structure of the MGR_HISTORY table. a ilc Guid
@ gm ent
i 5 7
S t ud
u t am this
h g a se
r i j es e to u
i (b in ethenlab
s folder to create the SPECIAL_SAL table.
5. Run the lab_09_05.sql m script c
6. a
Display the structure e li
utaof theblSPECIAL_SAL table.
G
h sfer a
j es
Bri n-tran
no

7.
a. Write a query to do the following:
Retrieve details such as the employee ID, hire date, salary, and manager ID of those
employees whose employee ID is less than 125 from the EMPLOYEES table.
If the salary is more than $20,000, insert details such as the employee ID and salary
into the SPECIAL_SAL table.
If the salary is less than $20,000:
- Insert details such as the employee ID, hire date, and salary into the
SAL_HISTORY table
- Insert details such as the employee ID, manager ID, and salary into the
MGR_HISTORY table
Copyright 2014, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Manipulating Data


Chapter 9 - Page 3
M/sSeed Infotech Ltd

b. Display the records from the SPECIAL_SAL table.

c. Display the records from the SAL_HISTORY table.


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

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au table.
d. Display the records from the MGR_HISTORY s e t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 9: Manipulating Data


Chapter 9 - Page 4
M/sSeed Infotech Ltd

8.
a. Run the lab_09_08_a.sql script in the lab folder to create the SALES_WEEK_DATA
table.
b. Run the lab_09_08_b.sql script in the lab folder to insert records into the
SALES_WEEK_DATA table.
c. Display the structure of the SALES_WEEK_DATA table.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

d. Display the records from the SALES_WEEK_DATA table.

s a
)h a
o m
ilc Guide
e. Run the lab_09_08_e.sql script in the lab folder to create the EMP_SALES_INFO
table. a
f. Display the structure of the EMP_SALES_INFO table.
@ gm ent
i 5 7
S t ud
u t am this
h g a se
r i j es e to u
i (b ens
u t adomthe following:
e lic
g. Write a query a to
Gdetailsersuch a b l
s h
Retrieve
e s f as ID, week ID, sales quantity on Monday, sales quantity on
j
Bri Tuesday,
n - t r
quantity
aonnsales
Friday
quantity on Wednesday, sales quantity on Thursday, and sales
from the SALES_WEEK_DATA table.
n o
Build a transformation such that each record retrieved from the SALES_WEEK_DATA
table is converted into multiple records for the EMP_SALES_INFO table.
Hint: Use a pivoting INSERT statement.

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

Practices for Lesson 9: Manipulating Data


Chapter 9 - Page 5
M/sSeed Infotech Ltd

h. Display the records from the EMP_SALES_INFO table.


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

9. You have the data of past employees stored in a flat file called emp.data. You want to
store the names and email IDs of all employees, past and present, in a table. To do this,
first create an external table called EMP_DATA using the emp.dat source file in the
emp_dir directory. Use the lab_09_09.sql script to do this.
10. Run the lab_09_10.sql script to create the EMP_HIST table.
a. Increase the size of the email column to 45.
b. Merge the data in the EMP_DATA table created in the last lab into the data in the
EMP_HIST table. Assume that the data in the external EMP_DATA table is the most up-
s a
h a
to-date. If a row in the EMP_DATA table matches the EMP_HIST table, update the email
)
m
c uide
column of the EMP_HIST table to match the EMP_DATA table row. If a row in the
o
i l
EMP_DATA table does not match, insert it into the EMP_HIST table. Rows are
ma nt G
considered matching when the employees first and last names are identical.
g
i 5 7@ tude
c. Retrieve the rows from EMP_HIST after the merge.

t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

...

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

Practices for Lesson 9: Manipulating Data


Chapter 9 - Page 6
M/sSeed Infotech Ltd

11. Create the EMP2 table based on the following table instance chart. Enter the syntax in the
SQL Worksheet. Then execute the statement to create the table. Confirm that the table is
created.

Column ID LAST_NAME FIRST_NAME DEPT_ID


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

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

12. Drop the EMP2 table.


13. Query the recycle bin to see whether the table is present.
s a
14. Restore the EMP2 table to a state before the DROP statement.
)h a
15. Create the EMP3 table using the lab_09_11.sql script. In the EMP3 table,c m
o change ethe
i l u
a thet department
department for Kochhar to 60 and commit your change. Next, change i d for
g m G
Kochhar to 50 and commit your change. Track the changes to
Versions feature. 7 @ en
Kochhar
u d
using the Row

a m 5
i60
i s St
UPDATE emp3 SET department_id
g a ut e th
=
WHERE last_name = 'Kochhar';
e s h o us
COMMIT; i j t
UPDATE emp3 iSET (brdepartment_id
e n s e = 50
m
ta le l=ic'Kochhar';
u
WHERE last_name
a
G erab
COMMIT;
h
r i es ansf
jSELECT
B n-tr VERSIONS_STARTTIME "START_DATE",
o VERSIONS_ENDTIME "END_DATE", DEPARTMENT_ID
nFROM EMP3
VERSIONS BETWEEN SCN MINVALUE AND MAXVALUE
WHERE LAST_NAME ='Kochhar';

16. Drop the EMP2 and EMP3 tables so that they cannot be restored. Check in the recycle bin.

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

Practices for Lesson 9: Manipulating Data


Chapter 9 - Page 7
M/sSeed Infotech Ltd

Solution 9-1: Manipulating Data


Solution
1. Run the lab_09_01.sql script in the lab folder to create the SAL_HISTORY table.
2. Display the structure of the SAL_HISTORY table.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

DESC sal_history

3. Run the lab_09_03.sql script in the lab folder to create the MGR_HISTORY table.
4. Display the structure of the MGR_HISTORY table.
DESC mgr_history

5. Run the lab_09_05.sql script in the lab folder to create the SPECIAL_SAL table.
6. Display the structure of the SPECIAL_SAL table.
DESC special_sal
s a
7.
a
)h
m
a. Write a query to do the following:
a i lco uide
Retrieve details such as the employee ID, hire date, salary,
g mand manager
n t G ID of those
employees whose employee ID is less than 125 from
i 5 7 t u de table.
@the EMPLOYEES
If the salary is more than $20,000, insert details m such as S
the employee ID and salary
t a h i s
into the SPECIAL_SAL table.
h g au se t
If the salary is less than $20,000:
i j s to u
eemployee
- Insert details such as
( b r
the
s e ID, hire date, and salary into the
SAL_HISTORY i
mtable lice n
t a
u such
- Insert a
G
details
a b leas the employee ID, manager ID, and salary into the
e s h sfer
MGR_HISTORY table
j
BriINSERT - t r n
aALL
on special_sal
WHEN
nINTO
SAL > 20000 THEN
VALUES (EMPID, SAL)
ELSE
INTO sal_history VALUES(EMPID,HIREDATE,SAL)
INTO mgr_history VALUES(EMPID,MGR,SAL)
SELECT employee_id EMPID, hire_date HIREDATE,
salary SAL, manager_id MGR
FROM employees
WHERE employee_id < 125;

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

Practices for Lesson 9: Manipulating Data


Chapter 9 - Page 8
M/sSeed Infotech Ltd

b. Display the records from the SPECIAL_SAL table.


SELECT * FROM special_sal;

c. Display the records from the SAL_HISTORY table.


SELECT * FROM sal_history;
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

d. Display the records from the MGR_HISTORY table.


SELECT * FROM mgr_history;

8.
a. Run the lab_09_08_a.sql script in the lab folder to create the SALES_WEEK_DATA
table.
b. Run the lab_09_08_b.sql script in the lab folder to insert records into the
SALES_WEEK_DATA table.
c. Display the structure of the SALES_WEEK_DATA table.
s a
DESC sales_week_data a
)h
m
a i l co uide
d. Display the records from the SALES_WEEK_DATA table.
g m nt G
SELECT * FROM SALES_WEEK_DATA;
i 5 7@ tude
t a m his S
e. Run the lab_09_08_e.sql script in
h g atheulab folder
s e tto create the EMP_SALES_INFO
table.
r i j es e to u
f. Display the structure of (the
i b EMP_SALES_INFO
n s table.
DESC emp_sales_infot am e lic e
u
a abl
G
ha querystofedor the following:
e
g. Write
j s
Bri Retrieve
- t r n such as the employee ID, week ID, sales quantity on Monday, sales
adetails
n on Tuesday, sales quantity on Wednesday, sales quantity on Thursday, and
noquantity
sales quantity on Friday from the SALES_WEEK_DATA table.
Build a transformation such that each record retrieved from the SALES_WEEK_DATA
table is converted into multiple records for the EMP_SALES_INFO table.

Hint: Use a pivoting INSERT statement.


INSERT ALL
INTO emp_sales_info VALUES (id, week_id, QTY_MON)
INTO emp_sales_info VALUES (id, week_id, QTY_TUE)
INTO emp_sales_info VALUES (id, week_id, QTY_WED)
INTO emp_sales_info VALUES (id, week_id, QTY_THUR)
INTO emp_sales_info VALUES (id, week_id, QTY_FRI)

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

Practices for Lesson 9: Manipulating Data


Chapter 9 - Page 9
M/sSeed Infotech Ltd

SELECT ID, week_id, QTY_MON, QTY_TUE, QTY_WED,


QTY_THUR,QTY_FRI FROM sales_week_data;

h. Display the records from the SALES_INFO table.


SELECT * FROM emp_sales_info;
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

9. You have the data of past employees stored in a flat file called emp.data. You want to
store the names and email IDs of all employees past and present in a table. To do this, first
create an external table called EMP_DATA using the emp.dat source file in the emp_dir
directory. You can use the script in lab_09_09.sql to do this.
CREATE TABLE emp_data
(first_name VARCHAR2(20)
,last_name VARCHAR2(20)
, email VARCHAR2(30)
)
s a
ORGANIZATION EXTERNAL ) h a
( o m
c uide
i l
TYPE oracle_loader
g ma nt G
7@ tude
DEFAULT DIRECTORY emp_dir
ACCESS PARAMETERS i 5
m his S
t a
(
h g au se t
es e to u
RECORDS DELIMITED BY NEWLINE CHARACTERSET US7ASCII
NOBADFILE r i j
i (b ens
am e lic
NOLOGFILE
u t
a abl
FIELDS
G
h sfer
( first_name POSITION ( 1:20) CHAR
j es
Bri n-tran
, last_name POSITION (22:41) CHAR
, email POSITION (43:72) CHAR )
no )
LOCATION ('emp.dat') ) ;

10. Run the lab_09_10.sql script to create the EMP_HIST table.


a. Increase the size of the email column to 45.
ALTER TABLE emp_hist MODIFY email varchar(45);

b. Merge the data in the EMP_DATA table created in the last lab into the data in the
EMP_HIST table. Assume that the data in the external EMP_DATA table is the most up-
to-date. If a row in the EMP_DATA table matches the EMP_HIST table, update the email
column of the EMP_HIST table to match the EMP_DATA table row. If a row in the

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

Practices for Lesson 9: Manipulating Data


Chapter 9 - Page 10
M/sSeed Infotech Ltd

EMP_DATA table does not match, insert it into the EMP_HIST table. Rows are
considered matching when the employees first and last names are identical.

MERGE INTO EMP_HIST f USING EMP_DATA h


ON (f.first_name = h.first_name
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

AND f.last_name = h.last_name)


WHEN MATCHED THEN
UPDATE SET f.email = h.email
WHEN NOT MATCHED THEN
INSERT (f.first_name
, f.last_name
, f.email)
VALUES (h.first_name
, h.last_name
, h.email);
s a
c. Retrieve the rows from EMP_HIST after the merge. )h a
o m
SELECT * FROM emp_hist;
a ilc Guide
@ gm ent
11. Create the EMP2 table based on the following table instance
i 5 d the syntax in the
7 chart.tuEnter
a m his
SQL Worksheet. Then execute the statement to create the S
table. Confirm that the table is
created. t
au se t
h g
Column ID
r j es e to uFIRST_NAME DEPT_ID
LAST_NAME
i
Name
i (b ens
Key Type
u t am e lic
Nulls/Unique G a abl
es h sfer
j
FK Table
BFKriColumn
n - t r an
n o
Data type NUMBER VARCHAR2 VARCHAR2 NUMBER
Length 7 25 25 7

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

Practices for Lesson 9: Manipulating Data


Chapter 9 - Page 11
M/sSeed Infotech Ltd

CREATE TABLE emp2


(id NUMBER(7),
last_name VARCHAR2(25),
first_name VARCHAR2(25),
dept_id NUMBER(7));
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

DESCRIBE emp2

12. Drop the EMP2 table.


DROP TABLE emp2;

13. Query the recycle bin to see whether the table is present.
SELECT original_name, operation, droptime
FROM recyclebin;
s a
)h a
o m
14. Restore the EMP2 table to a state before the DROP statement.
a ilc Guide
FLASHBACK TABLE emp2 TO BEFORE DROP; m t
@ g e n
DESC emp2;
i 5 7
S t ud
u t am this
15. g a sscript.
Create the EMP3 table using the lab_09_11.sql
h e In the EMP3 table, change the
j s eTrack
department for Kochhar to 60 andecommit u
to the
your change. Next, change the department for
b
Kochhar to 50 and commit (your richange.
s changes to Kochhar using the Row
Versions feature. i
m lic e n
u t a
a emp3abSET
UPDATE
G le department_id = 60
j es er
hWHERE slast_name
f = 'Kochhar';
Bri n-COMMIT;ran
tUPDATE
no WHERE last_name
emp3 SET department_id = 50
= 'Kochhar';
COMMIT;

SELECT VERSIONS_STARTTIME "START_DATE",


VERSIONS_ENDTIME "END_DATE", DEPARTMENT_ID
FROM EMP3
VERSIONS BETWEEN SCN MINVALUE AND MAXVALUE
WHERE LAST_NAME ='Kochhar';

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

Practices for Lesson 9: Manipulating Data


Chapter 9 - Page 12
M/sSeed Infotech Ltd

16. Drop the EMP2 and EMP3 tables so that they cannot be restored. Check in the recycle bin.
DROP TABLE emp2 PURGE;
DROP TABLE emp3 PURGE;

SELECT original_name, operation, droptime


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

FROM recyclebin;

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 9: Manipulating Data


Chapter 9 - Page 13
M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 9: Manipulating Data


Chapter 9 - Page 14
M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
Practices for Lesson o m
c uide
10:
i l
a Different
Managing Data min t G
g n
Time Zones
i 5 7@ tude
a m i s S
t
au se t
Chapter 10 h
h g
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 10: Managing Data in Different Time Zones


Chapter 10 - Page 1
M/sSeed Infotech Ltd

Practices for Lesson 10: Overview


Practice Overview:
This practice covers using the datetime functions.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Note: Before starting this practice, execute


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

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Practices for Lesson 10: Managing Data in Different Time Zones


Chapter 10 - Page 2
M/sSeed Infotech Ltd

Practice 10-1: Managing Data in Different Time Zones


Overview
In this practice, you display time zone offsets, CURRENT_DATE, CURRENT_TIMESTAMP, and
LOCALTIMESTAMP. You also set time zones and use the EXTRACT function.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Note: Execute cleanup_10.sql script from


/home/oracle/labs/sql2/code_ex/cleanup_scripts/cleanup_10.sql before
performing the following tasks.

Tasks
1. Alter the session to set NLS_DATE_FORMAT to DD-MON-YYYY HH24:MI:SS.
2.
a. Write queries to display the time zone offsets (TZ_OFFSET) for the following time
zones.
US/Pacific-New

s a
) h a
Singapore o m
c uide
i l
g ma nt G
i 5 7@ tude
Egypt
t a m his S
h g au se t
r i j es e to u
i (b ens
u t
b. Alter the session atomset the
e ic
lTIME_ZONE parameter value to the time zone offset of
a
G era
US/Pacific-New. b l
h
e ansf
s
r jsession.
c. Display
i CURRENT_DATE, CURRENT_TIMESTAMP, and LOCALTIMESTAMP for this
B n-tr
no
d. Alter the session to set the TIME_ZONE parameter value to the time zone offset of
Singapore.
e. Display CURRENT_DATE, CURRENT_TIMESTAMP, and LOCALTIMESTAMP for this
session.
Note: The output might be different based on the date when the command is executed.

Note: Observe in the preceding practice that CURRENT_DATE, CURRENT_TIMESTAMP, and


LOCALTIMESTAMP are sensitive to the session time zone.

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

Practices for Lesson 10: Managing Data in Different Time Zones


Chapter 10 - Page 3
M/sSeed Infotech Ltd

3. Write a query to display DBTIMEZONE and SESSIONTIMEZONE.

4. Write a query to extract the YEAR from the HIRE_DATE column of the EMPLOYEES table for
those employees who work in department 80.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
m
c uide
o

i l
g ma nt G
5. Alter the session to set NLS_DATE_FORMAT to DD-MON-YYYY.
i 5 7@ tude
6. Examine and run the lab_10_06.sql script to create
a m the i s S
SAMPLE_DATES table and
populate it. u t
a se t h
h g
s totouthe sysdate.
Note: The screenshot dates will change according
r i j e
( ense
a. Select from the table andbview the data.
i
u t am e lic
G a abl
es h sfer
j
BriModify
b. - t r
theandata type of the DATE_COL column and change it to TIMESTAMP. Select
onthe table to view the data.
nfrom

c. Try to modify the data type of the DATE_COL column and change it to TIMESTAMP
WITH TIME ZONE. What happens?

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

Practices for Lesson 10: Managing Data in Different Time Zones


Chapter 10 - Page 4
M/sSeed Infotech Ltd

7. Create a query to retrieve last names from the EMPLOYEES table and calculate the review
status. If the year hired was 2008, display Needs Review for the review status; otherwise,
display not this year! Name the review status column Review. Sort the results by the
HIRE_DATE column.
Hint: Use a CASE expression with the EXTRACT function to calculate the review status.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates


s a
8. h a
Create a query to print the last names and the number of years of service for each
)
m
c uide
employee. If the employee has been employed for five or more years, print 5 years of
o
i l
service. If the employee has been employed for 10 or more years, print 10 years of
ma nt G
service. If the employee has been employed for 15 or more years, print 15 years of
g
i 5 7@ tude
service. If none of these conditions matches, print maybe next year! Sort the results

t a m his S
by the HIRE_DATE column. Use the EMPLOYEES table.

h g au se t
Hint: Use CASE expressions and TO_YMINTERVAL.

r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

...

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

Practices for Lesson 10: Managing Data in Different Time Zones


Chapter 10 - Page 5
M/sSeed Infotech Ltd

Solution 10-1: Managing Data in Different Time Zones


Solution

1. Alter the session to set NLS_DATE_FORMAT to DD-MON-YYYY HH24:MI:SS.


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

ALTER SESSION SET NLS_DATE_FORMAT =


'DD-MON-YYYY HH24:MI:SS';

2.
a. Write queries to display the time zone offsets (TZ_OFFSET) for the following time
zones: US/Pacific-New, Singapore, and Egypt.
US/Pacific-New
SELECT TZ_OFFSET ('US/Pacific-New') from dual;
Singapore
SELECT TZ_OFFSET ('Singapore') from dual;
s a
Egypt
a
)h
SELECT TZ_OFFSET ('Egypt') from dual;
o m
a ilc Guide
b. Alter the session to set the TIME_ZONE parameter value g tom t offset of
the time zone
@ e n
US/Pacific-New.
i 5 7
S t ud
ALTER SESSION SET TIME_ZONE =m
u t a '-7:00';
t h is
h a
g use
j s
e e to
c. Display CURRENT_DATE, CURRENT_TIMESTAMP,
i and LOCALTIMESTAMP for this
b r s
session.
m i be( different
e n
u t a e lic based on the date when the command is executed.
Note: The output may

G a SELECT
r a bl CURRENT_DATE, CURRENT_TIMESTAMP,
h
jes ransfe
LOCALTIMESTAMP FROM DUAL;
r i
B n-t
o the session to set the TIME_ZONE parameter value to the time zone offset of
d. Alter
nSingapore.
ALTER SESSION SET TIME_ZONE = '+8:00';

e. Display CURRENT_DATE, CURRENT_TIMESTAMP, and LOCALTIMESTAMP for this


session.
Note: The output might be different, based on the date when the command is
executed.
SELECT CURRENT_DATE, CURRENT_TIMESTAMP,
LOCALTIMESTAMP FROM DUAL;

Note: Observe in the preceding practice that CURRENT_DATE, CURRENT_TIMESTAMP, and


LOCALTIMESTAMP are all sensitive to the session time zone.

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

Practices for Lesson 10: Managing Data in Different Time Zones


Chapter 10 - Page 6
M/sSeed Infotech Ltd

3. Write a query to display DBTIMEZONE and SESSIONTIMEZONE.


SELECT DBTIMEZONE,SESSIONTIMEZONE
FROM DUAL;

4. Write a query to extract YEAR from the HIRE_DATE column of the EMPLOYEES table for
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

those employees who work in department 80.


SELECT last_name, EXTRACT (YEAR FROM HIRE_DATE)
FROM employees
WHERE department_id = 80;

5. Alter the session to set NLS_DATE_FORMAT to DD-MON-YYYY.


ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY';

6. Examine and run the lab_10_06.sql script to create the SAMPLE_DATES table and
populate it.
s a
) h a
a. Select from the table and view the data.
o m
c uide
i l
ma nt G
SELECT * FROM sample_dates;
g e
b. Modify the data type of the DATE_COL column and i 5 7@ itttoudTIMESTAMP.
change Select
a m i s S
aut date_col
from the table to view the data.
g e th TIMESTAMP;
ALTER TABLE sample_dates h
j e s MODIFY
t o us
i
(br ense
SELECT * FROM sample_dates;
i
m lic
u t adata
c. Try to modify the
GaZONE. a b le of the DATE_COL column and change it to TIMESTAMP
type
WITHh
s TIME
f e r happens?
What
je rTABLE
BriTIMESTAMP
ALTER
t a ns sample_dates MODIFY date_col
-
non
WITH TIME ZONE;

You are unable to change the data type of the DATE_COL column because the Oracle server
does not permit you to convert from TIMESTAMP to TIMESTAMP WITH TIMEZONE by using the
ALTER statement.

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

Practices for Lesson 10: Managing Data in Different Time Zones


Chapter 10 - Page 7
M/sSeed Infotech Ltd

7. Create a query to retrieve last names from the EMPLOYEES table and calculate the review
status. If the year hired was 2008, display Needs Review for the review status; otherwise,
display not this year! Name the review status column Review. Sort the results by the
HIRE_DATE column.
Hint: Use a CASE expression with the EXTRACT function to calculate the review status.
SELECT e.last_name
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

, (CASE extract(year from e.hire_date)


WHEN 2008 THEN 'Needs Review'
ELSE 'not this year!'
END ) AS "Review "
FROM employees e
ORDER BY e.hire_date;

8. Create a query to print the last names and the number of years of service for each
employee. If the employee has been employed five or more years, print 5 years of
service. If the employee has been employed 10 or more years, print 10 years of
s a
) h a
service. If the employee has been employed 15 or more years, print 15 years of
service. If none of these conditions matches, print maybe next year! Sort the results
m
c uide
o
by the HIRE_DATE column. Use the EMPLOYEES table.
i l
Hint: Use CASE expressions and TO_YMINTERVAL.
g ma nt G
SELECT e.last_name, hire_date, sysdate, @
i 5 7 t u de
(CASE
t a m his S
h g auyearsseoft service'
WHEN (sysdate -TO_YMINTERVAL('15-0'))>=
hire_date THEN
i j s to u
'15
e-TO_YMINTERVAL('10-0'))>=
WHEN (sysdate r
(byears s eservice' hire_date
i n
m lic-eTO_YMINTERVAL('5-0'))>= hire_date
THEN '10 of
WHENta(sysdate
G auTHENab'5leyears of service'
s h sfeELSEr 'maybe next year!'
j e
Bri n-tran END) AS "Awards"
no FROM employees e;

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

Practices for Lesson 10: Managing Data in Different Time Zones


Chapter 10 - Page 8
M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
Additional Practices o m
c uide
and
i l
Solutions
g ma nt G
Chapter 11i57
@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Additional Practices and Solutions


Chapter 11 - Page 1
M/sSeed Infotech Ltd

Additional Practices and Solutions


Practices Overview:
In these practices, you will be working on extra practices that are based on the following topics:
Data manipulation language (DML) statements
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Data definition language (DDL) statements


Datetime functions
Advanced subqueries

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Additional Practices and Solutions


Chapter 11 - Page 2
M/sSeed Infotech Ltd

Additional Practices
Overview
The following exercises can be used for extra practice after you have discussed data
manipulation language (DML) and data definition language (DDL) statements in the lessons
titled Managing Schema Objects and Manipulating Data.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Note: Run the lab_ap_cre_special_sal.sql, lab_ap_cre_sal_history.sql, and


lab_ap_cre_mgr_history.sql scripts in the labs folder to create the SPECIAL_SAL,
SAL_HISTORY, and MGR_HISTORY tables.

Tasks
1. The Human Resources department wants to get a list of underpaid employees, salary
history of employees, and salary history of managers based on an industry salary survey.
So they have asked you to do the following:
Write a statement to do the following:
- Retrieve details such as the employee ID, hire date, salary, and manager ID of those a
employees whose employee ID is more than or equal to 200 from the EMPLOYEES table. a s
h into
m )salary
co uide
- If the salary is less than $5,000, insert details such as the employee ID and
the SPECIAL_SAL table. i l
a SAL_HISTORY
- Insert details such as the employee ID, hire date, and salary g m
into the n t G
table.
i 5 7@ tude
- Insert details such as the employee ID, manager
a S into the MGR_HISTORY
mID, handissalary
table. t
au se t
h g u
2. Query the SPECIAL_SAL, SAL_HISTORY,
records. r i j es eandt o MGR_HISTORY tables to view the inserted

i (b ens
SPECIAL_SAL
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

SAL_HISTORY

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

Additional Practices and Solutions


Chapter 11 - Page 3
M/sSeed Infotech Ltd

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

3. Nita, the DBA, needs you to create a table, which has a primary key constraint, but she
wants the index to have a different name than the constraint. Create the
LOCATIONS_NAMED_INDEX table based on the following table instance chart. Name the
index for the PRIMARY KEY column as LOCATIONS_PK_IDX.
s a
) h a
Column Name Deptno Dname m
c uide
o
i l
Primary Key Yes
g ma nt G
Data Type Number
i 7@ tude
VARCHAR2
5
Length 4 t a m 30 his S
h g au se t
4. j
Query the USER_INDEXES table ito s the
edisplay t o u
INDEX_NAME for the
b r e
i cens
LOCATIONS_NAMED_INDEX(table.
m
a uta ble li
h G era
r i je ransf
s
B n-t
no

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

Additional Practices and Solutions


Chapter 11 - Page 4
M/sSeed Infotech Ltd

The following exercises can be used for extra practice after you have discussed
datetime functions.
You work for a global company and the new vice president of operations wants to know the
different time zones of all the company branches. The new vice president has requested
the following information:
5. Alter the session to set the NLS_DATE_FORMAT to DD-MON-YYYY HH24:MI:SS.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

6.
a. Write queries to display the time zone offsets (TZ_OFFSET) for the following time
zones:
Australia/Sydney

Chile/Easter Island
s a
)h a
o m
a ilc Guide
b. Alter the session to set the TIME_ZONE parameter value g tom
the timen t offset of
zone
Australia/Sydney. 7 @ ud e
i 5 S t
c. Display SYSDATE, CURRENT_DATE, CURRENT_TIMESTAMP,
for this session. u t am this and LOCALTIMESTAMP
h g a stheedate when the command is executed.
es e to u
Note: The output might be different based on
r i j
i (b ens
u t am e lic
G a abl
j es h sIsland.
d. Alter the session
f etor set the TIME_ZONE parameter value to the time zone offset of
BriNote: anresults of the preceding question are based on a different date, and in some
Chile/Easter
- t r
The
on they will not match the actual results that the students get. In addition, the time
ncases,
zone offset of the various countries may differ, based on daylight saving time.
e. Display SYSDATE, CURRENT_DATE, CURRENT_TIMESTAMP, and LOCALTIMESTAMP
for this session.
Note: The output may be different based on the date when the command is executed.

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

Additional Practices and Solutions


Chapter 11 - Page 5
M/sSeed Infotech Ltd

f. Alter the session to set NLS_DATE_FORMAT to DD-MON-YYYY.


Note
Observe in the preceding question that CURRENT_DATE, CURRENT_TIMESTAMP,
and LOCALTIMESTAMP are all sensitive to the session time zone. Observe that
SYSDATE is not sensitive to the session time zone.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

The results of the preceding question are based on a different date, and in some
cases, they will not match the actual results that the students get. In addition, the
time zone offset of the various countries may differ, based on daylight saving time.

7. The Human Resources department wants a list of employees who are up for review in
January, so they have requested you to do the following:
Write a query to display the last names, month of the date of hire, and hire date of those
employees who have been hired in the month of January, irrespective of the year of hire.

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Additional Practices and Solutions


Chapter 11 - Page 6
M/sSeed Infotech Ltd

The following exercises can be used for extra practice after you have discussed
advanced subqueries.
8. The CEO needs a report on the top three earners in the company for profit sharing. You are
responsible to provide the CEO with a list. Write a query to display the top three earners in
the EMPLOYEES table. Display their last names and salaries.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

9. The benefits for the state of California have been changed based on a local ordinance. So
the benefits representative has asked you to compile a list of the people who are affected.
Write a query to display the employee ID and last names of the employees who work in the
state of California.
Hint: Use scalar subqueries.

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Additional Practices and Solutions


Chapter 11 - Page 7
M/sSeed Infotech Ltd

10. Nita, the DBA, wants to remove old information from the database. One of the things she
thinks is unnecessary is the old employment records. She has asked you to do the
following:
Write a query to delete the oldest JOB_HISTORY row of an employee by looking up the
JOB_HISTORY table for the MIN(START_DATE) for the employee. Delete the records of
only those employees who have changed at least two jobs.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Hint: Use a correlated DELETE command.

11. The vice president of Human Resources needs the complete employment records for the
annual employee recognition banquet speech. The vice president makes a quick phone call
to stop you from following the DBAs orders.

Roll back the transaction.

12. The sluggish economy is forcing management to take cost reduction actions. The CEO
wants to review the highest paid jobs in the company. You are responsible to provide the
CEO with a list based on the following specifications:
s
Write a query to display the job IDs of those jobs whose maximum salary is above half the a
) h a
maximum salary in the entire company. Use the WITH clause to write this query. Name the
query MAX_SAL_CALC. o m
c uide
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Additional Practices and Solutions


Chapter 11 - Page 8
M/sSeed Infotech Ltd

Additional Practices Solutions


Solution
The following exercises can be used for extra practice after you have discussed data
manipulation language (DML) and data definition language (DDL) statements in the lessons
titled Managing Schema Objects and Manipulating Data.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

Note: Run the lab_ap_cre_special_sal.sql, lab_ap_cre_sal_history.sql, and


lab_ap_cre_mgr_history.sql scripts in the labs folder to create the SPECIAL_SAL,
SAL_HISTORY, and MGR_HISTORY tables
1. The Human Resources department wants to get a list of underpaid employees, salary
history of employees, and salary history of managers based on an industry salary survey.
So they have asked you to do the following:
Write a statement to do the following:
- Retrieve details such as the employee ID, hire date, salary, and manager ID of those
employees whose employee ID is more than or equal to 200 from the EMPLOYEES
table.
a
- If the salary is less than $5,000, insert details such as the employee ID and salary
s
into the SPECIAL_SAL table.
) h a
- Insert details such as the employee ID, hire date, and salary into the m e
coSAL_HISTORY
table. i l
a t Gu i d
- Insert details such as the employee ID, manager ID, and g m
salary into n the
@ d e
MGR_HISTORY table.
m i57 Stu
INSERT ALL
a u ta this
WHEN SAL < 5000 THEN
s h g use
INTO special_sal VALUES
b r ije (EMPID,
e to SAL)
ELSE (
i cen s
t a m li
a u
INTO sal_history
e
VALUES(EMPID,HIREDATE,SAL)
l
G erabVALUES(EMPID,MGR,SAL)
INTO mgr_history
h
r i
SELECT
n sf
jes raemployee_id EMPID, hire_date HIREDATE,
B n-t salary SAL, manager_id MGR
o employees
nFROM
WHERE employee_id >=200;

2. Query the SPECIAL_SAL, SAL_HISTORY, and the MGR_HISTORY tables to view the
inserted records.
SELECT * FROM special_sal;
SELECT * FROM sal_history;
SELECT * FROM mgr_history;

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

Additional Practices and Solutions


Chapter 11 - Page 9
M/sSeed Infotech Ltd

3. Nita, the DBA, needs you to create a table, which has a primary key constraint, but she
wants the index to have a different name than the constraint. Create the
LOCATIONS_NAMED_INDEX table based on the following table instance chart. Name the
index for the PRIMARY KEY column as LOCATIONS_PK_IDX.

Column Name Deptno Dname


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

Primary Key Yes


Data Type Number VARCHAR2
Length 4 30

CREATE TABLE LOCATIONS_NAMED_INDEX


(location_id NUMBER(4) PRIMARY KEY USING INDEX
(CREATE INDEX locations_pk_idx ON
LOCATIONS_NAMED_INDEX(location_id)),
location_name VARCHAR2(20)); s a
h a
Query the USER_INDEXES table to display the INDEX_NAME for the lco
m) e
4.
a i u id
LOCATIONS_NAMED_INDEX table.
gm ent G
SELECT INDEX_NAME, TABLE_NAME
5 7 @ t ud
i S
FROM USER_INDEXES
u t am this
h g a se
WHERE TABLE_NAME = 'LOCATIONS_NAMED_INDEX';

r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Additional Practices and Solutions


Chapter 11 - Page 10
M/sSeed Infotech Ltd

The following exercises can be used for extra practice after you have discussed datetime
functions.
You work for a global company and the new vice president of operations wants to know the
different time zones of all the company branches. The new vice president has requested the
following information:
5. Alter the session to set NLS_DATE_FORMAT to DD-MON-YYYY HH24:MI:SS.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

ALTER SESSION
SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';

6.
a. Write queries to display the time zone offsets (TZ_OFFSET) for the following time
zones:
Australia/Sydney
SELECT TZ_OFFSET ('Australia/Sydney') from dual;
Chile/Easter Island
SELECT TZ_OFFSET ('Chile/EasterIsland') from dual; s a
)h a
m
o offset
b. Alter the session to set the TIME_ZONE parameter value to the time
a i l czone u i deof
Australia/Sydney.
g m nt G
ALTER SESSION SET TIME_ZONE = '+10:00'; @
i 5 7 t u de
t a m his S
h g au se t
c. Display SYSDATE, CURRENT_DATE, CURRENT_TIMESTAMP, and LOCALTIMESTAMP
for this session.
j es based
t o u
r i
Note: The output may be different
b nse the date when the command is executed.
on
i ( e
SELECT SYSDATE,
t a mFROM lDUAL;
i c
CURRENT_DATE, CURRENT_TIMESTAMP,
LOCALTIMESTAMP
G au able
es h sfer
j
d. riAlter the a
r n to set the TIME_ZONE parameter value to the time zone offset of
session
B Chile/Easter
- t
on The results
nNote:
Island.
of the preceding question are based on a different date, and in some
cases, they will not match the actual results that the students get. In addition, the time
zone offset of the various countries may differ, based on daylight saving time.
ALTER SESSION SET TIME_ZONE = '-06:00';

e. Display SYSDATE, CURRENT_DATE, CURRENT_TIMESTAMP, and LOCALTIMESTAMP


for this session.
Note: The output may be different based on the date when the command is executed.
SELECT SYSDATE, CURRENT_DATE, CURRENT_TIMESTAMP,
LOCALTIMESTAMP FROM DUAL;

f. Alter the session to set NLS_DATE_FORMAT to DD-MON-YYYY.


ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY';

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

Additional Practices and Solutions


Chapter 11 - Page 11
M/sSeed Infotech Ltd

Note
Observe in the preceding question that CURRENT_DATE, CURRENT_TIMESTAMP, and
LOCALTIMESTAMP are all sensitive to the session time zone. Observe that SYSDATE is
not sensitive to the session time zone.
The results of the preceding question are based on a different date, and in some cases,
they will not match the actual results that the students get. In addition, the time zone
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

offset of the various countries may differ, based on daylight saving time.

7. The Human Resources department wants a list of employees who are up for review in
January, so they have requested you to do the following:
Write a query to display the last names, month of the date of hire, and hire date of those
employees who have been hired in the month of January, irrespective of the year of hire.
SELECT last_name, EXTRACT (MONTH FROM HIRE_DATE), HIRE_DATE
FROM employees
WHERE EXTRACT (MONTH FROM HIRE_DATE) = 1;

The following exercises can be used for extra practice after you have discussed
s a
advanced subqueries.
) h a
8. o m
c uide
The CEO needs a report on the top three earners in the company for profit sharing. You are
i l
responsible to provide the CEO with a list. Write a query to display the top three earners in
ma nt G
the EMPLOYEES table. Display their last names and salaries.
g
SELECT last_name, salary
i 5 7@ tude
FROM employees e
t a m his S
g u (*)
aCOUNT e t
WHERE 3 > (SELECT
h
s to u
FROM jeemployees
s
r i
i
WHERE
e n se < salary);
(b e.salary
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Additional Practices and Solutions


Chapter 11 - Page 12
M/sSeed Infotech Ltd

9. The benefits for the state of California have been changed based on a local ordinance. So
the benefits representative has asked you to compile a list of the people who are affected.
Write a query to display the employee ID and last names of the employees who work in the
state of California.
Hint: Use scalar subqueries.
SELECT employee_id, last_name
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

FROM employees e
WHERE ((SELECT location_id
FROM departments d
WHERE e.department_id = d.department_id )
IN (SELECT location_id
FROM locations l
WHERE state_province = 'California'));

10. Nita, the DBA, wants to remove old information from the database. One of the things she
s a
) h a
thinks is unnecessary is the old employment records. She has asked you to do the
following:
m
c uide
o
i l
Write a query to delete the oldest JOB_HISTORY row of an employee by looking up the
ma nt G
JOB_HISTORY table for the MIN(START_DATE) for the employee. Delete the records of
g
i 5 7@ tude
only those employees who have changed at least two jobs.
Hint: Use a correlated DELETE command.
t a m his S
DELETE FROM job_history s h
JH gau use t
b
WHERE employee_id
( rije= se to
m i ceemployee_id
(SELECT n
a l i
ut bleFROM employees E
a
G era WHERE JH.employee_id = E.employee_id
h
r i je ransf
s AND START_DATE = (SELECT MIN(start_date)
B n-t
no
FROM job_history JH
WHERE JH.employee_id =
E.employee_id)
AND 3 > (SELECT COUNT(*)
FROM job_history JH
WHERE JH.employee_id =
E.employee_id
GROUP BY EMPLOYEE_ID
HAVING COUNT(*) >= 2));

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

Additional Practices and Solutions


Chapter 11 - Page 13
M/sSeed Infotech Ltd

11. The vice president of Human Resources needs the complete employment records for the
annual employee recognition banquet speech. The vice president makes a quick phone call
to stop you from following the DBAs orders.

Roll back the transaction.


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

ROLLBACK;

12. The sluggish economy is forcing management to take cost reduction actions. The CEO
wants to review the highest paid jobs in the company. You are responsible to provide the
CEO with a list based on the following specifications:
Write a query to display the job IDs of those jobs whose maximum salary is above half the
maximum salary in the entire company. Use the WITH clause to write this query. Name the
query MAX_SAL_CALC.
WITH
MAX_SAL_CALC AS (SELECT job_title, MAX(salary) AS
job_total
s a
FROM employees, jobs
) h a
WHERE employees.job_id = jobs.job_id
o m
c uide
GROUP BY job_title) i l
SELECT job_title, job_total g ma nt G
FROM MAX_SAL_CALC
i 5 7@ tude
a m his S
WHERE job_total > (SELECT MAX(job_total) * 1/2
t
FROM MAX_SAL_CALC)
h g au se t
j es e to u
ORDER BY job_total DESC;
r i
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Additional Practices and Solutions


Chapter 11 - Page 14
M/sSeed Infotech Ltd

Additional Practices: Case Study

In the case study for the SQL WORKSHOP I course, you built a set of database tables for an
Online Book Store application. In addition, you inserted, updated, and deleted records in an
online book store database and generated a report.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

The following is a diagram of the tables and columns that you created for the video application:

s a
)h a
o m
a ilc Guide
@ gm ent
i 5 7
S t ud
u t am this
g a se
Note: First, run the Online_Book_Store_Drop_Tables.sql
h script in the labs folder to drop
s u
labs folder to create and populate(b
rijeOnline_Book_Store_Populate.sql
tables if they already exist. Then run the
the tables.se
to script in the

m i cen
a ut ble li
a
h G era
r i je ransf
s
B n-t
no

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

Additional Practices and Solutions


Chapter 11 - Page 15
M/sSeed Infotech Ltd

1. Verify that the tables were created properly by running a report to show the list of tables
and their column definitions.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Additional Practices and Solutions


Chapter 11 - Page 16
M/sSeed Infotech Ltd

2. Verify the existence of the ORDER_ID_SEQ sequence in the data dictionary.


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

3. You want to create some users who have access only to their purchase history. Create a
user called Carmen and grant her the privilege to select from the PURCHASE_HISTORY
table.
Note: Make sure to prefix the username with your database account. For example, if you
are the user oraxx, create a user called oraxx_Carmen.
4. Add an edition column (varchar2 (6)) to the BOOKS table to store the book edition
information.
5. Add a CREDIT_CARD_TYPE table to store CREDIT_CARD_TYPE and
CREDIT_CARD_DESCRIPTION. The table has a foreign key with the CREDIT_CARD_TYPE
column in the CREDIT_CARD_DETAILS table.
s a
6. Select all the tables from the data dictionary.
) h a
7. Create a SHOPPING_HISTORY table to store the details of purchase history of the
m
customers.
i l c uide
o
(Hint: You can copy the PURCHASE_HISTORY table.)
g ma nt G
8.
7@ tude
Display the customer details of the first ten customers who have placed orders in the last
i 5
t a m his S
month. Order the records based on the customer ID.

h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
9. Show a s
j e list
s f er who have placed an order more than one time.
hof customers
Bri n-tran
no

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

Additional Practices and Solutions


Chapter 11 - Page 17
M/sSeed Infotech Ltd

Additional Practices Solution: Case Study


Solution
First, run the Online_Book_Store_Drop_Tables.sql script in the labs folder to drop tables
if they already exist. Then run the Online_Book_Store_Populate.sql script in the labs
folder to create and populate the tables.
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

1. Verify that the tables were created properly by running a report to show the list of tables
and their column definitions.
SELECT table_name,column_name,data_type,nullable
FROM user_tab_columns
WHERE table_name
IN('CUSTOMER','CREDIT_CARD_DETAILS','SHOPPING_CART',
'ORDER_DETAILS','BOOKS','AUTHOR','PUBLISHER','SHIPPING_TYPE',
'PURCHASE_HISTORY');

2. Verify the existence of the ORDER_ID_SEQ sequences in the data dictionary.


s a
SELECT sequence_name FROM user_sequences; a
)h
m
o ide
3. You want to create some users who have access only to their purchasea ilchistory.
G uCreate a
g mPURCHASE_HISTORY
t
user called Carmen and grant her the privilege to select from the
7 @ u d en
table.
Note: Make sure to prefix the username with your a m i5 account.
database i s St For example, if you
a ut e th
are the user oraxx, create a user called oraxx_Carmen.
g
CREATE USER oraxx_carmen
j e s t o us BY oracle ;
hIDENTIFIED
i
i (br ense TO oraxx_carmen;
GRANT select ON purchase_history

u t am e lic
4. G
Add an edition a (varchar2
column
r a bl (6)) to the BOOKS table to store the book edition
r esh ansfe
information.
jALTER
i
B n-trTABLE books ADD(edition VARCHAR2(6));
no
5. Add a CREDIT_CARD_TYPE table to store CREDIT_CARD_TYPE and
CREDIT_CARD_DESCRIPTION. The table has a foreign key with the CREDIT_CARD_TYPE
column in the CREDIT_CARD_DETAILS table.
CREATE TABLE CREDIT_CARD_TYPE
( CREDIT_CARD_TYPE VARCHAR2(10) NOT NULL ENABLE,
CREDIT_CARD_DESCRIPTION VARCHAR2(4000 BYTE),
CONSTRAINT CREDIT_CARD_TYPE_PK PRIMARY KEY
(CREDIT_CARD_TYPE))
;

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

Additional Practices and Solutions


Chapter 11 - Page 18
M/sSeed Infotech Ltd

6. Select all the tables from the data dictionary.


SELECT table_name FROM user_tables order by table_name;

7. Create a SHOPPING_HISTORY table to store the details of a purchase history of customers.


(Hint: You can copy the PURCHASE_HISTORY table.)
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

CREATE TABLE shopping_history as select * from purchase_history


where '1' = '1';

8. Display the customer details of the first ten customers who have placed orders in the last
month. Order the records based on the customer ID.
SELECT o.CUSTOMER_ID, o.ORDER_ID, o.DATE_OF_PURCHASE,
c.CUSTOMER_NAME
FROM ORDER_DETAILS o JOIN PURCHASE_HISTORY p
ON o.CUSTOMER_ID = p.CUSTOMER_ID JOIN CUSTOMER c
ON o.CUSTOMER_ID= c.CUSTOMER_ID
AND rownum < 10
s a
ORDER BY CUSTOMER_ID;
) h a
9. Show a list of customers who have placed an order more than one time.com d e
i l i
SELECT customer_id, customer_name FROM customer
g ma c nt Gu
WHERE 1 <= (select count(*) from purchase_history
i 5 7@ tude where
customer_id = c.customer_id);
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Additional Practices and Solutions


Chapter 11 - Page 19
M/sSeed Infotech Ltd
Unauthorized reproduction or distribution prohibited Copyright 2014, Oracle and/or its affiliates

s a
) h a
m
c uide
o
i l
g ma nt G
i 5 7@ tude
t a m his S
h g au se t
r i j es e to u
i (b ens
u t am e lic
G a abl
es h sfer
j
Bri n-tran
no

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

Additional Practices and Solutions


Chapter 11 - Page 20

You might also like