1Z0051 Oracle 11g SQL Fundamentals I
1Z0051 Oracle 11g SQL Fundamentals I
1-800-418-6789
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Table of Contents
Abstract. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
What to Know. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.0 Oracle Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.0 Data Retrieval Using SELECT. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
DESCRIBE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
The Simple SELECT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.0 Restricting and Sorting with SELECT. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
The WHERE Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
The ORDER BY Clause. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Substitution and Session Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Substitution Examples. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
4.0 Single-Row Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Single-Row Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Examples of Single-Row Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
5.0 Conversion Functions and Conditional Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Key Conversion Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Handling NULL Values. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
CASE Expressions and the DECODE Function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
6.0 Group Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
GROUP BY Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
The HAVING Clause. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
The GROUP Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Key GROUP Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
7.0 Joining Data Across Tables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
ANSI Joins. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Oracle Syntax Joins. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
8.0 Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Kinds of Problems Subqueries Can Solve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
9.0 Set Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Example Set Operator Queries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
10.0 Updating Data Through DML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
INSERT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
UPDATE and DELETE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
MERGE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Example INSERT, UPDATE, DELETE, and MERGE Statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
TRUNCATE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
SAVEPOINTS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Transactions in Developer Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
SELECT FOR UPDATE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
11.0 Creating Tables Through DDL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Creating Tables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Modifying Existing Tables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Table Operations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Constraints. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
More on Foreign Key Constraints. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
12. 0 Creating Other Schema Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Synonyms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Indexes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Practice Questions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Answers & Explanations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Abstract
This Exam Manual prepares you for the Oracle 11g certification exam #1Z0-051, Oracle Database 11g: SQL
Fundamentals I. Passing this exam plus the test entitled Oracle 11g Administration I 1Z0-052 makes you
an Oracle 11g Certified Associate (an OCA).
This Exam Manual is your Cliffs Notes key to the test material. It is a short, highly-targeted summary of
whats on the exam. It cant cover everything, but if you understand and memorize its contents, you will
be very far along towards passing the exam.
The exam covers the SQL language in depth -- from an Oracle standpoint. Test topics include SQL
language elements (operators, precedence, notation, and syntax), SELECT statements (keywords,
selection, sorting, joins, subqueries, and CASE expressions), SELECT statement functions (single-row,
group, and conversion), updating data (INSERT, UPDATE, DELETE, and MERGE statements), set operators,
creating common objects (including tables, views, indexes, sequences, and synonyms), and basic table
characteristics, such as data types and constraints.
What to Know
You need to know the SQL language very well to pass this pass. This includes operators, syntax, notation,
special characters, and the like. Test questions will confront you with very minor syntax differences in SQL
statements so you have to remember SQL and its syntax well enough not to become confused.
The SQL covered is that typically used by developers in their database work. This includes DML
statements (SELECT, INSERT, UPDATE, DELETE, MERGE), transaction control statements (COMMIT,
ROLLBACK, SAVEPOINT), and the DDL statements that manage the kinds of objects that developers deal
with (CREATE / ALTER / DROP TABLE, INDEX, VIEW, SYNONYM, SEQUENCE).
The test does not cover the SQL statements used by database administrators to create or manage
physical storage (CREATE / ALTER / DROP DATABASE, TABLESPACE), partitioned tablespaces, or TABLE
storage parameters).
Know the SELECT statement, all its keywords and options, very well.
Understand Joins and how to perform them. Given a Join statement, be able to determine the result set.
Given a SELECT having a subquery, be able to determine its result set. Why does one use subqueries?
Understand the common uses of the INSERT, UPDATE, DELETE, and MERGE statements and their syntax.
What are transactions? How are they used and why are they important? Know why you issue COMMIT
and ROLLBACK statements.
Know the difference between single-row and group functions and why each is used. Study the conversion
functions too.
Know how to create and alter tables, views, indexes, synonyms, and sequences. What is each object and
for what is it used?
What are Oracle 11gs data types and how do you declare them when creating tables? How and why does
one apply constraints to tables?
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Tips
QQ
The test consists of multiple-choice questions with one correct answer. It also contains multiplechoice questions where you select 2 or 3 correct items out of a list of 5 or 6 possible answers.
For multiple-answer questions, you must select every correct answer and none of the incorrect
answers in order to get credit for correctly answering the question. There is no partial credit.
Be sure to answer every question -- there is no penalty for guessing.
Read each question carefully and read all alternatives before picking an answer. Often the
differences between answers are very slight and you dont want to pick a wrong answer just
because you didnt read the question carefully.
The answers to many questions will not be immediately evident. In this case it helps to use a
process of elimination. Eliminate answers you know are wrong, and youll often then be able to
take your best guess from the remaining couple alternatives.
You can always mark a question youre not sure about for later review.
It is not unusual to find information in other questions that will later help you answer the
questions youve marked for review.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Books:
Search at Amazon online and you will find several books that are written specifically to help you pass this
exam. Read reviewers comments to select which you prefer. Or go to a bricks-and-mortar bookstore and
peruse the books yourself. It is important to select a book you like and have confidence in you will be
spending a lot of time studying it.
Here are two popular certification books for this exam
OCA: Oracle Database 11g SQL Fundamentals I Exam Guide: Exam 1Z0-051. By John Watson and Roopesh
Ramklass (Osborne Oracle Press Series).
QQ
OCA: Oracle Database 11g Administrator Certified Associate Study Guide: (Exams 1Z0-051 and
1Z0-052). By Biju Thomas (Sybex). This book covers both the exams you need to become an
Oracle Certified Associate.
The Oracle manual on which this test is based is the SQL Language Reference.
Practice Questions:
Practice questions get you ready to face the real exam. They give you a feel for what the tests are like, and
they also help you conceptualize your knowledge of Oracle in terms of the kinds of questions youll face in
the real exam.
We recommend the practice tests available from LearnSmart. LearnSmart has earned a reputation for
quality practice tests that prepare candidates well for certification exams.
Oracle Corporation offers ten free sample questions at their certification web site. These questions show
you what the test questions look like -- but the sample is far too small to help you learn what you need to
know to pass the exam.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
A schema is the group of all database objects (such as tables, indexes, etc) owned by a particular
user. Two example or demonstration schemas come with Oracle and are used for tutorial purposes
in the Oracle manuals and on this exam. They are HR (Human Resources) and OE (Order Entry). The
demonstration schemas are usually created when you first install Oracle and create a database (their
creation is an option in the Database Configuration Assistant tool). If the schemas were not created
during install you can create them by running Oracle-provided scripts. Its easy to run the scripts but the
details vary by platform so see the appropriate Oracle installation guide for details. Usually youll find the
scripts in a directory or folder labeled demo within your Oracle Home directory. Youll want to practice
SQL statements on Oracles two demo schemas. Exam questions continually refer to them.
For your reference while working with this Exam Manual, here are the table definitions for three key tables
from the HR schema that the exam and this Manual use as examples.
Departments:
Name
--------------------------
DEPARTMENT_ID
DEPARTMENT_NAME
MANAGER_ID
LOCATION_ID
LearnSmart
Null?
---------------
NOT NULL
NOT NULL
Type
---------NUMBER(4)
VARCHAR2(30)
NUMBER(6)
NUMBER(4)
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Employees:
Name
Null?
Type
-------------------------- ----------- --------EMPLOYEE_ID
NUMBER(6)
FIRST_NAME
VARCHAR2(20)
LAST_NAME
NOT NULL
VARCHAR2(25)
EMAIL
NOT NULL
VARCHAR2(25)
PHONE_NUMBER
VARCHAR2(20)
HIRE_DATE
NOT NULL
DATE
JOB_ID
NOT NULL
VARCHAR2(10)
SALARY
NUMBER(8,2)
COMMISSION_PCT
NUMBER(2,2)
MANAGER_ID
NUMBER(6)
DEPARTMENT_ID
NUMBER(4)
Job History:
Name
--------------------------
EMPLOYEE_ID
START_DATE
END_DATE
JOB_ID
DEPARTMENT_ID
Null?
---------------
NOT NULL
NOT NULL
NOT NULL
NOT NULL
Type
-------NUMBER(6)
DATE
DATE
VARCHAR2(10
NUMBER(4)
2.1 DESCRIBE
Use the DESCRIBE statement to discover the format of a table from Oracles data dictionary. The data
dictionary contains table definitions or metadata about tables. To learn the format of the HR schemas
DEPARTMENTS table issue this DESCRIBE statement:
DESCRIBE DEPARTMENTS;
Most SQL keywords like DESCRIBE have allowable abbreviations (DESC may be used instead of DESCRIBE).
SQL statements and their keywords may be coded in either upper-, lower-, or mixed case. SQL is a caseinsensitive language. But the data you store within the database is case-sensitive. It can be upper-case,
lower-case, or mixed-case.
SQL statements are terminated by a semi-colon. (In SQL*Plus youll often see the final SQL statement
followed by a forward slash ( / ), which tells SQL*Plus to run the statement(s).)
In the DESCRIBE statement, the table name may optionally be preceded by the schema name. The table
name must be preceded by the schema name if you are querying a table from a schema other than that to
which you are connected. The example above only runs if you are connected as the user account HR and
referring to the table HR.DEPARTMENTS.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
These rules mean that, assuming you are connected to the HR schema, all these are valid variations on the
previous statement:
DESC DEPARTMENTS;
DESC HR.DEPARTMENTS;
Describe Departments;
desc hr.departments;
Used For:
Description:
NUMBER
Numbers
VARCHAR2
Character strings
DATE
Dates
Date and Time. Includes Century, Year, Month, Day, Hour, Minute,
and Second.
TIMESTAMP
Timestamps
Some table columns are defined such that they are always required to contain data. They are defined as
NOT NULL. NULL in Oracle refers to an absence of data. A nullable column is a column that is not required
to contain data. If a column attribute does not contain any data it is often spoken of as containing nulls.
This is not strictly accurate the column field contains nothing. Nulls means the absence of data.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Blank spaces do not count as NULL because they are present in the row and consume space. Thus setting a
field to blanks can fulfill a NOT NULL definition for a character data type column. 0 (zero) is the same. It is a
value that consumes space and it differs from NULL.
Use:
Projection
Selection
Joining
Combines selected rows from two or more tables into the result set
DEPARTMENT_ID
------------
60
110
110
20
50
50
90
80
80
90
10 rows selected.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
The last query above returns more rows than the first two because its DISTINCT keyword eliminates only
duplicate combinations of the two columns, JOB_ID and DEPARTMENT_ID. Look at the table data to make
sure you understand how this works.
An alias is an alternate name for a column or expression. Its typically used to produce more user-friendly
output, since aliases replace column names as column labels in query output. These two example
statements show that the output will label the JOB_ID column as Job Code instead:
SELECT employee_id, job_id Job Code FROM hr.job_history;
The keyword AS is optional in denoting an alias. The presence or absence of the comma ( , ) between
elements is what distinguishes columns from aliases in the SELECT list of the SELECT statement. The
example alias Job Code must appear in double-quotes because it contains an embedded blank. The
double-quotes also preserve the mixed case in Job Code. If your alias does not contain an embedded
blank, and you dont care that the alias will appear as an all upper-case column label in the output, then
you can code the alias without the doublel-quotes.
SQL expressions and operators give SQL much of its power. Expressions usually perform operations on
one or more column values. The operators are either arithmetic (for numeric values), concatenation (for
character string values), or addition and subtraction (for date and timestamp values).
The order of precedence (or order of evaluation) for operators is, from highest to lowest:
LearnSmart
Precedence:
Operator Symbol(s):
Operation(s):
1.
()
Parentheses
2.
* /
3.
+ - ||
4.
5.
6.
[NOT] BETWEEN
Range comparison
7.
!= <>
Not equal to
8.
NOT
9.
AND
10.
OR
OR logical operator
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Chapter 3 covers the comparison operators in rows 4 thru 7 and the logical operators in lines 8 thru 10.
Operators of equal precedence are processed from left to right. If you need to dictate the order of
expression evaluation, you can always use parentheses ( ) to indicate what to evaluate first, because they
have the highest precedence.
An arithmetic operation with a NULL value always returns NULL. Concatenation is the joining together of
character strings. A NULL value within any concatenation operation is just ignored.
Lets discuss example statements that illustrate these operators:
LearnSmart
1.
2.
3.
4.
5.
This query returns the result of the arithmetic calculation (4), as indicated by the arithmetic operator ( + ). DUAL is a special table available in every Oracle database. It contains a single column
called DUMMY and used in situations like this one, where you want to resolve an expression in a
SQL statement and dont care what table is referred to in the required FROM clause.
2.
This query lists everyone in the EMPLOYEES table. It uses the concatenation operator to splice together employee names, with the last name listed first. A comma and one blank follow each last
name. You cant assume any order to the output unless you add the ORDER BY clause to the SELECT
statement (see chapter 3):
PERSON
----------------------------------------------
Abel, Ellen
Ande, Sundar (continued)
3.
This query returns the result of 64. The same query with the parentheses removed returns 36.
Coded without any parentheses, the multiplication operation will occur first, due to its higher
order of precedence than addition. With parentheses, the addition occurs first. This example
demonstrates the importance of the precedence order for operators, and how to override it
through use of parentheses.
4.
This query lists employees and the number of days they have been employed. The column
labeled DAYS_EMPLOYED by the alias shows the results of the days employed calculation.
Notice how the calculation is applied to the values returned from the START_DATE and END_
DATE columns. One day is added to the result of the calculation so that no employee shows 0
days employed. The column label DAYS_EMPLOYED will appear in upper-case even though
its encoded in lower-case because this column alias is not enclosed in double quotes to
preserve its case.
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
5.
This query shows use of a character string literal, a character string enclosed in single quotes.
The output contains a series of lines with this literal, each with a different employees name:
EMPLOYEEOFTHEYEARIS: LAST_NAME
FIRST_NAME
------------------------------- -------------------- --------------------------Employee of the year is: Abel
Ellen
Employee of the year is: Ande
Sundar (continued)
How would you replace the goofy column heading for the literal with something more presentable? Use
a column alias in the query.
DATE values are considered equal when all their internal components are equal (century, year, month, day,
hours, minutes, and seconds). Oracles default date format is DD-MON-RR. RR is the year. If RR is between
50 and 99, Oracle returns the 20th century, otherwise it returns the 21st century. You can alternatively
specify a four-digit year, YYYY. So the first two queries below are equivalent:
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
The last statement above points out that you can compare columns to each other in WHERE clauses. In
fact, the terms on either side of the comparison coded within the WHERE clause can be columns, literal
values, or expressions. For example, this statement contains expressions on both sides of the comparison
operator in the WHERE clause:
Note that columns used in the WHERE clause do not have to be in the SELECT list (the list of columns
appearing immediately after the SELECT keyword.) The above example shows this by coding both the
START_DATE and END_DATE columns in the WHERE clause but not in the SELECT list.
The comparison operators used in WHERE clauses are like those used in many other programming
languages. Either != or <> may be used to denote not equal to:
!=
<>
<
>
<=
>=
WHERE clauses can include multiple conditions through use of the Boolean or logical operators AND,
OR, and NOT:
Operator:
Meaning:
AND
Both WHERE conditions linked by the AND must be TRUE for the row to
be returned
OR
Either WHERE condition linked by the OR can be TRUE and the row will
be returned
NOT
Heres an example. Note that the WHERE keyword itself only appears once in the SQL statement; it is not
coded for each condition tested. In this example rows must meet all three of the conditions in the WHERE
clause to become part of the result set, since the conditions are linked by keyword AND:
According to the operator precedence table given earlier in Chapter 2, the precedence of the logical
operators from highest to lowest is: NOT, AND, OR. If you have a complicated WHERE clause with several
conditions, remember that you can always use high-precedence parentheses to dictate the order in which
the conditions are applied.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Meaning / Example:
BETWEEN
Tests if a column or expression value falls within an inclusive range. This example returns
rows where the salary is greater than or equal to 10000 and less than or equal to 20000:
WHERE salary BETWEEN 10000 and 20000 ;
IN
Tests if a column or expression value is a member of the specified set of literal values. This
example returns rows where the salary is 10000, 20000, or 30000:
WHERE salary IN (10000, 20000, 30000) ;
IS NULL
Tests if a column value is NULL. This example returns rows where no value has yet been
assigned to the salary: WHERE salary IS NULL ;
IS NOT NULL
Applies NOT to IS NULL to return rows where there exists a valid non-null value for a column. Example: WHERE salary IS NOT NULL ;
Applies a specified character pattern comparison to a character string. The underscore
character ( _ ) may be used to represent any one character while the percentage sign ( % )
may be used to represent any zero or more characters. Here are a few examples:
LIKE
What if you have a LIKE comparison in which you actually want to use the percent symbol ( % ) or the
underscore ( _ ) as part of the pattern to compare? Use the ESCAPE keyword and you can denote that the
symbol is literal and not to be interpreted as a special character. For example, to search the EMAIL column
for the exact character string, AB%, you would code:
The ESCAPE keyword identifies an escape character. Any single special character encoded immediately
after this escape character in the LIKE pattern is treated by Oracle as the literal character encoded (and
not as a special character). So in this case, the percent sign after the LIKE keyword is treated as an actual
percentage sign, rather than as the special character that matches any zero or more arbitrary characters.
If a query contains both a WHERE clause and an ORDER BY clause, the ORDER BY goes last. Like WHERE
clauses, ORDER BY clauses may refer to column(s) not in the SELECT list.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
You can sort query results by more than a single column. In this case, the columns are applied to the sort
from left to right (the leftmost column is the first-applied sort column and the rightmost is the last). Thus,
we call the leftmost column the major sort and the rightmost the minor sort. Heres an example:
SELECT department_id, last_name, first_name FROM employees
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
When coding with single and double ampersand substitution, you need a way to manage the session
variables to which they refer. Oracle provides several SQL client control commands for this purpose.
These are not SQL statements but rather Oracle-provided commands for controlling the behavior of the client
tool SQL*Plus. The semi-colon statement terminator, required for SQL statements, is optional with these
SQL*Plus commands:
Command
Use
DEFINE;
DEFINE variable=value;
UNDEFINE variable;
Turning off DEFINE means that the client tool will not save session
variables. By default DEFINE is ON
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
All functions always return a single value of a predetermined data type. They return one
result per execution.
Functions operate on three kinds of input data:
1. Character
2. Numeric
3. Date
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
For
Character functions
(returning strings)
Character functions
(returning numeric values)
Numeric functions
Functions to manipulate date and time data, including date and time
arithmetic. Examples: ADD_MONTHS and NEXT_DAY.
Conversion functions
Group functions
Analytical functions
Complex analytics.
Miscellaneous functions
The Exam does not cover Object Reference or Analytical functions. It does cover all the others. This chapter
summarizes the single-row functions, while the next chapter covers the conversion functions. Finally,
chapter 6 details the aggregate or group functions.
The functions the exam covers are built-in functions. They come built-in as part of Oracle. Oracle also
allows you to define your own functions, called user-defined functions or UDFs. UDFs are not covered on
the exam.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
LearnSmart
Character Function
Returns
ASCII
CHR
CONCAT
INITCAP
INSTR
INSTRB
LENGTH
LENGTHB
LOWER
A string in lower-case
LPAD
LTRIM
RPAD
RTRIM
REPLACE
SUBSTR
SUBSTRB
SOUNDEX
TRANSLATE
TRIM
UPPER
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
LearnSmart
Numeric Function
Returns
ABS
Absolute value
ACOS
Arc cosine
ASIN
Arc sine
ATAN
Arc tangent
ATAN2
BITAND
CEIL
COS
The cosine
COSH
EXP
FLOOR
LN
LOG
The logarithm
MOD
POWER
ROUND
A rounded number
SIGN
SIN
The sine
SINH
SQRT
TAN
The tangent
TANH
TRUNC
Truncates a number
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Date Function
Returns
ADD_MONTHS
CURRENT_DATE
CURRENT_TIMESTAMP
DBTIMEZONE
EXTRACT
A part of a date/time
FROM_TZ
LAST_DAY
LOCALTIMESTAMP
MONTHS_BETWEEN
NEW_TIME
NEXT_DAY
ROUND
Rounds a date/time
SESSIONTIMEZONE
SYS_EXTRACT_UTC
SYSDATE
Current date/time
SYSTIMESTAMP
TRUNC
TZ_OFFSET
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Explanations for why each example works the way it does are listed below the chart.
Character Function Example
Returns
1.
length(sysdate)
2.
length(hi || there)
3.
3.14 almost pi
4.
concat(concat(a,b),c)
abc
5.
substr([email protected],5,3)
aol
6.
substr([email protected],4)
@aol.com
7.
instr([email protected],@,1,1)
8.
instr([email protected],@)
9.
initcap(this is fun)
This Is Fun
10.
upper(lower(Why?))
WHY?
11.
[email protected]@aol.com
12.
replace(this is fun,fun,bad)
this is bad
1.
This example demonstrates nested functions. SYSDATE is a built-in Date function that returns
the current date as a DATE data type. Oracle implicitly converts the DATE value to a character
string in this default format: 29-APR-09. This yields a character string length of 9.
2.
This example shows how to concatenate two literal character strings using the concatenation
operator ( || ). The result here is the string hi there which contains 8 characters. (Note that the 2nd
input argument contains a leading blank).
3.
CONCAT takes two strings and concatenates them. If the arguments are not strings, it attempts
to convert them prior to the concatenation operation. This example first resolves the numeric
expression 1+2.14 and returns 3.14. It then implicitly converts this to the character string 3.14.
Finally, CONCAT splices this together with the string literal in the second input argument to
produce the result shown.
4.
This example shows function nesting. The inner-most CONCAT produces the string ab, while the
outer function concatenates the letter c to this to return abc.
5 & 6. These statements illustrate SUBSTR. The first gives the subject string, then the starting charater
position for the substring and its length. The second example shows that the implied length of
the extracted substring, if not coded, is to the end of the subject string. 4 is the starting position
for the substring to extract.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
7 & 8. The first argument to INSTR is a subject string while the second is a search string to look for.
The function returns the numeric position of the Nth occurrence of the search string it finds in
the subject string, where Nth is specified by the 4th parameter (if any). The 3rd parameter is the
position to start searching at in the subject string. In this case the first occurrence of the subject
string @ is at character position four in the subject string. Example (8) just shows that the 3rd and
4th arguments default to 1 if not coded, so it returns the same result as example (7).
9. INITCAP capitalizes the first letter of every word in its input string.
10. The nested LOWER function converts the input string to lower case, then the outer UPPER
function converts it to all upper-case letters.
11. TRIM can be used to trim off leading and/or trailing characters from a string. A common use
is eliminating preceding and following spaces. Here it strips out occurrences of a specified
character from both ends of a string. Related functions include LTRIM and RTRIM, which
respectively remove leading and trailing occurrences of a specified character from a string.
Conversely, the LPAD and RPAD functions left- and right- fill a string with occurrence(s) of
a given character.
12. REPLACE replaces a target string within the subject string with a given replacement.
Here are example numeric and date functions. Full explanations follow the chart:
1.
round(13.48,1)
13.5
2.
trunc(13.42,1)
13.4
3.
mod(12,5)
4.
months_between(01-MAY-2009, 01-JUL-2009)
-2
5.
months_between(01-JUL-2009, 01-MAY-09)
6.
add_months(01-MAY-2009,2)
01-JUL-09
7.
next_day(01-MAY-2009, Friday)
08-MAY-09
8.
last_day(01-MAY-2009)
31-MAY-09
ROUND rounds off a number to the decimal precision indicated by the second input argument.
If you do not code the 2nd input argument, ROUND will round off the number to the nearest
whole number.
2.
TRUNC truncates a number as per the decimal precision indicated by the second input
argument. A whole number is returned if the 2nd argument is not coded.
MOD gives the remainder from dividing the 2nd argument into the 1st.
4 & 5. MONTHS_BETWEEN returns the number of months between the arguments. The
ordering of the input arguments determines the sign of the result.
6.
LearnSmart
Returns
1.
3.
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
7.
NEXT_DAY returns the date on which the next day of the week specified occurs after the given
input date.
8.
LAST_DAY returns the last day of the month for the given month in date format.
LearnSmart
Conversion Function:
Usage:
ASCIISTR
BIN_TO_NUM
CAST
Converts datatypes
CHARTOROWID
COMPOSE
Converts to Unicode
CONVERT
DECOMPOSE
HEXTORAW
NUMTODSINTERVAL
NUMTOTMINTERVAL
RAWTOHEX
ROWIDTOCHAR
TO_CHAR
TO_DATE
TO_DSINTERVAL
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
TO_MULTIBYTE
TO_NUMBER
TO_SINGLE_BYTE
TO_YMINTERVAL
UNISTR
The first parameter must either be a number or a date (or a value that can be implicitly converted into
either a number or a date). The second parameter is an optional format specification that tells the function
how to format the result it returns. Oracle supplies a long list of format specifiersletters, digits, and
special characters that provide masks that convert the data according to set rules. We cant list all the
format specifiers here due to space concerns, and also because they are highly similar to those used in
most programming languages (C++/C, Perl, COBOL, and others). See Oracles SQL Language Reference
manual for tables containing the format specifiers.
The third optional parameter refers to Oracles national language support or NLS and can
be safely ignored unless you are working with applications that provide cross-support for different
spoken languages.
Here are the TO_DATE and TO_NUMBER templates:
TO_DATE(string [,format] [,nls_parameter]),
TO_NUMBER(string [,format] [,nls_parameter]),
Like TO_CHAR, TO_DATE and TO_NUMBER both have their own unique lists of format
specifications. Oracles SQL Language Reference manual lists them all.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Returns:
Note:
TO_CHAR(451,0000999)
0000451
TO_CHAR(32.12,99.9)
32.1
TO_CHAR(sysdate, yyyy/mm/dd)
2009/05/01
TO_DATE(2009/05/01,yyyy/mm/dd)
01-MAY-09
TO_DATE(20090501,yyyymmdd)
01-MAY-09
TO_NUMBER(56,99)
56
As expected
TO_NUMBER(56,9999)
56
TO_NUMBER(56)
56
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Returns:
Reason:
NVL(NULL,ABC)
ABC
NVL(SUBSTR(A,5),Bad)
Bad
NVL2(NULL,notN,N)
NVL2(1,no,yes)
no
NULLIF(abc,abc)
NULL
NULLIF(abc,xyz)
abc
COALESCE(NULL,abc,def)
abc
The chart above states that NULLIF(abc,abc) returns NULL. How can we verify this? (The result only
shows up as a missing output on our display screen.) Heres one way:
SELECT NVL(NULLIF(abc,abc),It was NULL!) FROM dual;
This statement returns the string It was NULL!. This verifies that the first argument to the NVL function
our nested NULLIF function returned NULL.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Heres an example of the searched CASE. In it, comparisons follow after the WHEN clause:
SELECT last_name, salary,
CASE WHEN salary < 40000 THEN low
WHEN salary < 80000 THEN average
WHEN salary >= 80000 THEN high END Category
FROM employees
ORDER BY last_name ;
The DECODE function offers conditional logic, similar to CASE expressions, but coded into a function.
DECODED requires at least three parameters, but can accept many more. Here is its template:
DECODE(expr1, comp1, if_true1 [, expr2, comp2, if_true2] [, if_false]
DECODE compares the 1st two input parameters. If they are equal, it returns the 3rd parameter, IF_TRUE1.
If they are not equal, it proceeds to the next set of three parameters. If the first two of them are equal, it
returns IF_TRUE2. If not, DECODE continues working its way through each set of three parameters, left to
right, and returns the first IF_TRUEn value that matches two equal parameters.
If DECODE finds no parameter pairs that compare equally, it returns the optional parameter IF_FALSE. If
IF_FALSE is not coded, it returns a NULL value.
Heres an example of the DECODE function directly from the Oracle manuals. It returns the name of one of
four different cities depending on the value of the WAREHOUSE_ID. If WAREHOUSE_ID is not 1, 2, 3, or 4,
then DECODE returns the string value Non domestic.
SELECT product_id,
DECODE (warehouse_id, 1, Southlake,
2, San Francisco,
3, New Jersey,
4, Seattle,
Non domestic) Location
FROM inventories
WHERE product_id < 1775
ORDER BY product_id, Location;
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
When you have several keyword clauses in the same SELECT statement, the order in which they must
occur is WHERE, GROUP BY and HAVING, ORDER BY. Heres the template:
SELECT {column | expr | group_function(column | expr) [alias] },
FROM table_name
[WHERE condition(s)]
[GROUP BY {column(s) | expr}]
[HAVING group_condition(s)]
[ORDER BY {column(s) | expr | num_pos}
[ASC | DESC] [NULLS FIRST | LAST]] ;
The order of the GROUP BY and HAVING keywords can be reversed HAVING can come before GROUP BY.
But both must occur after the WHERE clause and before the ORDER BY clause.
HAVING can only be coded if GROUP BY is present. It cannot be coded in the absence of a GROUP BY clause.
The diagram below shows the parts the SELECT statement play in processing the query:
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
LearnSmart
Group Function:
Returns:
AVG
Statistical mean
CORR
COUNT
COVAR_POP
COVAR_SAMP
CUME_DIST
DENSE_RANK
FIRST
GROUP_ID
GROUPING
KEEP
LAST
MAX
Largest value
MIN
Smallest value
PERCENT_RANK
PERCENTILE_
CONT
The interpolated value that would fall in the percentile position using a
continuous model
PERCENTILE_DISC
The interpolated value that would fall in the percentile position using a
discrete model
RANK
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
REGR_AVGX
REGR_AVGY
REGR_COUNT
REGR_INTERCEPT
REGR_R2
REGR_SLOPE
REGR_SXX
REGR_SXY
REGR_SYY
STDDEV
Standard deviation
STDDEV_POP
STDDEV_SAMP
SUM
VAR_POP
Population variance
VAR_SAMP
Sample variance
VARIANCE
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
When DISTINCT is coded, only unique occurrences of the expression denoted by EXPR are included in the
evaluation for each group. For example, COUNT DISTINCT will only count unique occurrences of EXPR for
each group. ALL is the default, so by default all values are included in the group function. This includes
any duplicates. Remember that, unless you specifically code to handle them through functions like NVL or
NVL2, nulls are ignored in group function evaluations.
Here are a few usage examples of these group functions. Start with a simple COUNT of all rows in the
EMPLOYEES table. Duplicates would be included, since we did not specify DISTINCT and the default for all
the above group functions is ALL:
SQL> SELECT COUNT(*) Total Number FROM hr.employees;
Total Number
-----------107
How many managers are there? Here we need unique MANAGER_IDs only:
SQL> SELECT COUNT(DISTINCT manager_id) Managers FROM hr.employees;
Managers
---------18
What are the standard deviation and variance on salaries at the company?
SQL> SELECT STDDEV(salary) as Stddev, VARIANCE(salary) as Variance
2 FROM hr.employees;
Stddev Variance
---------- ---------3909.36575 15283140.5
What are the standard deviation and variance on the salaries within each department? This is a little
trickier query because you want to apply the STDDEV and VARIANCE functions to all salaries within each
departmentnot to all rows in the table as a whole. Youll want to group employees by department, since
that is the level on which we want to apply the standard deviation and variance group functions. Well
add an ORDER BY clause to sort by department to make it easier to view the results:
SQL> SELECT department_id, STDDEV(salary) as Stddev, VARIANCE(salary) as Variance
2 FROM hr.employees
3 GROUP BY department_id
4 ORDER BY department_id;
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
DEPARTMENT_ID
Stddev
-----------------------
----------
10
0
20
4949.74747
30
3362.58829
40
0
50
1488.00592
60
1925.61678
70
0
80
2033.6847
90
4041.45188
100
1801.11077
110
2616.29509
0
Variance
---------
0
24500000
11307000
0
2214161.62
3708000
0
4135873.44
16333333.3
3244000
6845000
0
Weve got the right grouping and group function outputs. But what about those departments that report
0 for the group functions? And how about that last row, where there is no reported DEPARTMENT_ID?
A quick query applying the COUNT function on each department shows that there is only one employee
in each of the departments that returned 0 for standard deviation and variance. Those functions cannot
compute meaningful numbers with only one value, so the 0 result makes sense:
LearnSmart
COUNT(*)
---------1
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
So all we have to do to develop the final query is add a HAVING clause to eliminate any department that
has only one employee. This clause also knocks out the row with the NULL DEPARTMENT_ID:
Stddev
----------
4949.74747
3362.58829
1488.00592
1925.61678
2033.6847
4041.45188
1801.11077
2616.29509
Variance
---------24500000
11307000
2214161.62
3708000
4135873.44
16333333.3
244000
6845000
Now heres an example that shows ordering query results on more than one column. In this case
DEPARTMENT_ID is the major sort order and EMPLOYEE_ID the minor (this could be useful for exception
processing if accidentally there were more than one employee per EMPLOYEE_ID). Remember that to list
EMPLOYEE_ID in the SELECT list for the output you have to include it in the GROUP BY clause. Failure to do
so causes a syntax error.
EMPLOYEE_ID
----------200
201
202
114
115
(continued)
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Nonequijoins match rows from different tables based on an inequality between column values, rather
than on equality like equijoins. Nonequijoins use the JOINON syntax and are not very common.
Finally, the cross join or Cartesian product produces a result set with every possible combination of
source and target tables joined together. The output is potentially huge and performance terrible
because multiplying the total number of rows for the two tables together tells you how many rows youll
get in the cross join results set. For example, with a 100,000 row table and a 200,000 row table, youll
get (100,000 * 200,000) = 20,000,000,000 rows. Wow! The ANSI keywords CROSS JOIN perform
the Cartesian product.
Heres the template for a cross join using ANSI-1999 syntax:
SELECT table_name_1.column, table_name_2.column
FROM table_name_1
CROSS JOIN table_name_2 ;
This example CROSS JOIN displays matching department number combinations and tries to limit results
by adding a WHERE clause:
SELECT d.department_id, e.department_id, e.last_name
FROM departments d CROSS JOIN employees e
WHERE d.department_id < 200
ORDER BY d.department_id ;
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
EMPLOYEE_ID MANAGER_ID
-----------
----------
100
101
100
108
101
109
108
110
108
111
108
112
108
113
108
JOB_ID
---------AD_PRES
AD_VP
FI_MGR
FI_ACCOUNT
FI_ACCOUNT
FI_ACCOUNT
FI_ACCOUNT
FI_ACCOUNT
(continued)
8.0 Subqueries
A subquery is a nested querya nested SELECT clause. The purpose of a subquery is to find and return
data to a higher-level or enclosing SQL statement. Subqueries can be nested inside SELECT, UPDATE,
INSERT, and DELETE statements.
This example SELECT statement lists employees who have higher than average salaries in the company.
See how the indented or inner query calculates the average salary across the company, and that it returns
that value to the outer query for purposes of the comparison:
SELECT last_name, salary FROM employees
WHERE salary >
(SELECT AVG(salary) FROM employees) ;
The subquery is termed the inner query, while the statement to which it returns its results is called
the outer query. The inner query is resolved first, and its results are returned to the outer query for
additional processing.
Since you can nest subqueries within subqueries, it sometimes makes sense to refer to the inner-most
query and the outer-most query. When you have a complicated SQL statement with multiple nested
subqueries, you can easily resolve it. Always remember this rule: however many nested subqueries a
statement contains, subqueries are always resolved from inner-most to outer-most.
Single-row subqueries return return one row to their enclosing SQL statement. A scalar subquery is a
special case of a single-row subquery; it returns one value (a single row with a single column). Mutiplerow subqueries return a multiple row result set. Correlated subqueries run the inner query once for
each row in the table or view named in the outer SELECT statement.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Subqueries are often coded to return from zero to many rows for use with keywords like IN, NOT IN, ANY,
or ALL. Or, subqueries can return a single value for use with one of the comparison operators
(eg: equals =).
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
In the correlated subquery, the outer SELECT is assigned a table label or correlation name. In this
example it is the letter s. The column name S.DEPARTMENT_ID is then used to correlate the columns of
the outer-level SELECT with those of the sub-SELECT.
Correlated subqueries are sometimes easier to write than alternative ways of solving the same
problem. But since the inner query repeatedly executes for each row of the outer query, they typically
perform poorly.
Use:
UNION
UNION ALL
Returns all rows from both queries, including duplicates. Unsorted by default.
INTERSECT
MINUS
Returns distinct rows returned by the first query but not by the second query, sorted.
By default, sorting occurs across all the columns, as listed left to right. The exception is UNION ALL
which does not sort at all by default. You would therefore normally code an ORDER BY clause for a
UNION ALL operation.
The order in which tables are coded in SELECT statements affects the results for MINUS but not for the
other set operations. There is no order of precedence among the set operators themselves, so if you code
more than one set operator in a query, parentheses are recommended to dictate the order of resolution.
Here are some set operator examples that show how the commands work. Assume table One contains
rows A, B, C, and table Two contains rows A and B:
Example:
Result:
A, B, C
A, B
NULL set
In writing the queries, it is fine if different column names are used in the corresponding columns for the
tables involved. But the data types of the corresponding columns must be of the same data type group.
That is, Oracle will accept two different numeric types for a corresponding column across tables, but not a
numeric type and a character type, for example. The number of selected columns must match across the
components of the compound query.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
EMPLOYEE_ID
-----------
102
101
101
201
114
122
200
176
176
200
START_DAT
---------
13-JAN-93
21-SEP-89
28-OCT-93
17-FEB-96
24-MAR-98
01-JAN-99
17-SEP-87
24-MAR-98
01-JAN-99
01-JUL-94
END_DATE
---------
24-JUL-98
27-OCT-93
15-MAR-97
19-DEC-99
31-DEC-99
31-DEC-99
17-JUN-93
31-DEC-98
31-DEC-99
31-DEC-98
JOB_ID
DEPARTMENT_ID
----------
------------IT_PROG
60
AC_ACCOUNT
110
AC_MGR
110
MK_REP
20
ST_CLERK
50
ST_CLERK
50
AD_ASST
90
SA_REP
80
SA_MAN
80
AC_ACCOUNT 90
First well create a duplicate of the JOB_HISTORY table in our own default schema:
CREATE TABLE job_history AS SELECT * FROM hr.job_history;
Both the new JOB_HISTORY and HR.JOB_HISTORY tables now have the exact same table definitions and
the same ten data rows shown above. While its unlikely youll often perform set operations on duplicate
tables, doing so is very instructive in showing how set operations work.
First, perform a UNION of the two tables:
SELECT * FROM job_history UNION SELECT * FROM hr.job_history;
The result is the same ten rows seen above, but sorted. Since UNION eliminates duplicates, we get ten
rows back (instead of twenty). The rows are sorted by the columns as listed, from left-most on to the right.
So the output is sorted by EMPLOYEE_ID, then by START_DATE within EMPLOYEE_ID, etc. Here is that
result set:
EMPLOYEE_ID
-----------
101
101
102
114
122
176
176
200
200
201
START_DAT
---------
21-SEP-89
28-OCT-93
13-JAN-93
24-MAR-98
01-JAN-99
24-MAR-98
01-JAN-99
17-SEP-87
01-JUL-94
17-FEB-96
END_DATE
---------
27-OCT-93
15-MAR-97
24-JUL-98
31-DEC-99
31-DEC-99
31-DEC-98
31-DEC-99
17-JUN-93
31-DEC-98
19-DEC-99
JOB_ID
DEPARTMENT_ID
----------
------------AC_ACCOUNT
110
AC_MGR
110
IT_PROG
60
ST_CLERK
50
ST_CLERK
50
SA_REP
80
SA_MAN
80
AD_ASST
90
AC_ACCOUNT
90
MK_REP
20
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Since UNION ALL does not eliminate duplicates, we get twenty rows in the result set (two of each row).
The rows are in no particular order, as UNION ALL does not sort by default. We could add an ORDER BY
clause if sorted output is important (as it usually is).
INTERSECT reports the rows that occur in both tables without duplicates:
SELECT * FROM job_history INTERSECT SELECT * FROM hr.job_history;
Thus this reports back ten rows. They are sorted by columns, left-most to right-most. In this particular case,
where we are operating on two duplicate tables, the output happens to be the exact same we received
from the initial UNION query. (Of course, since most compound queries dont work with duplicate tables,
this is an unusual result.)
Finally, lets try a MINUS operation. MINUS shows the difference between two tables (what rows are
in the first table that are not in the second). Since we are operating on duplicate tables, this query
returns no rows:
Usually MINUS gives entirely different results if you switch the positioning of the tables in the query.
Table A MINUS table B does not equal table B MINUS table A. But in this specific case, where the tables
JOB_HISTORY and HR.JOB_HISTORY contain exact duplicates rows, swapping the table positions in the
query will also return no rows:
Oracles DML statements are SELECT, INSERT, UPDATE, DELETE, and MERGE. SELECT is officially a DML
statement, though in informal usage, most Oracle professionals wouldnt include it because it does
not update data; the other four DML statements are used to add or change data in the database. DDL
statements include CREATE, ALTER, DROP, RENAME, TRUNCATE, and COMMENT. These manage tables and
other database objects. DCL statements include GRANT and REVOKE for security, while the TCL statements
include COMMIT, ROLLBACK, and SAVEPOINT for transactional control.
10.1 INSERT
Use an INSERT statement with a VALUES clause to insert a row into a table. You only need to specify a
column list (field names) if you do not supply a value for every column.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
You may use an INSERT with a subquery to insert multiple rows. Subqueries must return rows that
match the number of columns in the target tables column list and have compatible (ie, convertible)
data types. This example inserts (potentially) many rows into the EMPLOYEES table as read from the
HUMAN_TAB table:
When inserting into a view, the view should have been defined with the WITH CHECK OPTION to ensure
inserted rows must meet the criteria of the views defining query.
As with UPDATE, the data INSERT statements attempt to place into a table must meet any constraints
on that table. Constraints are business rules you apply to a table when you create the table or alter its
definition. The next chapter explains everything about constraints.
When coding the INSERT statement inside a program, use the RETURNING clause to return inserted values
to variables (including ROWIDs). Use PARTITION to insert data into a specific table partition. Both clauses
also apply to the UPDATE statement.
Note that it is often faster to bulk load tables through Oracle utility programs like SQL*Loader or
Datapump than it is to insert rows by the SQL INSERT statement.
10.3 MERGE
The MERGE statement both updates and inserts rows into a table. Rows that have matching keys are
updated; other (new) rows are inserted. The MERGE statement clauses WHEN MATCHED and WHEN NOT
MATCHED are used to indicate whether rows are updated or inserted, depending on the match criteria.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
10.5 TRUNCATE
An alternative to the DELETE statement to delete all rows from a table is the TRUNCATE command.
TRUNCATE is a DDL statement that removes all data from a tableas opposed to DELETE, which is DML.
TRUNCATE is fast, leaves the table definition intact (including dependent constraints and indexes), and
reclaims space. But, since its DDL, you can not issue a ROLLBACK to recover from an errant TRUNCATE. In
contrast, since the DELETE statement is DML, DELETE logs changes and offers the chance to ROLLBACK
data until it is committed to the database. Heres the format for TRUNCATE:
TRUNCATE TABLE table_name ;
If you need to very quickly delete all the rows from a large table, yet keep the table definition in the data
dictionary, TRUNCATE is your answer. Just remember that TRUNCATE is a DDL statement, so the change
will be immediately auto-committedthere is no logging and rolling back the statement if you deleted
the rows by mistake.
10.6 Transactions
A transaction is a set of one or more SQL DML statements, all of which will either succeed (and are
applied to the database), or do not succeed (in which case none of the statements in the transaction are
applied to the database). The purpose of dividing data updates into transactions is to ensure the integrity
of the data.
A log-in session starts a transaction as soon as it issues any INSERT, UPDATE, or DELETE statement.
Whatever changes you make in that session are invisible to other database users or programs until you
COMMIT them to the database.
A transaction is ended explicitly by the user when he issues a SQL COMMIT or ROLLBACK statement. Or
it may be ended implicitly, by external events like ending the client session or the database going down.
Issuing a DDL or DCL statement implicitly ends a transaction with a COMMIT. So if you issue a series of DML
statements, then follow them by a DDL or DCL statement, all the preceeding DML changes are committed
to the database.
A commit makes pending data changes permanent to the database. A rollback ensures any pending
changes not yet committed are discarded and not applied to the database. You can issue explicit
COMMIT or ROLLBACK commands yourself to control transactions.
Remember that while DDL and DCL commands issue an implicit commit, DML commands (SELECT, INSERT,
UPDATE, DELETE) do not cause an implicit commit. They are thus eligible for rollback until a COMMIT
statement is issued.
For example, say you perform these actions in order:
1. Create a new table
2. INSERT 2 rows into that table
3. GRANT the SELECT privilege to PUBLIC on that table
If the database crashes after step (3), all 3 actions were successfully applied to the database because of the
implicit commit that occurs after any DCL statement (the GRANT). If the database were to crash after step
(2), you have a new table due to the implicit commit after the DDL statement (CREATE TABLE) in step (1),
but no rows are in it because the INSERT statement is DML and is not implicitly committed.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
10.6.1 SAVEPOINTS
Oracle supports savepoints, intermediate points within transactions. You can rollback only part of the
transaction by issuing a ROLLBACK TO SAVEPOINT statement. Savepoints provide a convenient way to
break up large transactions into individually recoverable pieces.
To create a savepoint, simply issue this command:
SAVEPOINT savepoint_name;
To commit the work in the savepoint permanently to the database, issue the standard COMMIT command:
COMMIT ;
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
This locks the data for your exclusive update option until you release it to others by issuing a COMMIT
or ROLLBACK command or end the transaction implicitly. The benefit is that your UPDATE statement is
guaranteed to work against the exact same data that was retrieved by your initial SELECT. FOR UPDATE
statement. The cost is that other users and programs are prevented from updating the data until you
issue your COMMIT or ROLLBACK.
You can see that this update issue is a subtle problem of database locking. Locking by Oracle database
protects data integrity, the accuracy of the data. Most of this locking is transparent to users and
programs; it is automatic and they are not even aware of it. But the example above shows that sometimes
developers do need to be aware of locking and how to code programs that work as expected.
Locking is based on the four underlying principles, called ACID test due to their initials. Databases like
Oracle that ensure ACID principles guarantee data integrity:
A is for Atomicity
Atomicity means that all parts of a transaction must complete, or else none
of them complete
C is for Consistency
Consistency means that the results of a query must be consistent with the
state of the database at the time the query started
I is for Isolation
D is for Durable
Indexes- physical structures that organize data and speed data access
Oracle's data dictionary is a special set of objects that keep track of all the other objects. You could query
the data dictionary to find out the names of the tables in your schema, for example. When you issue
the DESCRIBE command, it retrieves information about the table you specify from the data dictionary
to display it to you. The data dictionary view named USER_OBJECTS lists basic information about all the
objects in your schema.
Your schema is also by default your namespace; that is, the area in which names must be unique. Thus
each table you create must have a unique name within your schema or namespace. A table and a view
could not have the same name if they exist in the same schema.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
All schema objects following the same naming rules. They must be:
QQ
1 to 30 characters long (except that database link names may be up to 128 characters)
Contain only letters, digits, the underscore ( _ ), dollar sign ( $ ), or pound sign ( # )
You cannot use a reserved word (like SELECT) for an object name. Object names are converted to all
upper-case by default. So under normal conditions you would expect all object names in the data
dictionary to be upper-case.
The SQL used to create and maintain objects is referred to as Data Definition Language or DDL. This
contrasts to the Data Manipulation Language or DML statements we have worked with in previous
chapters (SELECT, INSERT, UPDATE, and DELETE). The terms DDL and DML provide a quick way to
distinguish between SQL statements that are used to manipulate data versus those they are used to
create and maintain the underlying objects that facilitate storage and use of that data.
Type
---------------
EMPLOYEE_ID
START_DATE
END_DATE
JOB_ID
DEPARTMENT_ID
NUMBER(6)
DATE
DATE
VARCHAR2(10)
NUMBER(4)
NOT NULL
NOT NULL
NOT NULL
NOT NULL
Now that we know the column names, their data types, and whether they can be nulled (not entered), we
can reverse-engineer the CREATE TABLE statement to create a table just like it:
CREATE
TABLE JOB_HISTORY
(EMPLOYEE_ID NUMBER(6)
START_DATE
DATE
END_DATE
DATE
JOB_ID
VARCHAR2(10)
DEPARTMENT_ID NUMBER(4)
) ;
NOT NULL,
NOT NULL,
NOT NULL,
NOT NULL,
Notice that all the column definitions together are enclosed in a single set of parentheses. Dont forget
the final right parenthesis at the end of the column definitions. And remember, too, the single semi-colon
that terminates the entire SQL statement.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
This table is created in my own schema, as defined by my user id. If my user id is designer, my full table
name in the form SCHEMA.TABLE_NAME would be DESIGNER.JOB_HISTORY. Remember that names are
by default in all upper-case in the dictionary.
If my user id were HR, this CREATE TABLE statement would attempt to create a table named HR.JOB_
HISTORY. Since a table with this name already exists in that namespace, the statement would return an
error and create nothing.
One key parameter that is missing in the above table definition is DEFAULT. This permits you to declare
default data value that is inserted into a column if the input data does not specify a value. This example
ensures that START_DATE and END_DATE are never NULL by inserting the current date, SYSDATE, into
them if the user does not explicitly provide dates for insertion. The example also shows setting JOB_ID to
a default character string and DEPARTMENT_ID to a default numeric value:
CREATE TABLE JOB_HISTORY
(EMPLOYEE_ID NUMBER(6)
NOT NULL,
START_DATE
DATE
DEFAULT SYSDATE,
END_DATE
DATE
DEFAULT SYSDATE,
JOB_ID VARCHAR2(10) DEFAULT DBA,
DEPARTMENT_ID NUMBER(4)
DEFAULT(60) ) ;
To create tables you need to know the allowable data types. Here are Oracles key data types. The ones
you need detailed knowledge of for the exam are VARCHAR2, NUMBER, and DATE. The others you just
need be familiar with:
LearnSmart
Datatype:
Use:
CHAR(size)
NCHAR(size)
VARCHAR2(size)
Variable-length string up to 4000 bytes. You must specify SIZE (minimum is 1).
VARCHAR(size)
NVARCHAR2(size)
NUMBER(p,s)
NUMERIC, DECIMAL,
DEC, INTEGER, INT, FLOAT
DATE
TIMESTAMP
TIMESTAMP
WITH TIME ZONE
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
TIMESTAMP WITH
LOCAL TIME ZONE
Like TIMESTAMP, but stores the time as a normalized form of the database time zone.
ROWID
UROWID
LONG
CLOB
NCLOB
BLOB
BFILE
RAW
LONG RAW
After we created our own JOB_HISTORY table similar to HR.JOB_HISTORY table, we might want to load the
data from HR.JOB_HISTORY into our table. This requires two steps:
1. Creating the table
2. Loading the table with data
An alternative is to create the table and load it in a single statement. This technique creates the new table
via a subquery and is often called the CREATE TABLE AS statement.
This SQL creates a new JOB_HISTORY table with the exact same definitions as the HR.JOB_HISTORY table
and then loads all rows from the original HR.JOB_HISTORY table into the new table:
CREATE TABLE job_history
AS SELECT * FROM hr.job_history ;
Perform a SELECT * query against the new JOB_HISTORY table and youll see it contains the exact same
data as the HR.JOB_HISTORY table. DESCRIBE statements show both tables have the same table definition
and structure. Later in this chapter well discuss table constraints (like primary and foreign keys, etc).
But for now note that while CREATE TABLE AS duplicates data types, NOT NULL, DEFAULT, and CHECK
constraints into the new table, it does not duplicate primary key, column uniqueness, or foreign key
constraints. This is because these three constraints would require index creation.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
You can get fancier with table creation subqueries by applying any arbitrary WHERE clause to the
subquery. The effect is to restrict what rows are loaded into the new table. This statement only loads rows
into the new table that are from department 60:
CREATE TABLE job_history
AS SELECT * FROM hr.job_history WHERE department_id = 60 ;
You can also manipulate the SELECT list in the subquery to change the design of the new table. For
example, you can specify only a subset of the columns in the original table to come over to the new table.
This example creates a new table that has only two of the original column definitions, which are loaded
with the relevant data:
CREATE TABLE job_history
AS SELECT employee_id, department_id FROM hr.job_history ;
This example performs a group function in creating a new table that contains the average sales from the
original SALES_TABLE:
CREATE TABLE new_sales_table
ASSELECT avg(sales_quantity) Average_Sales FROM sales_table;
AVERAGE_SALES is the name of the new column that contains the average sales. It is the only column in
the new table and it has exactly one row in it, which contains the sales average.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Marking a column as UNUSED makes it appear as if the column does not exist to SQL queries. For
example, SELECT statements would not retrieve that column, and INSERT and UPDATE statements would
not refer to that column. Marking a column as UNUSED is also a quick operation. In contrast, dropping
columns is usually time-consuming because Oracle restructures each row in the table to remove the
columns data. So it is often best to set unused columns as UNUSED rather than dropping them. Then at a
later time when processing time is available, issue this command to finally drop the unused columns:
Another consideration in the above statements is the role of NULL columns. Oracle will not let you alter a
column to be NOT NULL if any existing rows are NULL for that column. Similarly, it does not make sense to
try to add a NOT NULL column to an existing table, as that would be incompatible with the initial state of
the newly-defined column.
11.4 Constraints
Constraints are rules or restrictions that apply to tables and their columns. They encode business rules
in the database (instead of in your program logic) for simplicity, accuracy, universality, and data integrity.
When a SQL statement that changes data runs against a table, it must not violate the constraint rules on
that table. If it does, it fails (by default).
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Keyword:
Use:
Primary Key
PRIMARY
One allowed per table to uniquely identify rows. Index may be automatically
created. Primary keys are UNIQUE and NOT NULL.
Uniqueness
UNIQUE
As many per table as desired. Index may be automatically created. Unless you
add NOT NULL to this, UNIQUE columns could have multiple null indicators.
NOT NULL
NOT NULL
Check
CHECK
Foreign Key
FOREIGN KEY
REFERENCES
Used for Referential Integrity (RI). Refers back to a unique or primary key in
the parent table. The table containing the foreign key is dependent on the
table it points to (often called its parent).
Key constraints can be defined over multiple columns. These are referred to as composite keys.
There are two main ways to specify constraints when you first define a table. You can place a constraint on
the same line as the column definition to which it refers, or you can place constraints on their own lines.
This example shows both techniques:
CREATE TABLE my_employee_table
(EMPLOYEE_ID NUMBER(6) PRIMARY KEY,
SALARY
NUMBER(8,2) CHECK (salary BETWEEN 10000 and 1000000),
TAX_INCREASE NUMBER(6)
CONSTRAINT tax_check CHECK (TAX_INCREASE > 100),
DAYS_WORKED NUMBER(9)
NOT NULL,
PREV_DAYS
NUMBER(9)
CONSTRAINT prev_here NOT NULL,
SECONDARY_ID NUMBER UNIQUE,
SEC_ID_TOO
NUMBER CONSTRAINT sec_uniq UNIQUE,
EMP_ID_REF NUMBER(6)
UNIQUE,
CONSTRAINT unq_sal_inc UNIQUE (salary,tax_increase) ) ;
This example also shows that you can leave constraints unnamed, or you can give them specific names
through use of the CONSTRAINT keyword. Adding a constraint name is useful when you violate the
constraint, because the error message will contain the constraint name. Its a good documentation
practice to name constraints.
Usually constraints are coded on the same line as the column to which they refer, but the last line of code
above shows that you can also place constraints at the end of the table definition. Where you see this
most frequently is in the definition of foreign key constraints.
How many indexes would automatically be created as a result of the above CREATE TABLE statement?
Fiveevery PRIMARY KEY and UNIQUE constraint forces an index to be automatically created if you do
not create the required index(es) explicitly yourself.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Foreign keys relate one table to another. The table containing the foreign key constraint points to its
parent table and is dependent on it. These two CREATE TABLE statements illustrate the point. The second
table is dependent on the first through its foreign key:
CREATE TABLE supplier
(SUPPLIER_ID
NUMBER(8) NOT NULL,
SUPPLIER_NAME
VARCHAR2(30)
NOT NULL,
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id) ) ;
CREATE TABLE products
(PRODUCT_ID
NUMBER(8) NOT NULL,
SUPPLIER_ID
NUMBER(8) NOT NULL,
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id) ) ;
The column in the parent table that the foreign key points to or references must already be defined
(though there are ways to defer it, ultimately every row in the table containing the foreign key must refer
to a valid parent table row). The two related columns do not have to have the same name in the two
tables but they do have to have the same data type.
You can use ALTER TABLE to add or drop constraints on existing tables. Examples:
ALTER TABLE tab ADD (CONSTRAINT cname PRIMARY KEY (c1));
ALTER TABLE tab ADD (CONSTRAINT cname UNIQUE (c1));
ALTER TABLE tab ADD (CONSTRAINT cname CHECK (c3=c4));
ALTER TABLE tab MODIFY (c1 NOT NULL);
ALTER TABLE tab DROP CONSTRAINT cname ;
ALTER TABLE tab DROP PRIMARY KEY ;
Constraints may also be enabled (activated) or disabled (turned off ) by use of the ALTER TABLE statement
with the ENABLE or DISABLE keywords. Examples:
ALTER TABLE table_name DISABLE CONSTRAINT constraint_name ;
ALTER TABLE table_name ENABLE CONSTRAINT constraint_name ;
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
12.1 Views
Views are virtual tables, stored queries that can be treated like tables in SQL. Their definitions are stored
in Oracles data dictionary, but they do not consume physical storage on disk. Views are internally just
stored SELECT statements that run against tables.
Views can be defined upon tables or other views and view definitions may be nested (although too much
nesting costs performance). Creating a view does not create a new table a view is simply a stored
query into an existing table. The purposes of views are to:
QQ
Reduce errors
Help performance
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Can you update data using a view? In general, you can with simple views but you can not with
complex views.
Views are not updatable by INSERT and UPDATE if they join detail tables in complex fashion, use functions,
or perform aggregation. Specifically, you can not INSERT or UPDATE through a view if it:
QQ
Does not contain all NOT NULL columns in its underlying table (and these must be assigned
values by the updating statement)
The rules for updatability of join views (views based on more than one table) are complicated. I
recommend just querying the data dictionary table called USER_UPDATABLE_COLUMNS to see what
columns in a join view can be updated. An Oracle feature called INSTEAD OF triggers can sometimes be
used to get around some of the restrictions on updatable views.
You can not change a view by the ALTER VIEW statement. Instead re-create the view without loss of
granted privileges by issuing CREATE OR REPLACE VIEW statement.
The main use of the ALTER VIEW statement is to recompile an existing view. The compilation or
recompilation process ensures that the view is validly based on its underlying table(s) and that it is ready
to be used. Use the DROP VIEW statement to eliminate a view.
Object views are views created upon traditional relational tables to make them appear like object tables.
Object views contain the key identifying phrases OF and WITH OBJECT IDENTIFIER. This is example creates
an object view, based on relational table EMP and the type definition EMP_T:
12.2 Synonyms
Use a synonym as shorthand or alias for an object name. You can refer to an object simply by coding its
synonym. Synonyms provide:
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Database Administrators create PUBLIC synonyms for use by everyone, while users can create their own
private synonyms for their own sole use. Synonyms can include the final parameter @DATABASE_LINK,
representing a database linka reference to a remote object on another computer. Syntax for CREATE,
ALTER, and DROP SYNONYM are:
CREATE [PUBLIC] SYNONYM synonym_name FOR object_name;
ALTER SYNONYM synonym_name COMPILE;
DROP [PUBLIC] SYNONYM synonym_name;
Like views, synonyms become invalid if the underlying object upon which they are based is dropped. The
ALTER COMPILE statement recompiles and revalidates a synonym.
Heres an example of creating a synonym:
CREATE SYNONYM emp FOR hr.employees ;
This example creates a PUBLIC synonym everyone can use that creates a shorthand name for a remote
table residing on a different computer:
12.3 Sequences
Sequences are a mechanism for generating unique integer values. They are sometimes used to generate
primary keys.
In SQL, the Oracle-generated sequence values are accessed through the pseudo-columns CURRVAL and
NEXTVAL. For example, if you create a sequence named ORDER_SEQUENCE, you could access the next
generated value from that sequence and use it in an INSERT statement like this:
INSERT INTO orders_table (order_number, order_date, customer_id)
VALUES (order_sequence.nextval, sysdate, 1505) ;
CURRVAL and NEXTVAL can be used in the:
QQ
LearnSmart
A CHECK constraint
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Here is the basic syntax to create a sequence. Default keywords are underlined:
CREATE SEQUENCE [schema.]sequence_name
[ INCREMENT BY number ]
[ START WITH number ]
[ MAXVALUE number | NOMAXVALUE]
[ MINVALUE number | NOMINVALUE]
[ CYCLE | NOCYCLE]
[ CACHE number | NOCACHE ]
[ ORDER | NOORDER] ;
Control the generated values by keywords START WITH, INCREMENT BY, MINVALUE, MAXVALUE, CYCLE, and
ORDER. CACHE speeds access by caching the specified number of values held in Oracle memory area,
the System Global Area or SGA, but also means values are lost when the database is shut down (or goes
down). This results in a gap in your sequence. Generated sequence numbers are guaranteed to be unique
and ordered but they are not guaranteed to be without any gaps. CACHE default value is 20.
Here is the example CREATE SEQUENCE statement used for the orders insertion example
of NEXTVAL above:
CREATE SEQUENCE order_sequence ;
Since this sequence assumes the defaults, it will start with 1, increment by 1, and have no minimum or
maximum value. 20 sequence values will be generated and stored in cache memory.
This sequence specifies that values start at 1,000 and increment by 10 each time. The NOCACHE keyword
reduces performance since pre-generated keys are not kept ready in memory, but also tends to reduce
sequence number gaps:
NOCACHE
NOCYCLE ;
12.4 Indexes
The purposes of indexes are to:
QQ
Indexes are implicitly created for you by Oracle when you define unique or primary key constraints, or you
can explicitly create them by issuing the CREATE INDEX statement.
There are two basic types of index:
LearnSmart
B-tree
Bitmap
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Unless you specify otherwise, indexes are created as b-tree by default. These work best with high
cardinality data (a wide range of values) and on big tables. Indexes may be ascending (ASC the default)
or descending DESC. To enforce key uniqueness within the index, specify keyword UNIQUE. Specifying
UNIQUE does not preclude the possibility of multiple NULL entries for columns that permit nulls. Indexes
containing more than one column are called composite indexes.
Create a bitmap index by keyword BITMAP. BITMAP indexes are recommended for low-cardinality data
(data having few different values, e.g., gender). They save space and work fast. They are probably not so
good if you frequently update the index column values. They are definitely not good for data with many
different values, ie high-cardinality data.
Function-based indexes allow you to create an index using a SQL function as long as that function is
deterministic (always gives the same results for the same inputs, however or whenever used).
Here is the basic index creation statement:
CREATE [UNIQUE | BITMAP] INDEX [schema.]index_name
ON [schema.]table_name (column [,column] ) ;
To DROP an index just:
DROP [schema.]index_name ;
Here are a few index creation examples. This creates a b-tree index:
CREATE INDEX emp_mgr_ix
ON employees (manager_id);
This creates a unique, composite index spanning the EMPLOYEE_ID, LAST_NAME, and
FIRST_NAME columns:
This statementt creates a bitmap index. Assumedly the column LIST_PRICE has a limited range
of possible values:
CREATE BITMAP INDEX product_bm_ix
ON product_information_part(list_price);
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Practice Questions
Chapter 1
1.
A schema is:
A. The collection of all the tables owned by a user
B. The collection of all database objects owned by a user
C. The collection of all data owned by a user
D. The collection of all programs and data owned by a user
1.
Chapter 2
1. When does a simple SELECT statement alter table data?
2. Which statement will label the output column with this word in all upper-case: LAST
Chapter 3
1. Choose the proper statement about this SQL query:
SELECT distinct job_id FROM employees
WHERE hire_date < 01-JAN-2000
AND WHERE salary < 15000 AND WHERE department_id <> 50 ;
A. The query will return rows matching the hire_date, salary and
department_id conditions
B. The query will not run because the not equals syntax <> is incorrect and must be !=
C. The query will not run because of the WHERE keywords
D. The query will not run because all WHERE conditions must be specified on
the same line
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Chapter 4
1. Why would you want to explicitly convert a value between data types rather than having
Oracle do it for you implicitly?
A. You dont know which data type Oracle will convert the value to.
B You always get more accurate results when you explicitly convert values yourself.
C. Performance. Explicit conversions are faster.
D. You have greater control and reliability, and explicitly document the conversion
when you code it yourself.
2. What is the difference between the CONCAT function and the concatenation operator?
A. The CONCAT function can also perform string replacements
B. The CONCAT function can take any number of string arguments
C. The concatenation operator can take any number of string arguments
D. The concatenation operator can also perform string replacement
Chapter 5
1. The NULLIF function:
A. Compares two parameters and returns NULL if they are equal and the
1st parm otherwise.
B. Tests its 1st parameter and returns the 2nd parm if the first is NULL. Otherwise it
returns the 1st parm.
C. Tests its 1st parameter. If it is NOT NULL, the 2nd parm is returned, otherwise the 3rd
parm is returned.
2. What will this return: TO_CHAR(TO_DATE(01-MAY-09,DD-MON-RR),Day)
Chapter 6
1. Which two templates reflect the correct order for SELECT statement keywords?
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Chapter 7
1. If you want to retrieve all rows that match between two tables and also the rows from one
table that do not have matches in the other, what kind of join do you want to perform?
Chapter 8
1. Which statement will delete staff whose department number is that of the lowest department
number in the ORG table?
A. DELETE FROM staff
WHERE dept =
(SELECT MIN(deptnumb) FROM org) ;
B. DELETE FROM staff
WHERE dept IN SOME
(SELECT MIN(deptnumb) FROM org) ;
C. DELETE * FROM staff
WHERE dept =
(SELECT MIN(deptnumb) FROM org) ;
D. DELETE * FROM staff s
WHERE salary >
(SELECT AVG(salary) FROM staff
WHERE dept = s.dept)
ORDER BY dept, id ;
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
2. In a correlated subquery:
A. The single-row subquery is executed only once, and its result is passed to
the outer query
B. The subquery is executed one time for each row in the parent query
C. The subquery is executed once per retrieval of all rows or a group of rows
D. None of the above
Chapter 9
1. Which statement is true?
2. You have three tables named A, B, and C. You want to remove all data from A and also remove
its data dictionary definition. You want to remove all rows from B as quickly as possible but
retain its data dictionary definition. You want to remove all rows from C but require logging of
any changes and for possible rollback. What do you do:
Chapter 10
1. You issue the following commands while in SQL*Plus:
SQL> update employees set salary = 100000 where employee_id= 101 ;
SQL> create table my_employee_table as select * from employees ;
SQL> delete from employees;
<<< Poof! Youre session ends as your clumsy cube-mate trips over
your computers power cord and spill his hot coffee on you! >>>
Assuming all statements are valid and all required objects are available, what is the result of
these statements?
A. The UPDATE, CREATE TABLE, and DELETE have all been applied to the database
B. The UPDATE and CREATE TABLE have been applied to the database but
not the DELETE
C. None of the three statements (UPDATE, CREATE TABLE, DELETE) have been applied to
the database because you did not get to issue a COMMIT
D. The UPDATE and the DELETE have been applied to the database because they are
DML statements but the CREATE TABLE DDL statement was not
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Chapter 11
1. Which statement is true about columns defined with the UNIQUE attribute
in table definitions?
2. Why do most people use the VARCHAR2 data type instead of CHAR?
A. VARCHAR2 is variable-length, so it saves space, and it permits columns up
to 2,000 bytes
B. CHAR was not supported by older releases of Oracle database
C. VARCHAR2 is variable-length, so it saves space, and it permits columns up
to 4,000 bytes
D. VARCHAR2 is variable-length, so it saves space. CHAR handles binary data
Chapter 12
1. For better performance with a large table with high-cardinality data, you should create which
kind of index?
A. A bitmap index
B. A bitmap index with a composite key on all relevant retrieval columns
C. A b-tree index
D. A function-based index
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
2. ANSWERS: A, B, C
SQL is a set-oriented language, meaning that one SQL statement can affect multiple rows of data in the
database. SQL lacks flow-of-control statements, which is why you need languages into which you can
embed SQL to create complete applications (like PL/SQL and Java). SQL*Plus and SQL Developer are client
tools that are specifically designed to help you run SQL statements. Answer D is incorrect because you
can embed SQL statements within PL/SQL programs.
Chapter 2
1. ANSWER: E
A SELECT statement is a read-only operation. It never changes data within tables. You can embed a SELECT
statement within an enclosing INSERT, UPDATE or DELETE statement, but it is the INSERT, UPDATE or
DELETE that changes the data (not the embedded SELECT statement.) Answer B is incorrect because the
SELECT statement does not have a CHANGE keyword. Answer C is incorrect because the Oracle SELECT
statement FOR UPDATE clause does not update data. It merely locks data for your update later on through
an UPDATE statement (see chapter 10 for full details on this). Answer D is incorrect because a SELECT
statement is a read-only operation.
2. ANSWER: C
The lack of any quotation marks means the column alias will appear in all upper-case in the output.
Answers A and B will not run, since aliases can not appear inside of single quotation marks. Answer D will
run because it uses double-quote marks around the alias, but it will list the alias in all lower-case letters as
last. Double-quote marks ensure no translation to all upper-case letters occurs.
Chapter 3
1. ANSWER: C
A SELECT statement can only have one WHERE keyword, and this one incorrectly has three. Answer A
is incorrect because the query will not run because it has more than one WHERE keyword. Answer B is
incorrect because <> and != are equivalent and coding either is valid. Answer D is incorrect because SQL
statements can span lines, as long as they are broken apart between and not within words, and as long as
they are terminated by a semi-colon.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
2. ANSWER: B
B is correct because the default for DEFINE is ON. DEFINE has two uses, one of which is the allow you
to define session variables (the other is to list current session variables and their values). Answer A is
incorrect because the default for DEFINE is ON. Answer C is incorrect because UNDEFINE is used to
remove session variables, not DEFINE. Answer D is incorrect because VERIFY is used to display the values of
session variables before and after their substitution, not DEFINE.
Chapter 4
1. ANSWER: D
When converting a data type yourself you have more control and can explicitly state the data type of the
result. Answer A is incorrect because you can definitely determine which data type Oracle will convert the
value to if you look it up in the Oracle documentation. Answer B is incorrect because you could possibly
get more accurate results than Oracle, but this depends on what you code and the situation. Answer C is
incorrect in that performance for conversions is not appreciably different whether you specify it or Oracle
does it implicitly.
2. ANSWER: C
A big advantage to the concatenation operator over the CONCAT function is that you can splice multiple
input strings together into one string in one command. Answer A is incorrect because the CONCAT
function can only concatenate strings, it can not perform string replacements (use the REPLACE
function for that). Answer B is incorrect because the CONCAT function always takes exactly two
input arguments. Answer D is incorrect because the concatenation operator can not perform string
replacements, it only performs concatenation.
Chapter 5
1. ANSWER: A
The NULLIF function has two mandatory input parameters. It compares them and returns NULL if they
are identical and the 1st parm otherwise. Answer B is incorrect because it is the definition of how the NVL
function works, not the NULLIF function. Answer C is incorrect because it is the definition of how the NVL2
function works, not the NULLIF function.
2. ANSWER: C
The DD-MON-RR parameter is missing a right single quote mark, so the syntax error results. Answer A is
incorrect because of the syntax error. If there were no missing single quote this answer would be correct.
Answer B is incorrect due to the syntax error. Answer D is incorrect because all the data types in the
clause are compatible.
Chapter 6
1. ANSWERS: B, E
These two orderings are correct. Answers A, C, and D are incorrect because the ORDER BY must always go
last among SELECT clauses (not HAVING or GROUP BY). Answer F is incorrect because HAVING can never
be coded in a SELECT statement without a GROUP BY.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
2. ANSWER: D
The maximum allowable nesting of group functions is two levels. Since the first line of this statement
nests group functions three levels deep, it fails with the message indicated. Remember that single-row
functions do not have this limitation and can be nested as deeply as you like. Answers A, B, and C are
incorrect because this statement fails with the syntax error message given in Answer D.
Chapter 7
1. ANSWER: E
A left or right outer join retrieves all matching rows plus rows from one of the tables that do not have
matches in the other. A is incorrect because full outer joins retrieve all matching rows plus all rows
from both tables that do not have matches in the other. Answer B is incorrect because a Cartesian join
produces all combinations of rows from both tables. Answer C is incorrect because an equijoin retrieves
matching rows from the tables only. Answer D is incorrect because an nonequijoin match column
values based on an inequality condition. Answer F is incorrect for the same reason Answer B is incorrect.
Cartesian joins and Cross joins are the same thing.
2. ANSWER: D
Table aliases are a short-hand way to refer to tables. Usually they are used to qualify columns so that
those references are unambiguous since join statements refer to multiple tables. Answer A is incorrect
because the FROM clause tells Oracle which tables to join. Answer B is incorrect because you dont use
table aliases to rename tables in output reports. Answer C is incorrect because table aliases have no
relationship to column aliases.
Chapter 8
1. ANSWER: A
Answer A is correct because the inner query returns the lowest department number from the ORG
table, and then the outer query deletes all staff with this department number. Answer B is syntactically
incorrect because there is no IN SOME operator in Oracle SQL. IN and SOME are individual keywords that
are used separately. Answer C is syntactically incorrect because DELETE does not take an asterisk as an
operand. It should be DELETE FROM STAFF not DELETE * FROM STAFF. Answer D is incorrect for the same
reason as Answer C. It also is incorrect because it returns an average salary from the subquery, not a
lowest department number.
2. ANSWER: B
Answer B is correct because a correlated subquery executes (evaluates) the subquery one time for each
parent row. Answer A is incorrect because it refers to the behavior of regular single-row subqueries,
not correlated subqueries. Answer C is incorrect because it describes group functions, not correlated
subqueries. Answer D is incorrect because Answer B is correct.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
Chapter 9
1. ANSWER: B
This answer is correct because UNION ALL does not sort results and it does not remove duplicates.
Answer A is incorrect because UNION ALL does not sort results nor does it remove duplicates. Answer C
is incorrect because UNION sorts results and removes duplicates. Answer D is incorrect because UNION
removes duplicates. Answer E is incorrect because UNION sorts results.
2. ANSWER: B
DROP removes a table and its data, TRUNCATE quickly removes data but leaves the data dictionary
definition intact, and DELETE without a WHERE clause deletes all rows from a table while logging
changes for possible rollback. Answer A is incorrect because DELETE with no WHERE clause can not
handle the requirements for table B. Answer C is incorrect because TRUNCATE can only accomplish the
objectives for table B. Answer D is incorrect because DELETE without a WHERE clause is not as fast as
TRUNCATE for the requirements of table B, and because TRUNCATEing table C ensures no logging and
no possible ROLLBACK.
Chapter 10
1. ANSWER: B
Answer B is correct. The CREATE TABLE issues an implicit COMMIT that applied it and the prior UPDATE
statement changes to the database. The DELETE was not applied to the database because no explicit
or implicit COMMIT occurred after it was issued. Instead an involuntary end-of-session occurred which
prevented the DELETE change from being committed to the database. Answer A is incorrect because the
DELETE was not committed to the database. Answer C is incorrect because the CREATE TABLE implicitly
committed itself and the prior UPDATE changes to the database. Answer D is incorrect because whether
they changes were committed to the database is not a mere function of DML versus DDL. As correct
Answer B shows, the sequence of statements is also critical to determining what changes are committed
to the database.
2. ANSWER: A
SELECT with FOR UPDATE locks table rows until you issue a COMMIT or ROLLBACK. Before you do you
typically update those rows. Answer B is incorrect because the SELECT with UPDATE statement itself does
not update any data. Answer C is correct, in that you are locking out other users from updating the data
until you issue a COMMIT or ROLLBACK. But it is not your main goal when issuing this statement. Answer
A gives the true purpose. Answer D is incorrect because 11g supports this SQL statement.
Chapter 11
1. ANSWER: C
The UNIQUE attribute means all values inserted into the table for that column must be unique. But it does
not prevent multiple rows from being inserted with NULL for that column. Answer A is incorrect because
UNIQUE does not prevent insertion of rows with NULL for the column defined as UNIQUE. Answer B is
incorrect because UNIQUE does not prevent insertion of multiple rows with NULL for the column. Answer
D is incorrect because answer C is correct.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals
1-800-418-6789
2. ANSWER: C
VARCHAR2 is variable-length so it saves space, and it permits a maximum column length of 4,000
characters. Answer A is incorrect because VARCHAR2 permits up to 4,000 bytes, not 2,000 (which is the
limit for CHAR columns). Answer B is incorrect because CHAR is supported on older releases of Oracle.
Answer D is incorrect because CHAR handles character data, not binary data.
Chapter 12
1. ANSWER: C
A b-tree index is recommended for improving performance for high-cardinality data in large tables.
High-cardinality data are rows that have a large range of different values. Answer A is incorrect because
bitmap indexes best improve performance for low-cardinality data. Answer B is incorrect because bitmap
indexes best improve performance for low-cardinality data. Answer D is incorrect because functionbased indexes are useful when you want to access data by applying some function to the data; they have
nothing to do with data cardinality and the size of the table.
2. ANSWER: C
The CREATE OR REPLACE VIEW statement is specifically designed for this purpose, to help you easily
change view definitions. Answer A is incorrect because it will accomplish the task but it is not as easy or
efficient as Answer C. Answer B is incorrect because the ALTER VIEW statement can not change column
definitions in views. Answer D is incorrect because it never actually changes the column in the original
view. This approach would force you to give the new view a different name, and you would leave old
unused views around.
LearnSmart
Practice Exams
Audiobooks
Exam Manuals