Introduction To Oracle 11g SQL Programming: Student Workbook
Introduction To Oracle 11g SQL Programming: Student Workbook
Introduction To Oracle 11g SQL Programming: Student Workbook
Student Workbook
Introduction to Oracle 11g SQL Programming
Published by ITCourseware, LLC, 7245 South Havana Street, Suite 100, Centennial, CO 80112
Special thanks to: Many instructors whose ideas and careful review have contributed to the quality of this
workbook, including Elizabeth Boss, Denise Geller, Jennifer James, Julie Johnson, Roger Jones, Joe
McGlynn, Jim McNally, and Kevin Smith, and the many students who have offered comments, suggestions,
criticisms, and insights.
Copyright © 2009 by ITCourseware, LLC. All rights reserved. No part of this book may be reproduced or
utilized in any form or by any means, electronic or mechanical, including photo-copying, recording, or by an
information storage retrieval system, without permission in writing from the publisher. Inquiries should be
addressed to ITCourseware, LLC, 7245 South Havana Street, Suite 100, Centennial, Colorado, 80112.
(303) 302-5280.
All brand names, product names, trademarks, and registered trademarks are the property of their
respective owners.
Contents
Chapter 1 - Course Introduction ............................................................................................................. 7
Course Objectives ............................................................................................................................ 8
Course Overview ........................................................................................................................... 10
Using the Workbook ...................................................................................................................... 11
Suggested References ..................................................................................................................... 12
Course Objectives
Course Overview
Student Materials:
Student workbook
Classroom Environment:
Oracle 11g
This workbook design is based on a page-pair, consisting of a Topic page and a Support page. When you
lay the workbook open flat, the Topic page is on the left and the Support page is on the right. The Topic
page contains the points to be discussed in class. The Support page has code examples, diagrams, screen
shots and additional information. Hands On sections provide opportunities for practical application of key
concepts. Try It and Investigate sections help direct individual discovery.
In addition, there is an index for quick look-up. Printed lab solutions are in the back of the book as well as
on-line if you need a little help.
third ()level
Whenpoints.
the servlet is unloaded, the container calls the destroy()
public void service(ServletRequest request,
ServletResponse response) throws ServletException, IOException
method. {
...
// Write the document
As with Java’s finalize() method, don’t count on this being
called.
Callout boxes point out
out.println("This servlet was born on " + bornOn.toString());
out.println("It is now " + today.toString());
super.init(config);
Suggested References
Celko, Joe. 2005. Joe Celko's SQL for Smarties: Advanced SQL Programming. Academic Press/
Morgan Kaufman, San Francisco, CA. ISBN 0123693799
Celko, Joe. 2006. Joe Celko's SQL Puzzles and Answers. Morgan Kaufmann, San Francisco, CA.
ISBN 0123735963
Churcher, Clare. 2008. Beginning SQL Queries: From Novice to Professional. Apress, Inc.,
Berkeley, CA. ISBN 9781590599433
Date, C.J. and Hugh Darwen. 1996. A Guide to The SQL Standard, Fourth Edition. Addison-
Wesley, Reading, MA. ISBN 0201964260
Freeman, Robert G. 2004. Oracle Database 10g New Features. McGraw-Hill Osborne Media,
Emeryville, CA. ISBN 0072229470
Gennick, Jonathan. 2004. Oracle Sql*Plus Pocket Reference, Third Edition. O'Reilly & Associates,
Sebastopol, CA. ISBN 0596008856
Gennick, Jonathan. 2004. Oracle SQL*Plus: The Definitive Guide, Second Edition. O'Reilly &
Associates, Sebastopol, CA. ISBN 0596007469
Gruber, Martin. 2000. SQL Instant Reference, Second Edition. SYBEX, Alameda, CA.
ISBN 0782125395
Kline, Kevin. 2004. SQL in a Nutshell, Second Edition. O'Reilly & Associates, Sebastopol, CA.
ISBN 0596004818
Kreines, David. 2003. Oracle Data Dictionary Pocket Reference. O'Reilly & Associates, Sebastopol,
CA. ISBN 0596005172
Loney, Kevin. 2004. Oracle Database 10g: The Complete Reference. McGraw-Hill Osborne Media,
ISBN 0072253517
Mishra, Sanjay. 2004. Mastering Oracle SQL, Second Edition. O'Reilly & Associates, Sebastopol,
CA. ISBN 0596006322
http://tahiti.oracle.com http://www.oracle.com
http://www.dbasupport.com http://www.searchdatabase.com
http://www.hot-oracle.com http://www.toadworld.com
Your single most important reference is the SQL Reference book, which is part of the Oracle Database
Online Documentation. You may have received this on CD-ROM with your Oracle distribution. If not, you
can access it online at Oracle's web site. This is the official, complete description of Oracle's implementation
of SQL. It includes many examples and discussions.
http://tahiti.oracle.com/
Find the documentation for your version of Oracle. Locate the SQL Reference, and open the HTML table
of contents.
If you have web access in the classroom, open a browser now and find the SQL Reference. Set a browser
bookmark, and have the SQL Reference at hand throughout this class.
Objectives
A SELECT statement may make use of several clauses, but minimally must
include the following two:
The SELECT clause specifies which data values will be retrieved, and will be
followed by either an item_list or a *.
Oracle will return each item in item_list under a column heading of the
same name, unless an alias is specified.
The FROM clause specifies one or more sources, typically tables, from which
to retrieve data.
A heading may be overridden with a column alias, a word used to replace the
default heading.
product.sql
SELECT description name,
price orig_price,
price * .75 sales_price
FROM product;
The SELECT statement may query one or many tables. The data that is retrieved may be thought of as a
virtual table (i.e., one that exists in memory only until the query completes). This virtual table is also
referred to as the query's result set.
The SELECT statement can be used to retrieve data from any or all columns from a table. For example,
the following SELECT will display a list of everything about every store in the database:
store.sql
SELECT *
FROM store;
The query below will list each state (once) in which our company has stores:
store2.sql
SELECT DISTINCT state
FROM store;
store3.sql
SELECT store_number, city, state
FROM store;
Note:
Oracle allows column aliases to contain spaces. You must use double quotes if the alias includes one or
more spaces.
product2.sql
SELECT description AS name,
price AS orig_price,
price * .75 AS "Sales Price"
FROM product;
CASE [expression]
WHEN value THEN result
WHEN value THEN result
ELSE result
END;
The simple CASE expression evaluates one expression and compares it for
equality with the value of each of the WHEN clauses.
simple_case.sql
SELECT id, pay_amount, CASE pay_type_code
WHEN 'S' THEN 'Salaried'
WHEN 'C' THEN 'Commissioned'
WHEN 'T' THEN 'Temporary'
WHEN 'H' THEN 'Hourly'
ELSE 'Unknown Pay Type'
END
FROM employee;
A searched CASE evaluates the condition in each of the WHEN clauses, taking
the first one that's true.
searched_case.sql
SELECT id, pay_amount,
CASE WHEN pay_type_code='S' THEN 'Salaried'
WHEN pay_type_code='C' THEN 'Commissioned'
WHEN pay_type_code='T'
AND pay_amount < 8 THEN 'Poorly Paid Temporary'
WHEN pay_type_code='T' THEN 'Temporary'
WHEN pay_type_code='H' THEN 'Hourly'
ELSE 'Unknown Pay Type'
END
FROM employee;
Page 62 Rev 04-29-09 ©2009 ITCourseware, LLC
Chapter 4 SQL Queries — The SELECT Statement
A simple CASE expression can be rewritten as a searched CASE, but a searched CASE can't always be
rewritten as a simple CASE:
searched_case2.sql
SELECT account_number, account_name, balance,
CASE WHEN balance > credit_limit - 100
THEN 'Reaching Limit'
END warning, credit_limit
FROM account;
Other Functions
Before implementing the ANSI-standard CASE construct, Oracle supplied other functions. You will still
find these used in current and legacy applications, though developers will probably choose the CASE
expression for new code.
NVL() will replace a null value with another value, or leave a non-null value alone.
nvl.sql
SELECT id, NVL(store_number, 999) store FROM employee;
coalesce.sql
SELECT COALESCE(delivery_date, est_delivery_date) delivery_date
FROM order_header;
DECODE() is more general than NVL() in that it will search through a list of values to determine what
value to return. Values not found will return NULL.
decode.sql
SELECT DECODE(state, NULL, '?', 'UT', 'Utah') state FROM vendor;
NULLIF() will return a null if both values are the same; otherwise, it will return the first value.
nullif.sql
SELECT product_id, NULLIF(quantity_on_hand, 0) quantity FROM inventory;
Use the WHERE clause when only a subset of all the rows in a table is
required.
SELECT {item_list | *}
FROM table
[WHERE conditions];
conditions will be one or more expressions that will evaluate to either true, false,
or neither (null).
If the WHERE clause evaluates to true, then the current row is returned
in the result set.
= equal to
Any character string values in conditions must be enclosed within single quotes.
To display all information for each store with a store number less than 4, enter the following:
store4.sql
SELECT *
FROM store
WHERE store_number < 4;
To display each store's number, location, and phone number in the state of Nevada, enter the following:
store5.sql
SELECT store_number, street, city, area_code, phone_number
FROM store
WHERE state = 'NV';
NULL Values
person2.sql
SELECT *
FROM person
WHERE mi IS NULL;
person3.sql
SELECT *
FROM person
WHERE phone_number IS NOT NULL;
NULL is not the same as a "false" value, but it isn't a "true" value, either.
person4.sql
SELECT *
FROM person
WHERE phone_number = NULL;
This will never be true, even for rows with null values in the
phone_number column!
To display a list of people who have middle initials, enter the following:
person5.sql
SELECT lastname, firstname, mi, area_code, phone_number
FROM person
WHERE mi IS NOT NULL;
employee.sql
SELECT id
FROM employee
WHERE supervisor_id != 7881 OR
supervisor_id IS NULL;
Compound Expressions
AND will result in true if both conditions are true for a row.
The logical operators are evaluated based on precedence: NOT has the highest
precedence, then AND, and then OR.
If a WHERE clause contains both an AND and an OR, the AND will
always be evaluated first.
and.sql
SELECT *
FROM person
WHERE lastname = 'Johnson'
OR lastname = 'Johanson'
AND firstname = 'Carole';
This query will find Carole Johanson, as well as anyone with the
last name of Johnson.
and2.sql
SELECT *
FROM person
WHERE (lastname = 'Johnson'
OR lastname = 'Johanson')
AND firstname = 'Carole';
This query will find all people with a firstname of Carole and a
lastname of either Johnson or Johanson.
Page 68 Rev 04-29-09 ©2009 ITCourseware, LLC
Chapter 4 SQL Queries — The SELECT Statement
The query below will find all accounts having a minimum $1000 credit limit that have a non-zero
balance:
account.sql
SELECT account_number "ACCT NUMBER",
account_name name,
credit_limit limit,
balance
FROM account
WHERE credit_limit >= 1000 AND
balance > 0;
When an employee enters data into the system, a field for which there is no data may be skipped or
have a 0 entered. When checking on the status of a store's inventory, the query below will display any
products at each store that may be running low in inventory and haven't yet been reordered:
inventory.sql
SELECT product_id, store_number
FROM inventory
WHERE quantity_on_hand < 20 AND
(quantity_on_order = 0 OR
quantity_on_order IS NULL);
IN and BETWEEN
Use the IN (or NOT IN) operator to compare a column against several possible
values.
in.sql
SELECT lastname, firstname
FROM person
WHERE state IN ('CA', 'CO');
or.sql
SELECT lastname, firstname
FROM person
WHERE state = 'CA'
OR state = 'CO';
between.sql
SELECT lastname, firstname
FROM person
WHERE id BETWEEN 6900 AND 7000;
between_date.sql
SELECT invoice_number, order_date
FROM order_header
WHERE order_date BETWEEN '01-NOV-95' AND '01-DEC-95';
To display the same information for both Washington and Colorado, enter the following:
store6.sql
SELECT store_number, street, city, area_code, phone_number
FROM store
WHERE state = 'WA' OR state = 'CO';
store7.sql
SELECT store_number, street, city, area_code, phone_number
FROM store
WHERE state IN ('WA', 'CO');
To list all store locations in California outside the 415 and 213 area codes:
store8.sql
SELECT store_number, street, city, area_code, phone_number
FROM store
WHERE area_code NOT IN ('213', '415')
AND state = 'CA';
To display a specific vendor's products that fall in the $100 to $500 price range:
product7.sql
SELECT description, price
FROM product
WHERE vendor_id = 'IBM' AND price BETWEEN 100 AND 500;
To display all orders placed between July 20, 1996 and August 1, 1996:
order.sql
SELECT invoice_number, customer_id, order_date
FROM order_header
WHERE order_date BETWEEN '20-JUL-1996' AND '01-AUG-1996';
vendor_like.sql
SELECT vendor_id, name
FROM vendor
WHERE name LIKE '%Software%';
Beginning with Oracle 10g, you may also use regular expressions to find string
patterns.
The REGEXP_LIKE operator works like a function that takes two arguments,
the string to search in, and the pattern to look for.
reg_person.sql
SELECT firstname
FROM person
WHERE REGEXP_LIKE(firstname, '^Ste(v|ph)en$');
Use full regular expression syntax, similar to Perl, to find very complex
patterns.
person_like.sql
SELECT id, firstname, lastname
FROM person
WHERE lastname LIKE 'M%ll_';
ID FIRSTNAME LASTNAME
------- ------------- ---------------
6873 L. E. McAnally
8993 Madonna Mullally
9166 Angie Matilla
9412 Bruce McNally
9845 Neil Montville
person_like2.sql
SELECT id, lastname, firstname
FROM person
WHERE lastname LIKE '%son';
If you need to include the % or _ characters in the search pattern, specify an escape character. An escape
character removes the special meaning of the character following it. For example, to locate vendor
company names that contain an underscore, modify the query with an escape parameter.
vendor_like2.sql
SELECT name
FROM vendor
WHERE name LIKE '%\_%' ESCAPE '\';
To find names that contain a single quote, escape the single quote with another single quote:
person_like3.sql
SELECT id,lastname,firstname
FROM person
WHERE lastname like '%''%';
SELECT {item_list | *}
FROM table
[ORDER BY column [ASC | DESC],...];
column can either be the name or the numeric position of the column in
the item_list.
The result set is sorted by the first column name in the ORDER BY clause.
If there are duplicate values in the first sort column, the sort is repeated
on the second column in the list, and so on.
NULL values will be sorted after all non-NULL values in ASC order (and
before all non-NULLs when you use DESC).
To display each store's number and location in descending order by state, and ascending order by city
in each state, enter the following:
store9.sql
SELECT store_number, city, state
FROM store
ORDER BY state DESC, city ASC;
The description, and original and sale price of an item may be displayed in descending price order with the
following:
product5.sql
SELECT description, price,
price * .75
FROM product
ORDER BY 3 DESC;
An equivalent, and usually more readable, form of the above makes use of column aliases:
product6.sql
SELECT description Name, price Original_Price,
price * .75 sales_price
FROM product
ORDER BY sales_price DESC;
Labs
List the states in which there are stores, listing each state only once.
(Solution: store_states.sql)
List the states in which there are people, listing each state only once.
(Solution: person_states.sql)
List the last name, first name, city, and state of everyone who lives in a city that starts with
"Las" or "Los" or "San".
(Solution: las_los_san.sql)
Write a query that displays the account name and type. Use CASE...WHEN to show the account
type.
(Solution: account.sql)
Objectives
Views
A view's data consists of the results of the defining query on its base tables.
Base tables are those used within the defining SELECT statement.
Creating Views
This creates a phone list view based on data in the person table:
phone.sql
CREATE VIEW phone_list (name, phone)
AS SELECT lastname || ', ' || firstname,
'(' || area_code || ')-'
|| SUBSTR(phone_number,1,3) || '-'
|| SUBSTR(phone_number,4)
FROM person;
phone_query.sql
SELECT *
FROM phone_list
WHERE upper(name) LIKE 'SMIT%';
nevada_phone.sql
CREATE VIEW nevadaphone
AS SELECT lastname, firstname, area_code, phone_number
FROM person
WHERE area_code = '702';
Updatable Views
Queries on a view may only return columns listed in the view definition,
that is, the items in the SELECT list of the view's defining query.
Updates can be made to columns derived from plain columns in the base tables.
update.sql
UPDATE nevadaphone
SET phone_number = '3585544'
WHERE lastname = 'Johnson'
AND firstname = 'Jack';
SET
DISTINCT
Aggregate function
GROUP BY
Views that have more than one base table in the FROM clause of their
SELECT statement are updatable with some restrictions:
You can only affect fields from one of the base tables in one UPDATE
statement to the view.
Any table which is not key-preserved cannot be updated through the view.
A key-preserved table has only one record in the result set for each
row in the orignial database table.
Page 180 Rev 04-29-09 © 2009 ITCourseware, LLC
Chapter 10 Other Database Objects
View definitions are stored within the Data Dictionary as the defining SELECT statement. If any of the base
tables change, you may have to DROP and CREATE the view again.
You may inspect a view's underlying definition by looking in the Data Dictionary.
phone_view_text.sql
SELECT text
FROM user_views
WHERE view_name = 'PHONE_LIST';
key_preserv.sql
CREATE OR REPLACE VIEW emps
AS SELECT id, pay_amount, pay_type_name
FROM employee e JOIN pay_type p USING (pay_type_code);
Updates to the employee table through the view will succeed because it is key-preserved; each employee
in the view corresponds to one employee in the employee table.
update1.sql
UPDATE emps
SET pay_amount = pay_amount * 1.1
WHERE id = 7881;
Updates to the pay_type table will fail, since each pay_type record may appear multiple times in the view
result.
update2.sql
UPDATE emps
SET pay_type_name = 'Exempt'
WHERE pay_type_name = 'Salaried';
Sequences
sequence.sql
CREATE SEQUENCE po_seq START WITH 12000
INCREMENT BY 5;
alter_seq.sql
ALTER SEQUENCE po_seq
INCREMENT BY 2;
ORDER | NOORDER Guarantees that sequence numbers are generated in the order that
they were requested. Default is NOORDER.
When caching sequence numbers, Oracle stores the numbers in memory, which can improve
performance. However, if the instance fails, the numbers are then lost upon startup, causing a gap in the
numbers.
You must have CREATE SEQUENCE privileges to create a sequence in your own schema, and
CREATE ANY SEQUENCE privileges to make a sequence in someone else's schema.
A SELECT list.
The SET clause of an UPDATE.
The VALUES list of an INSERT.
Synonyms
When one user owns all of the tables that everyone accesses, PUBLIC
synonyms allow easy use of those tables from any login.
Labs
Create a view called order_check that will list the invoice number, store number, customer id,
order date, and the date of the Monday following the estimated delivery date of orders in the
order_header table.
(Solution: order_check.sql)
Using the view you just created, list all the orders from the San Francisco store.
(Solution: order_check2.sql)
Create a private synonym called vend for the vendor table. List all records from the vendor
table using this synonym.
(Solution: vendor.sql)