SQL
SQL
SQL
Tell Me / Show Me
DUAL Table
The DUAL table has one row called "X" and one column
called "DUMMY." The DUAL table is used to create SELECT
statements and execute functions not directly related to a
specific database table. Queries using the DUAL table return
one row as a result. DUAL can be useful to do calculations
and also to evaluate expressions that are not derived from a
table.
DUMMY
X
Tell Me / Show Me
DUAL Table (continued)
DUAL will be used to learn many of the single-
row functions. In this example the DUAL table
is used to execute a SELECT statement that
contains a calculation. As you can see the
SELECT statement returns a value that does
not exist in the DUAL table. The value
returned is a result of the calculation sdp_s01_l01_a02
executed.
SELECT (319/29) + 12
FROM DUAL;
(319/29)+12
23
Tell Me / Show Me
Single-Row Character Functions
Single-row character functions are divided into two
categories:
Tell Me / Show Me
Single-Row Character Functions (continued)
Case-manipulation functions are important because you may
not always know in which case (upper, lower or mixed) the
data is stored in the database. Case manipulation allows you
to temporarily convert the database data to a case of your
choosing. Mismatches between database case storage and
query case requests are avoided.
Tell Me / Show Me
Case Manipulation
Functions CHARACTER FUNCTIONS
Case-manipulation
functions are used to Character Functions
convert from lower to upper
or mixed case. These
conversions can be used to
format the output and can
also be used to search for
specific strings. Case-Manipulation Character-Manipulation
Functions Functions
LOWER CONCAT
Case-manipulation UPPER SUBSTR
functions can be used in INITCAP LENGTH
most parts of a SQL INSTR
LPAD | RPAD
statement.
TRIM
REPLACE
Tell Me / Show Me
Case Manipulation Functions (continued)
Case-manipulation functions are often helpful when you are
searching for data and you do not know whether the data you
are looking for is in upper or lower case. From the point of view
of the database, ‘V’ and ‘v’ are NOT the same character and as
such, you need to search using the correct case.
SELECT title
FROM d_cds
WHERE LOWER(title) = 'carpe diem';
Tell Me / Show Me
Case Manipulation Functions (continued)
UPPER(column | expression) converts alpha characters
to upper-case.
SELECT title
FROM d_cds
WHERE UPPER(title) = 'CARPE DIEM';
SELECT title
FROM d_cds
WHERE INITCAP(title) = 'Carpe Diem';
Tell Me / Show Me
Character Manipulation Functions (continued)
Character-manipulation functions are used to extract, change, format,
or alter in some way a character string.
One or more characters or words are passed into the function and
the function will then perform its functionality on the input character
strings and return the changed, extracted, counted, or altered value.
Function Result
CONCAT('Hello', 'World') HelloWorld
SUBSTR('HelloWorld', 1, 5) Hello
Tell Me / Show Me
Character Manipulation Functions (continued)
• LENGTH: Shows the length of a string as a number
value.
• INSTR: Finds the numeric position of a named character.
• LPAD: Pads the left side of a character, resulting in a
right-justified value.
Function Result
LENGTH('HelloWorld') 10
INSTR('HelloWorld','W') 6
LPAD(salary, 10,’*’) *****24000
Tell Me / Show Me
Character Manipulation Functions (continued)
• RPAD: Pads the right-hand side of a character, resulting
in a left-justified value.
• TRIM: Removes all specified characters from either the
beginning or the ending of a string. The syntax for the trim
function is:
TRIM( [ leading | trailing | both
[character(s) to be removed ] ] string to trim)
Function Result
RPAD(salary, 10, '*') 24000*****
TRIM('H' FROM 'HelloWorld') elloWorld
Tell Me / Show Me
Character Manipulation Functions (continued)
REPLACE: Replaces a sequence of characters in a string with
another set of characters. The syntax for the REPLACE function is:
Function Changes
REPLACE('JACK and JUE', 'J', 'BL') BLACK and BLUE
Tell Me / Show Me
Using Column Aliases With Functions
All functions operate on values that are in parentheses, and
each function name denotes its purpose, which is helpful to
remember when constructing a query. Often times a column
alias is used to name a function. When a column alias is
used, the column alias appears in the output instead of the
actual function syntax.
In the following examples, the alias "User Name" has
replaced the function syntax in the first query.
By default, the column name in a SELECT statement
appears as the column heading. In the second query
example, however, there is no column in the table for the
results produced, so the query syntax is used instead.
Tell Me / Show Me
Using Column Aliases With Functions (continued)
SELECT LOWER
(last_name)||LOWER(SUBSTR(first_name,1,1))
AS "User Name"
User Name
FROM f_staffs;
does
millerb
tuttlem
LOWER (last_name)||LOWER(SUBSTR(first_name,1,1))
does
millerb
tuttlem
Tell Me / Show Me
Substitution Variables
Occasionally you may need to run the same query with many
different values to get different result sets. Imagine for instance
if you had to write a report of employees and their
departments, but the query must only return data for one
department at a time. Without the use of substitution variables,
this request would mean you would have to continually edit the
same statement to change the WHERE-clause.
Tell Me / Show Me
Substitution Variables (continued)
So this original query:
SELECT first_name, last_name, salary, department_id
FROM employees
WHERE department_id = 10 (and then 20, 30, 40…)
Note the use of : in front of dept_id. It is the colon that is the magic
bit and makes Oracle Application Express accept the variable
value.
Tell Me / Show Me
Substitution Variables (continued)
Substitution variables are treated as character strings in Oracle Application
Express, which means that when passing in character or date values you do not
need the single quotation marks you would normally use to enclose the strings.
SELECT *
FROM employees
WHERE last_name = :l_name
When you click Run, a pop-up like the following is displayed by Oracle
Application Express:
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
Summary
Objectives Summarized
In this lesson you have learned to:
• Select and apply single-row functions that perform case
conversion and/or character manipulation
• Select and apply character case-manipulation functions
LOWER, UPPER, and INITCAP in a SQL query
• Select and apply character-manipulation functions
CONCAT, SUBSTR, LENGTH, INSTR, LPAD, RPAD,
TRIM, and REPLACE in a SQL query
• Write flexible queries using substitution variables
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
sdp_s01_l02_a01
Tell Me / Show Me
Number Functions
The three number functions are:
• ROUND
• TRUNC
• MOD
sdp_s01_l02_a02
Tell Me / Show Me
ROUND
ROUND can be used with both numbers and
dates. It is mainly used to round numbers to a
specified number of decimal places, but it can
also be used to round numbers to the left of the
decimal point.
sdp_s01_l02_a03
Syntax
ROUND(column|expression, decimal
places)
Note that if the number of decimal places is not
specified or is zero, the number will round to no
decimal places.
ROUND(45.926) 46
ROUND(45.926, 0) 46
Tell Me / Show Me
ROUND (continued)
If the number of decimal places is a positive number, the
number is rounded to that number of decimal places.
ROUND(45.926, 2) 45.93
ROUND(45.926, -1) 50
Tell Me / Show Me
TRUNC
The TRUNC function can be used with both numbers and dates.
It is mainly used to terminate the column, expression, or value to
a specified number of decimal places. When TRUNC is used, if
the number of decimal places is not specified, then the specified
number defaults to zero.
Syntax
Tell Me / Show Me
TRUNC (continued)
As with ROUND, if the TRUNC expression does not specify
the number of decimal places or specifies a zero, the
number is truncated to zero decimal places.
TRUNC (45.926, 0) 45
TRUNC (45.926) 45
Tell Me / Show Me
MOD
The MOD function finds the remainder of one value
divided by another value.
Tell Me / Show Me
MOD (continued)
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
Number functions
MOD
ROUND
TRUNC
Summary
Objectives Summarized
In this lesson you have learned to:
• Select and apply the single-row number functions
ROUND, TRUNC, and MOD in a SQL query
• Distinguish between the results obtained when
TRUNC is applied to a numeric value and
ROUND is applied to a numeric value
• State the implications for business when applying
TRUNC and ROUND to numeric values
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
Displaying Dates
The default display format for dates is
DD-MON-RR -- that is, 02-DEC-99.
The default display and input format for any date is DD-
MON-RR. Valid Oracle dates are between January 1, 4712
B.C., and December 31, 9999 A.D. This represents the
range of dates that you can store successfully in an Oracle
database.
Tell Me / Show Me
SYSDATE
When a record with a date column is inserted
into a table, the century information is picked
up from the SYSDATE function. SYSDATE is
a date function that returns the current
sdp_s01_l03_a01
database server date and time.
SYSDATE
Tell Me / Show Me
DATE Data Type
The DATE data type always stores year
information as a four-digit number internally:
two digits for the century and two digits for sdp_s01_l03_a01
the year. For example, the Oracle database
stores the year as 1996 or 2004, not just as
96 or 04.
Tell Me / Show Me
Working with Dates
Tell Me / Show Me
Date Functions
The date functions shown in the table operate on Oracle
dates. All of the date functions return a value with a DATE
data type except the MONTHS_BETWEEN function, which
returns a numeric data type value.
Function Description
MONTHS_BETWEEN Number of months between two dates
ADD_MONTHS Add calendar months to date
NEXT_DAY Next day of the date specified
LAST_DAY Last day of the month
ROUND Round date
TRUNC Truncate date
Tell Me / Show Me
Date Functions (continued)
Here is another example of a query using multiple date functions.
SELECT employee_id, hire_date,
ROUND(MONTHS_BETWEEN(SYSDATE, hire_date)) AS TENURE,
ADD_MONTHS (hire_date, 6) AS REVIEW,
NEXT_DAY(hire_date, 'FRIDAY'),
LAST_DAY(hire_date)
FROM employees
WHERE MONTHS_BETWEEN (SYSDATE, hire_date) > 36;
Tell Me / Show Me
Date Functions (continued)
Below are the results from queries using ROUND
and TRUNC date functions with SYSDATE
(assume SYSDATE = '25-JUL-95').
Function Result
ROUND (SYSDATE, 'MONTH') 01-AUG-95
ROUND (SYSDATE, 'YEAR') 01-JAN-96
TRUNC (SYSDATE, 'MONTH') 01-JUL-95
TRUNC (SYSDATE, 'YEAR’) 01-JAN-95
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
ADD_MONTHS
LAST_DAY
MONTHS_BETWEEN
NEXT_DAY
SYSDATE
Summary
Objectives Summarized
In this lesson, you have learned to:
• Select and apply the single-row functions
MONTHS_BETWEEN, ADD_MONTHS, NEXT_DAY,
LAST_DAY, ROUND, and TRUNC that operate on
date data
• Explain how date functions transform Oracle dates
into date data or a numeric value
• Demonstrate proper use of the arithmetic operators
with dates
• Demonstrate the use of SYSDATE and date functions
• State the implications for world businesses to be able
to easily manipulate data stored in date format
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
Data Types
When a table is created for a database, the SQL
programmer must define what kind of data will be stored in
each field of the table. In SQL, there are several different
data types. These data types define the domain of values
that each column can contain. For this lesson, you will use:
VARCHAR2
CHAR
NUMBER
DATE
Tell Me / Show Me
Data Types Described
Tell Me / Show Me
EXPLICIT DATE-TYPE CONVERSION
Tell Me / Show Me
Date Conversion to Character Data
It is often desirable to convert dates stored in a database in the default DD-
MON-YY format to another format specified by you. The function to
accomplish this task is:
Tell Me / Show Me
YYYY Full year in numbers
Date Conversion to
YEAR Year spelled out
Character Data
MM Two-digit value for month
(continued) MONTH Full name of the month
The tables show the MON Three-letter abbreviation of the month
Tell Me / Show Me
Date Conversion to Character Data (continued)
If an employee‟s hire date was 04-MAY-04, the format model
using fm would have returned May 4, 2004, suppressing the
leading zero.
Tell Me / Show Me
Date and Time Format Models YYYY Full year in numbers
Tell Me / Show Me
Number Conversion to Character Data (VARCHAR2)
Numbers stored in the database have no formatting. This
means that there are no currency signs/symbols, no
commas, no decimals or other formatting. To add
formatting, you first need to convert the number to a
character format. This conversion is especially useful with
concatenation.
Tell Me / Show Me
Number Conversion to ELEMENT DESCRIPTION EXAMPLE RESULT
Character Data 9 Numeric position (# of 999999 1234
9‟s determine width)
(VARCHAR2) (continued)
0 Display leading zeros 099999 001234
The table illustrates some of $ Floating dollar sign $999999 $1234
the format elements available L Floating local currency L999999 FF1234
symbol
to use with TO_CHAR
. Decimal point in position 999999.99 1234.00
functions. specified
, Comma in position 999,999 1,234
specified
SELECT TO_CHAR(cost, MI Minus signs to right 999999MI 1234-
'$99,999') COST (negative values)
PR Parenthesize negative 999999PR <1234>
FROM d_events; numbers
EEEE Scientific notation ( must 99.999EEEE 1,23E+03
have four EEEE)
V Multiply by 10 n times 9999V99 9999V99
COST (n= number of 9‟s after
V)
$8,000 B Display zero values as B9999.99 1234.00
blank, not 0
$10,000
Tell Me / Show Me
Number Conversion to ELEMENT DESCRIPTION EXAMPLE RESULT
(continued) $
L
Floating dollar sign
Floating local currency
$999999
L999999
$1234
FF1234
symbol
Can you identify the . Decimal point in position 999999.99 1234.00
format models used to specified
V)
9,000.00 B Display zero values as B9999.99 1234.00
blank, not 0
0004422
Tell Me / Show Me
Character Conversion to Number
It is often desirable to convert a character string to a number. The
function for this conversion is:
TO_NUMBER(character string, 'format model')
Tell Me / Show Me
Character Conversion to Number (continued)
SELECT TO_NUMBER('450', '9999') + 10 AS
"Number Change" FROM DUAL;
Number Change
460
Tell Me / Show Me
Character Conversion to Date
To convert a character string to a date format, use:
Tell Me / Show Me
Character Conversion to Date (continued)
When making a character-to-date conversion, the fx (format
exact) modifier specifies exact matching for the character
argument and the date format model.
Tell Me / Show Me
fx Modifier Rules
The fx modifier rules are:
• Punctuation and quoted text in the character argument
must match the corresponding parts of the format
model exactly (except for case).
• The character argument cannot have extra blanks.
Without fx, the Oracle Server ignores extra blanks.
• Numeric data in the character argument must have the
same number of digits as the corresponding element in
the format model. Without fx, numbers in the character
argument can omit leading zeros.
Tell Me / Show Me
RR Date Format and YY
Current Specified RR Format YY Format
Date Format Year Date
1995 27-OCT-95 1995 1995
1995 27-OCT-17 2017 1917
It hasn't been that long since 2001 27-OCT-17 2017 2017
the century changed from 2001 27-OCT-95 1995 2095
1900 to 2000. Along with this
change came considerable If the specified two-digit
confusion as to whether a year is:
Tell Me / Show Me
A Few Simple Rules
If the date format is specified with the YY or YYYY format, the
return value will be in the same century as the current century.
So, if the year is 1995 and you use the YY or YYYY format, all
is well and the dates will be in the 1900s. However, if the
current year is 2004 and you use the YY or YYYY format for a
date such as 1989, you will get 2089! Maybe not what you
intended.
Tell Me / Show Me
A Few Simple Rules
(continued)
If the date format is specified with If the specified two-digit
year is:
the RR or RRRR format, the return
0-49 50-99
value has two possibilities.
If two digits 0-49 The return The return
If the current year is between 00- of the date is in date is in
current the current the century
49: year are: century before the
• Dates from 0-49: The date current one
Tell Me / Show Me
A Few Simple Rules Current Specified RR Format YY Format
(continued) Year Date
1995 27-OCT-95 1995 1995
When I query my employee 1995 27-OCT-17 2017 1917
database using the following 2001 27-OCT-17 2017 2017
statement, it returns every 2001 27-OCT-95 1995 2095
row in the table. I know there
are only a few employees If the specified two-digit
who were hired before 1990. year is:
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
CHAR
DATE
DD date format
Conversion function
fm
NUMBER
RR date format
TO_CHAR
TO_DATE
TO_NUMBER
VARCHAR2
Summary
Objectives Summarized
In this lesson, you have learned to:
• Provide an example of an explicit data-type conversion
and an implicit data-type conversion
• Explain why it is important, from a business
perspective, for a language to have built-in data-
conversion capabilities
• Construct a SQL query that correctly applies
TO_CHAR, TO_NUMBER and TO_DATE single-row
functions to produce a desired result
• Apply the appropriate date and/or character format
model to produce a desired output
• Explain and apply the use of YYYY and RRRR to return
the correct year as stored in the database
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
How Functions are Evaluated
Up to now, you have applied single-row functions in simple
statements. It is possible, however, to nest functions to any depth.
What is important to know is how nested functions are evaluated. The
following example, is a nested function. The evaluation process
begins from the innermost level to the outermost level.
Tell Me / Show Me
How Functions are Evaluated (continued)
• Step 1: The hire date is going to have six months added to it.
• Step 2: The first Friday following the future day will be
identified.
• Step 3: The default date format will be formatted to read and
display the Friday in a format similar to: Friday, December
18th, 1987, and will appear in the output under the column
name "Next Evaluation."
Tell Me / Show Me
Functions Pertaining to Null Values
At the beginning of the course, the term "null"
was introduced. If you remember, it's the value sdp_s02_l02_a01
that is unavailable, unassigned, unknown, or
inapplicable. We basically cannot test to see if it
is the same as another value, because we do not
know what value it has. It isn't equal to anything,
not even zero! But just because it really isn't
anything doesn't mean that it is not important.
Imagine this question: Is it true that X = Y? In
order to answer you have to know the values of
X and Y. Oracle has four general functions that
pertain to the use of null values. The four
functions are:
- NVL
- NVL2
- NULLIF
- COALESCE
Tell Me / Show Me
NVL Function
The NVL function converts a null value to a known value of a
fixed datatype, either date, character or number. The data types
of the null value column and the new value must be the same.
The NVL function is:
NVL (value or column that may contain a null, value to replace
the null)
The following query uses the NVL function with character data
types:
Tell Me / Show Me
NVL Function (continued)
The data types of the null value column and the new value
must be the same as shown in the following examples:
NVL(auth_expense_amt,0)
NVL(hire_date,'01-JAN-97')
NVL(speciality,'None Yet')
Tell Me / Show Me
NVL Function (continued)
You can use the NVL function to convert column values
containing nulls to a number before doing calculations. When
an arithmetic calculation is performed with null, the result is
null. The NVL function can convert the null value to a number
before arithmetic calculations are done to avoid a null result.
Tell Me / Show Me
NVL Function (continued)
In the example, the auth_expense_amt column in the
D_PARTNERS table contains null values. The NVL function
is used to change the null to zero before arithmetic
calculations.
SELECT first_name,
last_name,NVL(auth_expense_amt, 0) * 1.05 AS Expenses
FROM D_Partners;
Tell Me / Show Me
NVL2 Function
The NVL2 function evaluates an expression with three
values. If the first value is not null, then the NVL2 function
returns the second expression.
Tell Me / Show Me
NVL2 Function (continued)
The NVL2 function is:
NVL2 (expression 1 value that may contain a null, expression 2
value to return if expression 1 is not null, expression 3 value
to replace if expression 1 is null)
Tell Me / Show Me
NULLIF Function
The NULLIF function compares two functions. If they are equal,
the function returns null. If they are not equal, the function returns
the first expression.
The NULLIF function is:
NULLIF(expression 1, expression 2)
Tell Me / Show Me
COALESCE Function
The COALESCE function is an extension of the NVL
function, except COALESCE can take multiple values.
The word "coalesce" literally means "to come together"
and that is what happens.
Tell Me / Show Me
COALESCE Function
(continued)
The COALESCE function is: SELECT last_name,
COALESCE(commission_pct,
COALESCE (expression 1, salary, 10) comm
expression 2, FROM employees
ORDER BY commission_pct;
...expression n)
Grant .15
Zlotkey .2
Examine the SELECT statement
Taylor .2
from the employees table shown at
Abel .3
right. Which employees do not
receive a commission? How can King 24000
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
NVL
NVL2
NULLIF
COALESCE
Summary
Objectives Summarized
In this lesson, you have learned to:
• Demonstrate and explain the evaluation of a nested
function
• List at least four general functions that work with any
data type and relate to handling null values
• Explain the use of the COALESCE and the NVL
functions
• Explain the use of general functions to deal with null
values in data
• Construct and execute a SQL query that correctly
applies NVL, NVL2, NULLIF and COALESCE single-
row functions
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
Conditional Expressions
The two conditional expressions are CASE and DECODE.
You have already studied NULLIF, which is logically
equivalent to the CASE expression in that CASE
compares two expressions. If the two expressions are
equal, then return null; if they are not equal, then return
the first expression.
CASE Expression
The CASE expression basically does the work of an IF-
THEN-ELSE statement. Data types of the CASE, WHEN,
and ELSE expressions must be the same.
Tell Me / Show Me
CASE Syntax
CASE expr WHEN comparison_expr1 THEN return_expr1
[WHEN comparison_expr2 THEN return_expr2
WHEN comparison_exprn THEN return_exprn
ELSE else_expr]
END
Tell Me / Show Me
DECODE Expression
The DECODE function evaluates an expression in a similar way to
the IF-THEN-ELSE logic. DECODE compares an expression to
each of the search values. The syntax for DECODE is:
DECODE(columnl|expression, search1, result1
[, search2, result2,...,]
[, default])
If the default value is omitted, a null value is returned where a
search value does not match any of the values.
Tell Me / Show Me
DECODE Expression (continued)
Examine the example:
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
Conditional expression
CASE
DECODE
Summary
Objectives Summarized
In this lesson, you have learned to:
• Compare and contrast the DECODE and CASE
functions
• Construct and execute a SQL query that correctly uses
the DECODE and CASE functions
• Construct and execute two methods for implementing IF-
THEN-ELSE conditional logic
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
Join Commands
There are two sets of commands or syntax which can be
used to make connections between tables in a database:
Tell Me / Show Me
ANSI
ANSI stands for American National Standards Institute.
Founded in 1918, ANSI is a private, non-profit organization
that administers and coordinates the U.S. voluntary
standardization and conformity assessment system.
Reference: http://www.ansi.org/default.aspx
Tell Me / Show Me
SQL
Structured Query Language (SQL) is the information-
processing industry-standard language of relational database
management systems (RDBMS).
Tell Me / Show Me
NATURAL JOIN
Equijoin
An Oracle proprietary equijoin returns
all rows whose values match in both =
tables.
ANSI/ISO SQL: 1999
Natural
The ANSI/ISO SQL: 1999 join that
Join
accomplishes the same result is called
a natural join.
Tell Me / Show Me
NATURAL JOIN (continued)
As shown in the sample code, when using a natural
join, it is possible to join the tables without having to
explicitly specify the columns in the corresponding sdp_s04_l02_a01
table. However, the names and data types in both
columns must be the same.
Tell Me / Show Me
NATURAL JOIN (continued)
Here is another example:
Tell Me / Show Me
CROSS JOIN
sdp_s04_l02_a02
An Oracle Proprietary Cartesian Product joins
every row in one table to every row in the other
table.
Tell Me / Show Me
Cross Join Example
SELECT name, event_date, loc_type, rental_fee
FROM d_events CROSS JOIN d_venues;
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
Cross Join
Natural Join
Summary
Objectives Summarized
In this lesson you have learned to:
• Compose and execute a natural join using ANSI-99
SQL join syntax
• Create a cross join using ANSI-99 SQL join syntax
• Define the relationship between a cross join and a
Cartesian product
• Define the relationship between a natural join and
an equijoin
• Explain why it is important to have a standard for
SQL as defined by ANSI
• Provide evidence to answer the question “Why is it
important, from a business perspective, for a
language to be able to combine information from
multiple data sources?
Copyright © 2011, Oracle. All rights reserved. 13
Cross Joins and Natural Joins
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
USING Clause
In a natural join, if the tables have columns with the same
names but different data types, the join causes an error.
Tell Me / Show Me
USING Clause (continued)
The query shown is an example of the USING clause. The
columns referenced in the USING clause should not have a
qualifier (table name or alias) anywhere in the SQL statement.
Tell Me / Show Me
USING Clause (continued)
The USING clause allows us to use WHERE to restrict
rows from one or both tables:
Tell Me / Show Me
ON Clause
What if the columns to be joined have different names, or if
the join uses non-equality comparison operators such as <, >
or BETWEEN ?
Tell Me / Show Me
ON Clause Example
In this example, the ON clause is used in a self-join where the
same table is given two different references. In the employees table,
some employees are also managers. The self-join is used to select
those employees who are also managers.
EMP MGR
Kochhar King
Higgins Kochhar
……… ………
Tell Me / Show Me
ON Clause with WHERE Clause
Here is the same query with a WHERE clause to restrict the
rows selected.
Higgins Kochhar
Hunold De Haan
Tell Me / Show Me
Joining Three Tables
Both USING and ON can be used to join three or more tables.
Tell Me / Show Me
Joining Three Tables Example
SELECT last_name, event_date, t.description
FROM d_clients c JOIN d_events e
USING (client_number)
JOIN d_themes t
ON (e.theme_code = t.code);
Tell Me / Show Me
Join Comparison
Comparing Oracle Proprietary Joins with ANSI/ISO SQL:
1999 Joins
Oracle Proprietary Join ANSI/ISO SQL: 1999 Equivalent
Equijoin Natural Join (if the join columns have the same name
and data type)
USING clause (if the columns have the same name but
different data types)
Non-equijoin ON clause
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
USING clause
ON clause
Summary
Objectives Summarized
In this lesson you have learned to:
• Construct and execute a join with the ANSI-99
USING and ON clauses
• Construct and execute an ANSI-99 query that
joins three tables
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
INNER And OUTER Joins
In ANSI-99 SQL, a join of two or more tables that return only
matched rows is called an inner join.
Outer join syntax uses the terms “left, full, and right.” These
names are associated with the order of the table names in the
FROM clause of the SELECT statement.
Tell Me / Show Me
LEFT and RIGHT OUTER SELECT e.last_name, d.department_id, d.department_name
Joins FROM employees e
LEFT OUTER JOIN departments d
In the example shown of a ON (e.department_id = d.department_id);
left outer join, note that the
table name listed to the left
of the words “left outer join" LAST_NAME DEPT_ID DEPT_NAME
is referred to as the "left King 90 Executive
table.“ Kochhar 90 Executive
…
Whalen 10 Administration
This query will return all Hartstein 20 Marketing
matched rows as well as all Fay 20 Marketing
employee last names even if Higgins 110 Accounting
they aren’t assigned to a Gietz 110 Accounting
Grant
department.
Tell Me / Show Me
LEFT and RIGHT OUTER
Joins (continued) SELECT e.last_name, d.department_id, d.department_name
FROM employees e
This right outer join would RIGHT OUTER JOIN departments d
return all department IDs and ON (e.department_id = d.department_id);
department names even if no
employees were assigned to
them. LAST_NAME DEPT_ID DEPT_NAME
King 90 Executive
Kochhar 90 Executive
…
Whalen 10 Administration
Hartstein 20 Marketing
Fay 20 Marketing
Higgins 110 Accounting
Gietz 110 Accounting
190 Contracting
Tell Me / Show Me
FULL OUTER Join
It is possible to create a join condition to retrieve all matching
rows and all unmatched rows from both tables in a join.
Using a full outer join solves this problem. The results set of a full
outer join includes all rows in both tables even if there is no match
in the other table.
Tell Me / Show Me
FULL OUTER Join
Example SELECT e.last_name, d.department_id, d.department_name
FROM employees e
The example shown is FULL OUTER JOIN departments d
a full outer join. ON (e.department_id = d.department_id);
Tell Me / Show Me
Join Scenario
Construct a join to display a list of Global Fast Foods
customers and their orders. Include all customers whether or
not they have placed an order.
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
Summary
Objectives Summarized
In this lesson you have learned to:
• Compare and contrast an inner and an outer join
• Construct and execute a query to use a left
outer join
• Construct and execute a query to use a right
outer join
• Construct and execute a query to use a full
outer join
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
100 Steven King SKING 515.123.4567 17-JUN-87 AD_PRES 24000 (null) (null) 90
101 Neena Kochhar NKOCHHA 515.123.4568 21-SEP-89 AD_VP 17000 (null) 100 90
R
Tell Me / Show Me
SELF-JOIN
To join a table to itself, the table is given two names or aliases.
This will make the database “think” that there are two tables.
Choose alias names that relate to the data's association
with that table.
EMPLOYEES (worker) EMPLOYEES (manager)
employee_id last_name manager_id employee_id last_name
Tell Me / Show Me
SELF-JOIN Example
Here is another example of a self-join. In this
example of a band, we have members of the band
who play an instrument and members of the band
who play an instrument and are their section's lead
player or chair. A readable way to show this self-join
is:
Tell Me / Show Me
Hierarchical Queries
Closely related to self-joins are hierarchical queries. On the
previous pages you saw how you can use self-joins to see
who is someone's direct manager. With hierarchical queries
we can also see who that manager works for and so on.
We can basically build an Organization Chart showing the
structure of a company or a department. Imagine a family
tree with the eldest members of the family found close to the
base or trunk of the tree and the youngest members
representing branches of the tree. Branches can have their
own branches, and so on.
Tell Me / Show Me
Using Hierarchical Queries
Using hierarchical queries, you can retrieve data based on a
natural hierarchical relationship between rows in a table.
A relational database does not store records in a
hierarchical way. However, where a hierarchical relationship
exists between the rows of a single table, a process called
tree walking enables the hierarchy to be constructed.
A hierarchical query is a method of reporting the branches of
a tree in a specific order.
Tell Me / Show Me
EMPLOYEE_ FIRST_ LAST_ EMAIL PHONE_ HIRE_ JOB_ID SALARY COMM_ MGR_ DEPT_
ID NAME NAME NUMBER DATE PCT ID ID
100 Steven King SKING 515.123.4567 17-JUN-87 AD_PRES 24000 (null) (null) 90
101 Neena Kochhar NKOCHHAR 515.123.4568 21-SEP-89 AD_VP 17000 (null) 100 90
102 Lex De Haan LDEHAAN 515.123.4569 13-JAN-93 AD_VP 17000 (null) 100 90
103 Alexander Hunold AHUNOLD 590.423.4567 03-JAN-90 IT_PROG 9000 (null) 102 60
104 Bruce Ernst BERNST 590.423.4568 21-MAY-91 IT_PROG 6000 (null) 103 60
124 Kevin Mourgos KMOURGOS 650.123.5234 16-NOV-99 ST_MAN 5800 (null) 100 50
141 Trenna Rajs TRAJS 650.121.8009 17-OCT-95 ST_CLERK 3500 (null) 124 50
Tell Me / Show Me
Hierarchical Queries Illustrated
King
Hunold Rajs
Ernst
Tell Me / Show Me
Hierarchical Queries Keywords
Hierarchical queries have their own new keywords: START
WITH, CONNECT BY PRIOR and LEVEL.
Tell Me / Show Me
Hierarchical Queries Keyword Example
SELECT employee_id, last_name, job_id, manager_id
FROM employees
START WITH employee_id = 100
CONNECT BY PRIOR employee_id = manager_id
Tell Me / Show Me
Hierarchical Queries Another Example
SELECT last_name||' reports to '||
PRIOR last_name "Walk Top Down"
FROM employees
START WITH last_name = 'King'
CONNECT BY PRIOR employee_id = manager_id
Walk Top Down
King reports to
Kochhar reports to King
Whalen reports to Kochhar
Higgins reports to Kochhar
Gietz reports to Higgins
De Haan reports to King
Hunold reports to De Haan
Ernst reports to Hunold
Tell Me / Show Me
Hierarchical Queries Level Example
SELECT LEVEL, last_name||' reports to '||
PRIOR last_name "Walk Top Down"
FROM employees
START WITH last_name = 'King'
CONNECT BY PRIOR employee_id = manager_id
Tell Me / Show Me
Hierarchical Query Report
If you wanted to create a report displaying company management
levels, beginning with the highest level and indenting each of the
following levels, then this would be easy to do using the LEVEL
pseudo column and the LPAD function to indent employees based
on their level.
Tell Me / Show Me
Hierarchical Query Output Levels
SELECT LPAD(last_name, LENGTH(last_name)+(LEVEL*2)-2,'_')
AS ORG_CHART
FROM employees
START WITH last_name='King'
CONNECT BY PRIOR employee_id=manager_id
As you can see in the result on the left, each row is indented by two
underscores per level.
Tell Me / Show Me
Hierarchical Queries Pruning
Pruning branches from the tree can be done using either the
WHERE clause or the CONNECT BY PRIOR clause.
If the WHERE clause is used then only the row named in the
statement is excluded and if the CONNECT BY PRIOR is used
that entire branch is excluded.
Tell Me / Show Me
Hierarchical Queries
So if you wanted to just not include a single row in your result you
would use the WHERE clause to exclude that row, but in the result
it would then look like Gietz worked directly for Kochhar, which he
does not.
Gietz
Tell Me / Show Me
Hierarchical Queries (continued)
If, however, you wanted to exclude one row and all the rows below
that one you should make the exclusion part of the CONNECT BY
statement. In this example by excluding Higgins, we are also
excluding Gietz in the result.
Gietz
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
Self join
Hierarchical Queries
Level
Start with
Connect By prior
Summary
Objectives Summarized
In this lesson you have learned to:
• Construct and execute a SELECT statement to join a
table to itself using a self-join
• Interpret the concept of a hierarchical query
• Create a tree-structured report
• Format hierarchical data
• Exclude branches from the tree structure
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Try It / Solve It
Classroom Activity
Try every example listed below. Confirm that your results match the expected result. If you
need help, ask another student or the teacher. All example code is based on the Oracle
database.
Cross Join
SELECT last_name, department_name
FROM employees CROSS JOIN departments;
Natural Join
SELECT employee_id, last_name, department_name
FROM employees NATURAL JOIN departments;
Joins by column names and data types that are identical in each
table. Both the employees and departments tables have the
columns department_id and manager_id. Therefore, the query will
return the rows where the values in both columns match.
Try It / Solve It
Classroom Activity (Continued)
Joins .. Using
SELECT employee_id, last_name, department_name
FROM employees JOIN departments
USING (department_id);
Joins by column names and data types that are identical in each table
but USING statement limits to one column.
Join .. On
SELECT e.employee_id, e.last_name, d.department_id, d.location_id
FROM employees e JOIN departments d
ON (e.department_id = d.department_id);
Try It / Solve It
Classroom Activity (Continued)
Join .. On
SELECT e.employee_id, e.last_name, e.salary, j.grade_level
FROM employees e JOIN job_grades j
ON (e.salary BETWEEN j.lowest_sal AND j.highest_sal);
This displays the grade level for each employee based on salary.
Try It / Solve It
Classroom Activity (Continued)
Outer Joins
Right Outer Join
SELECT e.employee_id, e.last_name,
e.department_id, d.department_name
FROM employees e RIGHT OUTER JOIN departments d
ON (e.department_id = d.department_id);
Retrieves all data in the left table (EMPLOYEES). Returns employees who
are assigned to a department as well as employees who are not assigned
to a department.
Try It / Solve It
Classroom Activity (Continued)
Retrieves all data in the left table and all data in the right
table. This includes departments with employees and
departments without employees. It also includes
employees who are assigned to a department as well as
employees who are not assigned to a department.
Summary
Objectives Summarized
In this lesson you have learned to:
• Determine the correct join syntax to use given a
scenario requiring the join of data from two or
more tables
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
What if you needed to know this now so that you could meet a
3:00 p.m. deadline? You might have a problem!
In this lesson, you are going to learn about the power of group
functions in SQL.
sdp_s05_l04_a01
Tell Me / Show Me
GROUP Functions
In SQL, the following group functions can operate on a whole
table or on a specific grouping of rows. Each function returns
one result.
AVG
COUNT
MIN
MAX
SUM
VARIANCE
STDDEV
Tell Me / Show Me
GROUP Functions List
SELECT MAX(salary)
FROM employees;
MIN: Used with columns that
store any data type to return the DEPT_ID SALARY
minimum value. 90 24000
90 17000
MAX: Used with columns that 90 17000
store any data type to return the 60 9000
maximum value. 60 6000
60 4200
50 5800
SUM: Used with columns that 50 3500 MAX (SALARY)
store numeric data to find the 50 3100 24000
total or sum of values. 50 2600
50 2500
AVG: Used with columns that … …
store numeric data to compute 60 11000
the average. 60 8600
7000
10 4400
Tell Me / Show Me
GROUP Functions List (continued) SELECT STDDEV(salary)
FROM employees;
COUNT: Returns the number of rows.
DEPT_ID SALARY
VARIANCE: Used with columns that 90 24000
store numeric data to calculate the 90 17000
spread of data around the mean. For 90 17000
example, if the average grade for the 60 9000
class on the last test was 82% and the 60 6000
student's scores ranged from 40% to
60 4200
100%, the variance of scores would be
greater than if the student's scores 50 5800
50 3500 STDDEV (SALARY)
ranged from 78% to 88%.
50 3100 5659.633
50 2600
STDDEV: Similar to variance, standard 50 2500
deviation measures the spread of data.
… …
For two sets of data with approximately
the same mean, the greater the spread, 60 11000
the greater the standard deviation. 60 8600
7000
10 4400
Tell Me / Show Me
GROUP Functions SELECT Clause DEPT_ID SALARY
90 24000 The maximum
Group functions are written in the 90 17000 salary in the
SELECT clause: 90 17000 EMPLOYEES
60 9000 table
60 6000
SELECT column,
60 4200
group_function(column), ..
50 5800
FROM table 50 3500 MAX (SALARY)
WHERE condition 50 3100 24000
GROUP BY column; 50 2600
50 2500
60 10500
60 11000
60 8600
7000
10 4400
Tell Me / Show Me
GROUP Function Cautions
There are a few important things you should know
about group functions:
SELECT type_code
FROM d_songs
WHERE SUM (duration) = 100;
Tell Me / Show Me
GROUP Function and NULL
Group functions ignore NULL values. In the example below,
the (null) values were not used to find the average overtime
rate.
FIRST_NAME OVERTIME_RATE
Sue 10.25
Bob (null)
Monique (null)
sdp_s05_l04_a02
SELECT AVG(overtime_rate)
FROM f_staffs;
AVG(OVERTIME_RATE)
10.25
Tell Me / Show Me
More Than One Group Function
You can have more than one group function in the
SELECT clause, on the same or different columns.
Tell Me / Show Me
MIN and MAX Group Functions SELECT MIN(last_name)
FROM employees;
MIN(LAST_NAME)
Two group functions, MIN and MAX,
Abel
can be used with any data type.
Tell Me / Show Me
Rules for Group Functions
• Group functions ignore null values.
• Group functions cannot be used in the WHERE clause.
• MIN and MAX can be used with any data type; SUM,
AVG, STDDEV and VARIANCE can be used only with
numeric data types.
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
Aggregate
AVG
COUNT
Group functions
MAX
MIN
STDDEV
SUM
VARIANCE
Summary
Objectives Summarized
In this lesson you have learned to:
• Define and give an example of the seven group
functions: SUM, AVG, COUNT, MIN, MAX, STDDEV,
VARIANCE
• Construct and execute a SQL query using group
functions
• Construct and execute group functions that operate
only with numeric data types
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
COUNT
SELECT COUNT (YEAR) COUNT (YEAR)
COUNT(expression) returns FROM d_cds
the number of non-null WHERE year < 2001; 5
values in the expression
column
COUNT(DISTINCT
expression) returns the
number of unique non-null SELECT COUNT COUNT (DISTINCT
(DISTINCT year) YEAR)
values in the expression
FROM d_cds 4
column. WHERE year < 2001;
Tell Me / Show Me
COUNT and NULL Values
Why are null values returned in the SELECT comments
query shown? There are six comments FROM d_play_list_items;
listed, but the count function returned
only five. Why? COMMENTS
Play late
(null)
Because COUNT ignores the null value Play early
in the column. Play after cake cutting
Play first
Play for the father
SELECT COUNT(comments)
FROM d_play_list_items;
COUNT (COMMENTS)
Tell Me / Show Me
COUNT All Rows
COUNT(*) returns the number of rows SELECT COUNT (*)
in a table that satisfy the criteria of the FROM d_cds
SELECT statement. WHERE year < 2001;
Tell Me / Show Me
DISTINCT
The keyword DISTINCT is used to SELECT year as ‘CD Year’
FROM d_cds;
return only nonduplicate values or
combinations of nonduplicate CD Year
2000
2004
Tell Me / Show Me
DISTINCT Example SELECT DISTINCT year AS ‘CD Year’
FROM d_cds;
To eliminate duplicate rows, use
the DISTINCT keyword as shown CD Years
here. 1997
1998
1999
Using the DISTINCT keyword
returned all the CD years exactly 2000
2002
2004
Tell Me / Show Me
YEAR TITLE
DISTINCT Nonduplicate
1997 The Celebrants Live in Concert
The keyword DISTINCT, when 1998 Graduation Songbook
used in a query selecting more 1999 Songs from My Childhood
than one column, will return 2000 Cape Diem
nonduplicate combinations of the 2000 Party Music for All Occasions
2001 Here Comes the Bride
columns. Examine the two results
2002 Back to the Shire
sets shown here. Can you tell 2004 Whirled Peas
which query used the DISTINCT
keyword? SELECT DISTINCT year, title
FROM d_cds;
YEAR TITLE
In this case, it's hard to tell, isn't it?
1997 The Celebrants Live in Concert
The results set on the top was 2000 Party Music for All Occasions
returned using the DISTINCT 2002 Back to the Shire
keyword. In both examples, there 1999 Songs from My Childhood
are no duplicate combinations of 2000 Carpe Diem
year and title even though there 2001 Here Comes the Bride
are duplicate years. 1998 Graduation Songbook
2004 Whirled Peas
Tell Me / Show Me
SELECT SUM(salary)
Using DISTINCT FROM employees
WHERE department_id = 90;
The keyword DISTINCT
SALARY
can be used with all group
24000 SUM(SALARY)
functions. Using DISTINCT
17000 58000
makes the function
17000
consider only nonduplicate
values.
SELECT SUM(DISTINCT salary)
FROM employees
Why do the two statements WHERE department_id = 90;
on the right produce SALARY
different results? 24000 SUM(DISTINCT
SALARY)
17000 41000
17000
Tell Me / Show Me
DISTINCT and COUNT SELECT COUNT (DISTINCT job_id)
FROM employees;
When using DISTINCT with a
group function such as COUNT, COUNT (DISTINCT job_id)
the result set will return the 12
number of nonduplicate column
values.
Tell Me / Show Me
NVL
Sometimes it is desirable to include null values
in group functions. For example, knowing the
average number of customer orders served
each day could be used to judge how much
food to order each month. Some days the
restaurant is closed and there are no
customers, but the owner has found that
computing the average including every day is a
better indicator than just counting the days with
customers. The SELECT statement to include
null values could be written starting with:
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
COUNT (expression)
COUNT (DISTINCT expression)
DISTINCT
Summary
Objectives Summarized
In this lesson you have learned to:
• Construct and execute a SQL query using the COUNT
group function
• Use DISTINCT and the NVL function with group
functions
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
But what if you wanted to know the average height of the students based
on their year in school? Right now, you would have to write a number of
different SQL statements to accomplish this:
And so on! To simplify problems like this with just one statement you use
the GROUP BY and HAVING clauses.
Tell Me / Show Me
GROUP BY Use
SELECT department_id, AVG(salary)
You use the GROUP BY FROM employees
clause to divide the rows in a GROUP BY department_id;
Tell Me / Show Me
GROUP BY Example
What if we wanted to find the maximum salary of
employees in each department? We use a GROUP BY
clause stating which column to use to group the rows.
Tell Me / Show Me
GROUP BY in SELECT
Usually we want to include the GROUP BY column in the
SELECT list.
DEPT_ID SALARY
90 24000
90 17000 DEPT_ID MAX (SALARY)
90 17000 90 24000
60 9000 60 9000
60 6000 … …
60 4200
… …
Tell Me / Show Me
GROUP BY Clause
Group functions require that any column listed
in the SELECT clause that is not part of a
group function must be listed in a GROUP BY
clause.
Tell Me / Show Me
COUNT
This example shows how many students wear shirts of each color.
Remember that group functions ignore null values, so if any student does
not have a first name, he or she will not be included in the COUNT. Of
course this is unlikely, but when constructing SQL statements we have to
think about all the possibilities.
Tell Me / Show Me
WHERE Clause
We can also use a WHERE clause to exclude rows before the
remaining rows are formed into groups.
Tell Me / Show Me
More GROUP BY Examples
Tell Me / Show Me
GROUP BY Guidelines
Important guidelines to remember when using a GROUP
BY clause are:
Tell Me / Show Me
SELECT department_id, job_id, count(*)
Groups Within GROUPS
FROM employees
Sometimes you need to divide WHERE department_id > 40
groups into smaller groups. For GROUP BY department_id, job_id;
60 IT_PROG 3
This example shows how many
employees are doing each job 80 SA_MAN 1
… … …
Tell Me / Show Me
Nesting Group Functions
Group functions can be nested to a depth of
two when GROUP BY is used.
SELECT max(avg(salary))
FROM employees
GROUP by department_id;
Tell Me / Show Me
HAVING
Suppose we want to find the maximum salary in each
department, but only for those departments which have
more than one employee? What is wrong with this
example?
Tell Me / Show Me
HAVING (continued)
In the same way you used the WHERE clause to restrict the rows that you
selected, you can use the HAVING clause to restrict groups.
In a query using a GROUP BY and HAVING clause, the rows are first
grouped, group functions are applied, and then only those groups matching
the HAVING clause are displayed.
The WHERE clause is used to restrict rows; the HAVING clause is used to
restrict groups returned from a GROUP BY clause.
Tell Me / Show Me
HAVING (continued)
Although the HAVING clause can precede the GROUP BY
clause in a SELECT statement, it is recommended that you
place each clause in the order shown. The ORDER BY clause
(if used) is always last!
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
GROUP BY
HAVING
Summary
Objectives Summarized
In this lesson you have learned to:
• Construct and execute a SQL query using GROUP BY
• Construct and execute a SQL query using GROUP BY
… HAVING
• Construct and execute a GROUP BY on more than one
column
• Nest group functions
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Purpose
What if you wanted to know the average height of all students? You
could write a query that looks like this:
SELECT AVG(height) FROM students;
But what if you wanted to know the average height of the students
based on their year in school? Right now, you would have to write a
number of different SQL statements to accomplish this:
SELECT AVG(height) FROM students WHERE year_in_school = 10;
SELECT AVG(height) FROM students WHERE year_in_school = 11;
SELECT AVG(height) FROM students WHERE year_in_school = 12;
And so on! To simplify problems like this with just one statement you
use the GROUP BY and HAVING clauses.
Purpose (continued)
What if, once you have selected your groups and computed your
aggregates across these groups, you also wanted subtotals per
group and a grand total of all the rows selected.
Using these extensions requires less work on your part and they
are all highly efficient to use, from the point of view of the
database.
Tell Me / Show Me
ROLLUP
In GROUP BY queries you are quite often required to produce
subtotals and totals, and the ROLLUP operation can do that for
you.
Tell Me / Show Me
ROLLUP Result Table
In the result table below, the rows highlighted in red are generated
by the ROLLUP operation:
Tell Me / Show Me
ROLLUP Result Formula
The number of columns or expressions that appear in the ROLLUP
clause determine the number of groupings. The formula is (number
of columns) + 1 where the number of columns listed is the number
of columns listed in the ROLLUP clause. In the example query
below there are 2 columns listed in the ROLLUP clause and
therefore you will see 3 values generated automatically.
Tell Me / Show Me
Without ROLLUP
If you use GROUP BY without ROLLUP for the same query what
would the results look like?
Tell Me / Show Me
CUBE
CUBE is an extension to the GROUP BY clause like ROLLUP. It
produces cross-tabulation reports.
Tell Me / Show Me
CUBE (Continued)
CUBE is typically most suitable in queries that use columns from
multiple tables rather than columns representing different rows of a
single table.
Imagine for example a user querying the Sales table for a company
like AMAZON.COM. For instance, a commonly requested cross-
tabulation might need subtotals for all the combinations of Month,
Region and Product.
Tell Me / Show Me
CUBE (Continued)
In the following statement the rows in red are generated by the
CUBE operation:
Tell Me / Show Me
GROUPING SETS
GROUPING SETS is another extension to the GROUP BY clause, like
ROLLUP and CUBE. It is used to specify multiple groupings of data. It is
like giving you the possibility to have multiple GROUP BY clauses in the
same SELECT statement, which is not allowed in the syntax.
The point of GROUPING SETS is that if you want to see data from the
EMPLOYEES table grouped by (department_id, job_id , manager_id), but
also by (department_id, manager_id) and also by (job_id, manager_id)
then you would normally have to write 3 different select statements with the
only difference being the GROUP BY clauses. For the database this
means retrieving the same data in this case 3 times, and that can be quite
a big overhead. Imagine if your company had 3,000,000 employees. Then
you are asking the database to retrieve 9 million rows instead of just 3
million rows – quite a big difference.
Tell Me / Show Me
GROUPING SETS (continued)
In the following statement the rows highlighted in color are generated by the
GROUPING SETS operation:
Tell Me / Show Me
GROUPING Functions
When you create reports with subtotals,
using either ROLLUP or CUBE you quite
often also have to be able to tell which rows
in the output are actual rows returned from
the database and which rows are computed
subtotal rows, resulting from the ROLLUP or
CUBE operations.
Tell Me / Show Me
GROUPING Functions (continued)
You may also need to find the exact level
of aggregation for a given subtotal. You
often need to use subtotals in calculations
such as percent-of-totals, so you need an
easy way to determine which rows are the
subtotals.
Tell Me / Show Me
GROUPING Functions (continued)
The GROUPING function handles these problems.
Using a single column from the query as its argument,
GROUPING returns 1 when it encounters a NULL value
created by a ROLLUP or CUBE operation. That is, if the
NULL indicates the row is a subtotal, GROUPING
returns a 1. Any other type of value, including a stored
NULL, returns a 0. So the GROUPING function will
return a 1 for an aggregated (computed) row and a 0 for
a not aggregated (returned) row.
The syntax for the GROUPING is simply GROUPING
(column_name). It is used only in the SELECT clause
and it takes only a single column expression as
argument.
Tell Me / Show Me
GROUPING Functions (continued)
SELECT department_id, job_id, SUM(salary),
GROUPING(department_id) Dept_sub_total,
DECODE(GROUPING(department_id),
1,'Dept Aggregate row', department_id) AS DT,
GROUPING(job_id) job_sub_total,
DECODE(GROUPING(job_id),
1,'JobID Aggregate row',job_id) AS JI
FROM employees
WHERE department_id < 50
GROUP BY CUBE (department_id, job_id)
Tell Me / Show Me
GROUPING Functions (continued)
The output below is from the query on the previous slide, and it shows the
use of the GROUPING function along with a DECODE to translate the 0 and
1 returned by GROUPING into either a text string or the actual table data:
DECODE(GROUPING(job_id), 1,'JobID Aggregate row',job_id) AS JI
Tell Me / Show Me
GROUPING Functions (continued)
Quite often queries like these are used as a basis for reporting these numbers in
graphical reporting tools, and all sorts of charts are created from the data to
present the results in an easy to understand format to the end user. To save the
end-user query tools having to do the summaries and calculations, you get that
work done by the database, but if you total all the numbers below you would get
a very wrong result. The total sum(salary) for employees working in
department_id < 50 is only 23400, not 93600, which is the total of all the rows
returned by the query. So you need to be able to tell the real rows apart from the
aggregated rows, and the 0 and 1 makes that job really easy.
Tell Me / Show Me
GROUPING Functions (continued)
If the result of the query on the previous slide were to be imported into a
spreadsheet and graphed without any filters applied it would result in the
following graph, which is wrong, as it includes the same numbers multiple times.
Tell Me / Show Me
GROUPING Functions (continued)
Here is the same query displayed with filters applied to only include rows
with a 0 in the GROUPING(department_id) or GROUPING(job_id). In this
report no number is included more than once. With the 0 and 1 from the
GROUPING function present, it is very easy to filter out the subtotals.
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
ROLLUP
CUBE
GROUPING SETS
GROUPING FUNCTION
Summary
Objectives Summarized
In this lesson you have learned to:
• Use ROLLUP to produce subtotal values
• Use CUBE to produce cross-tabulation values
• Use GROUPING SETS to produce a single result set
• Use the GROUPING function to identify the extra row
values created by either a ROLLUP or CUBE operation
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
Setting the Stage
In order to explain the SET operators the
following two lists will be used throughout this
lesson:
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
Tell Me / Show Me
Rules to Remember
There are a few rules to remember when using SET operators:
• The number of columns and the data types of the columns
must be identical in all of the SELECT statements used in
the query.
• The names of the columns need not be identical.
• Column names in the output are taken from the column
names in the first SELECT statement. So any column
aliases should be entered in the first statement as you
would want to see them in the finished report.
Tell Me / Show Me
UNION
The UNION operator returns all rows from both tables, after
eliminating duplicates.
SELECT a_id A B
FROM a 1
4
6
2 7
UNION 3
5
8
SELECT b_id
FROM b;
Tell Me / Show Me
UNION ALL
The UNION ALL operator returns all rows from both tables,
without eliminating duplicates.
SELECT a_id
FROM a A 4 B
1 6
5
UNION ALL 2
4
7
3 8
SELECT b_id 5
FROM b;
Tell Me / Show Me
INTERSECT
The INTERSECT operator returns all rows common to both
tables.
SELECT a_id
FROM a A B
4
INTERSECT 5
SELECT b_id
FROM b;
Tell Me / Show Me
MINUS
The MINUS operator returns all rows found in one table
but not the other.
SELECT a_id
FROM a A B
1
MINUS 2
SELECT b_id 3
FROM b;
Tell Me / Show Me
Set Operator Examples
Sometimes if you are selecting rows from tables that do not have columns
in common, you may have to make up columns in order to match the
queries. The easiest way to do this is to include one or more NULL values
in the select list. Remember to give them suitable aliases and matching
datatypes.
For example:
Table A contains a location id and a department name.
Table B contains a location id and a warehouse name.
You can use the TO_CHAR(NULL) function to fill in the missing columns
as shown below.
Tell Me / Show Me
Set Operator Examples (continued)
The keyword NULL can be used to match columns in a SELECT
list. One NULL is included for each missing column. Furthermore,
NULL is formatted to match the datatype of the column it is
standing in for, so TO_CHAR, TO_DATE or TO_NUMBER
functions are often used to achieve identical SELECT lists.
Tell Me / Show Me
Set Operator Examples (continued)
The WAREHOUSES table description:
Tell Me / Show Me
Set Operator Examples (continued)
Select location_id, department_name "Department", TO_CHAR(NULL)
"Warehouse"
FROM Departments
UNION
SELECT location_id, TO_CHAR(NULL) "Department", warehouse_name
FROM warehouses;
Tell Me / Show Me
SET Operations ORDER BY
If you want to control the order of the returned rows when using SET operators
in your query, the ORDER BY statement must only be used once, in the last
SELECT statement in the query. Using the example on the previous slide, if you
need to sort the rows returned by employee_id, you would need to add an
ORDER BY.
Tell Me / Show Me
SET Operations ORDER BY (continued)
The same query ordered by employee_id gives the following result, and on
this output you can see the entire employment history of one individual
employee without scrolling up and down.
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
SET operators
UNION
UNION ALL
INTERSECT
MINUS
TO_CHAR(null) – matching the select list
Summary
Objectives Summarized
In this lesson you have learned to:
• Define and explain the purpose of Set Operators
• Use a set operator to combine multiple queries into a
single query
• Control the order of rows returned using set operators
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
\sdp_s06_l04_a01
Asking parents, or doing the math problem,
are examples of subqueries.
Tell Me / Show Me
Subquery Overview
Throughout this course, you have written queries to extract data
from a database. What if you wanted to write a query only to find
out you didn't have all the information you needed to construct it?
You can solve this problem by combining two queries, placing one
query inside the other query. The inner query is called the
"subquery." The subquery executes to find the information you
don’t know. The outer query uses that information to find out what
you need to know.
Being able to combine two queries into one can be very useful
when you need to select rows from a table with a condition that
depends on the data in the table itself.
Tell Me / Show Me
The subquery syntax is:
Subquery Example
A subquery is a SELECT SELECT select_list
FROM table
statement that is embedded in a WHERE expression operator
clause of another SELECT (SELECT select_list
FROM table);
statement. A subquery executes
once before the main query The
result of the subquery is used by The SELECT statement in parentheses
is the inner query or ‘subquery’.
the main or outer query. It executes first, before the outer query.
Tell Me / Show Me
Guidelines for using Subqueries
• The subquery is enclosed in parentheses.
• The subquery is placed on the right side of the
comparison condition.
• The outer and inner queries can get data from different
tables.
• Only one ORDER BY clause can be used for a SELECT
statement; and, if used, it must be the last clause in the
outer query. A subquery cannot have its own ORDER BY
clause.
• The only limit on the number of subqueries is the buffer
size the query uses.
Tell Me / Show Me
Two types of Subqueries
• Single-row subqueries that use single-row operators
(>, =, >=, < <>, <=) and return only one row from the
inner query.
• Multiple-row subqueries that use multiple-row
operators (IN, ANY, ALL) and return more than one row
from the inner query.
Tell Me / Show Me
Subquery Example SELECT staff_id, first_name, last_name, birth_date
FROM f_staffs
What if you wanted to WHERE birth_date >=
find out the names of (SELECT birth_date
the Global Fast Foods FROM f_staffs
WHERE last_name = ‘Tuttle’);
staff members that were
born after Monique
STAFF_ID FIRST_NAME LAST_NAME BIRTH_DATE
Tuttle? What is the first
1000 Roger Morgan 17-JUN-87
thing you need to
1189 Nancy Vickers 21-SEP-89
know? When was
1007 Monique Tuttle 13-JAN-87
Monique born? Once
1354 Alex Hunter 03-JAN-90
you know her birth date,
1423 Kathryn Bassman 08-AUG-91
then you can select
those staff members
whose birth dates are
after hers.
Tell Me / Show Me
Subquery and Null SELECT last_name
FROM employees
If a subquery returns a null value or no
WHERE department_id =
rows, the outer query takes the results of (SELECT department_id
the subquery (null) and uses this result FROM employees
in its WHERE clause. WHERE last_name = ‘Grant’);
No data found.
The outer query will then return no rows,
because comparing a value with null
always yields a null.
Tell Me / Show Me
Multiple-Column Subqueries SELECT employee_id,
manager_id,
Subqueries can use one or more department_id
columns. If they use more than FROM employees
WHERE (manager_id,department_id) IN
one column, they are called (SELECT manager_id,department_id
multiple-column subqueries. A FROM employees
multiple-column subquery can be WHERE employee_id IN (149,174))
either pair-wise comparisons or AND employee_id NOT IN (149,174)
non-pair-wise comparisons.
The example on the right shows a EMPLOYEE MANAGER_ID DEPARTMENT
multiple-column pair-wise _ID _ID
subquery with the subquery 176 149 80
highlighted in red and the result
in the table below.
The query lists the employees
whose manager and departments
are the same as the manager and
department of employees 149 or
174.
Tell Me / Show Me
Multiple-Column Subqueries SELECT employee_id,
manager_id,
(continued) department_id
A non-pair-wise multiple-column FROM employees
subquery also uses more than WHERE manager_id IN
one column in the subquery, but (SELECT manager_id
it compares them one at a time, FROM employees
WHERE employee_id IN
so the comparisons take place (174,199))
in different subqueries. You will AND department_id IN
need to write one subquery per (SELECT department_id
column you want to compare FROM employees
against when performing non- WHERE employee_id IN
pair-wise multiple column (174,199))
AND employee_id NOT IN(174,199);
subqueries. The example on the
right shows a multiple-column
EMPLOYEE_ID MANAGER_ID DEPARTMENT_ID
non-pair-wise subquery with the
subqueries highlighted in red. 176 149 80
This query is listing the
149 100 80
employees who have either a
manager_id or a department_id
in common with employees 174
or 199.
Copyright © 2011, Oracle. All rights reserved. 11
Fundamentals of Subqueries
Tell Me / Show Me
EXISTS & NOT EXISTS in Subqueries
EXISTS and its opposite, NOT EXISTS, are another two clauses that can
be used when testing for matches in subqueries. EXISTS test for a TRUE,
or a matching result in the subquery.
If you want to see how many employees are employees and not managers,
you could use NOT EXISTS:
Tell Me / Show Me
EXISTS & NOT EXISTS in Subqueries (continued)
If the same query is executed with a NOT IN instead of NOT EXISTS, the result
is very different. The result of this query suggests there are no employees who
are also not managers, so all employees are managers, which we already know
is not true. What is causing this result?
SELECT count(*)
FROM employees t1
WHERE t1.employee_id NOT IN (SELECT t2.manager_id
FROM employees t2 );
Tell Me / Show Me
EXISTS & NOT EXISTS in Subqueries (continued)
The cause of the strange result is due to the NULL value returned by the
subquery. One of the rows in the employees table does not have a
manager, and this makes the entire result wrong. Subqueries can return
three values: TRUE, FALSE and UNKNOWN. A NULL in the subquery
result set will return an UNKNOWN, which Oracle cannot evaluate, so it
doesn’t.
BEWARE of NULLS in
SELECT count(*)
subqueries when using NOT
FROM employees t1
WHERE t1.employee_id NOT IN (SELECT t2.manager_id IN. If you do not know if the
FROM employees t2 ); subquery will return null
values, always use NOT
EXISTS. It is safer.
Tell Me / Show Me
EXISTS & NOT EXISTS in Subqueries (continued)
The way EXISTS and NOT EXISTS are executed by Oracle is very different
from the way IN and NOT IN are executed.
When the database is executing an IN with a Subquery, it evaluates the
Subquery, typically Distincts that query and then joins the result to the outer
query to get the result.
When an EXISTS is executed it performs a Full Table Scan of the outer
table, and then Oracle loops through the Subquery result rows one by one to
see if the condition is true. It executes like this:
Tell Me / Show Me
EXISTS & NOT EXISTS in Subqueries (continued)
One final note about EXISTS and IN.
IN will generally execute faster, as it can use any existing indexes on the
outer table. EXISTS cannot use indexes on the outer table. The size of the
table is also an important factor and affects which of the expressions will run
faster.
A small outer table joined to a very big inner table can still execute very fast
using EXISTS, perhaps even faster than the same statement using IN.
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
Inner query
Multiple- row subquery
Outer subquery
Single row subquery
Subquery
Pair-wise multiple column subquery
Non-pair-wise multiple column subquery
EXIST and NOT EXIST
Summary
Objectives Summarized
In this lesson you have learned to:
• Define and explain the purpose of subqueries for
retrieving data
• Construct and execute a single-row subquery in the
WHERE clause
• Distinguish between single-row and multiple-row
subqueries
• Distinguish between pair-wise and non-pair-wise
subqueries
• Use the EXIST and NOT EXISTS operators in a
query
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
Facts about single-row subqueries
They:
Always:
Tell Me / Show Me
Additional Subquery Facts
• The outer and inner queries can get data from different
tables
• Only one ORDER BY clause can be used for a SELECT
statement, and if specified, it must be the last clause in the
main SELECT statement
• The only limit on the number of subqueries is the buffer size
that the query uses.
Tell Me / Show Me
DEPARTMENT_ID DEPARTMENT_NAME
Subqueries from Different 10 Administration
Tables 20 Marketing
50 Shipping
… …
The outer and inner queries
can get data from different
tables. SELECT last_name, job_id, department_id
FROM employees
Who works in the Marketing WHERE department_id =
department? (SELECT department_id
FROM departments
WHERE department_name = ‘Marketing’)
ORDER BY job_id;
Tell Me / Show Me
Subqueries from Different LAST_NAME JOB_ID DEPARTMENT_ID
Tables (continued) Lorentz IT_PROG 60
There can be more than one Mourgos ST_MAN 50
Rajs ST_CLERK 50
subquery returning Davies ST_CLERK 50
information to Matos ST_CLERK 50
the outer query. DEPARTMENT_ID LOCATION_ID
10 1700
SELECT last_name, job_id, 20 1800
salary, department_id
50 1500
FROM employees
WHERE job_id = 60 1400
(SELECT job_id
FROM employees LAST_NAME JOB_ID SALARY DEPARTMENT_ID
WHERE employee_id = 141) Rajs ST_CLERK 3500 50
Davies ST_CLERK 3100 50
AND department_id =
Matos ST_CLERK 2600 50
(SELECT department_id
FROM departments
WHERE location_id =1500);
Tell Me / Show Me
Group Functions in
SELECT last_name, first_name, salary
Subqueries FROM f_staffs
Group functions can be used in WHERE salary <
(SELECT MAX(salary)
subqueries. A group function FROM f_staffs);
without a GROUP BY clause in
the subquery returns a single F_STAFFS
60
Tell Me / Show Me
Subqueries in the HAVING Clause
Subqueries can also be placed in the
HAVING clause.
Tell Me / Show Me
SELECT department_id, MIN(salary)
Subquery Example FROM employees
Which departments have a lowest GROUP BY department_id
salary that is greater than the HAVING MIN(salary) >
lowest salary in department 50? (SELECT MIN(salary)
FROM employees
WHERE department_id = 50);
In this example, the subquery
selects and returns the lowest
salary in department 50. DEPARTMENT_ID MIN(SALARY)
10 4400
20 6000
The outer query uses this value to 60 4200
select the department ID and 80 8600
lowest salaries of all the 90 17000
departments whose lowest salary is 110 8300
greater than that number.
EMPLOYEES
The HAVING clause eliminated MIN(SALARY)
those departments whose MIN
salary was less than department 2500
50’s MIN salary.
Summary
Objectives Summarized
In this lesson you have learned to:
• Construct and execute a single-row subquery in the
WHERE clause or HAVING clause
• Construct and execute a SELECT statement using
more than one subquery
• Construct and execute a SELECT statement using a
group function in the subquery
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
Query Comparison SELECT first_name, last_name
Whose salary is equal to the salary FROM employees
of an employee in department 20 ? WHERE salary =
(SELECT salary
FROM employees
Why does this example not work? WHERE department_id = 20);
Because there is more than one
employee in department 20, so the LAST_NAME DEPT_ID SALARY
subquery returns multiple rows. Hartstein 20 13000
We call this a multiple-row Fay 20 6000
subquery.
Tell Me / Show Me
SELECT title, year
IN, ANY, and ALL FROM d_cds
WHERE year IN
Subqueries that return more than one (SELECT year
value are called multiple-row FROM d_cds);
D_CDS
subqueries.
TITLE YEAR
The Celebrants Live in 1997
Because we cannot use the single-row Concert
Songs from My Childhood 1999
comparison operators (=, < and so on),
Party Music for All Occasions 2000
we need different comparison
Carpe Diem 2000
operators for multiple-row subqueries.
Tell Me / Show Me
SELECT title, year
IN FROM d_cds
WHERE year IN
The IN operator is used when the outer (SELECT year
query WHERE clause is designed to select FROM d_cds
only those rows which are equal to one of WHERE cd_number < 93);
the list of values returned from the inner D_CDS
query.
TITLE YEAR
For example, we are interested in all the The Celebrants Live in 1997
Concert
CD titles that have the same year as the Party Music for All Occasions 2000
CD numbers less than 93. Since we are Back to the Shire 2002
not sure what the years are for the CDs
numbered below 93, the inner query will
YEAR
return a list of years.
1997
2000
The outer query will then return any title 2002
that has the same year as any year in the
inner query list.
Tell Me / Show Me
ANY D_CDS
Tell Me / Show Me
SELECT title, producer,year
ALL
FROM d_cds
The ALL operator is used when we WHERE year > ALL
want the outer-query WHERE clause (SELECT year
to select the rows which are equal to, FROM d_cds
less than or greater than all the WHERE producer = ‘The Music Man’);
values in the subquery result set.
D_CDS
D_CDS
The ALL operator compares a value
to every value returned by the inner YEAR
query. 2000
2001
Tell Me / Show Me
NULL VALUES SELECT last_name, employee_id
Suppose that one of the values returned by a FROM employees
multiple-row subquery is null, but other WHERE employee_id IN
values are not. (SELECT manager_id
FROM employees);
Tell Me / Show Me
NULL Values in Subqueries
SELECT emp.last_name
FROM employees emp
WHERE emp.employee_id NOT IN
(SELECT mgr.manager_id
FROM employees mgr
WHERE mgr.manager_id IS NOT
NULL);
Tell Me / Show Me
GROUP BY and HAVING
As you might suspect, the GROUP BY
clause, and the HAVING clause can also LAST_NAME DEPT_ID SALARY
be used with multiple-row subqueries. Whalen 10 4400
Hartstein 20 13000
Fay 20 6000
What if you wanted to find the
departments whose minimum salary is
less than the salary of any employee who
DEPARTMENT_ID MIN(SALARY)
works in department 10 or 20? 10 4400
20 6000
We need a multiple-row subquery which 50 2500
60 4200
returns the salaries of employees in
80 8600
departments 10 and 20. The outer query 110 8300
will use a group function (MIN) so we (null) 7000
need to GROUP the outer query BY
department_id.
Tell Me / Show Me
GROUP BY and HAVING (continued)
Here is the needed SQL statement: LAST_NAME DEPT_ID SALARY
Whalen 10 4400
Hartstein 20 13000
SELECT department_id, MIN(salary)
Fay 20 6000
FROM employees
GROUP BY department_id
HAVING MIN(salary) <ANY
DEPARTMENT_ID MIN(SALARY)
(SELECT salary
10 4400
FROM employees
20 6000
WHERE department_id IN (10,20)); 50 2500
60 4200
80 8600
110 8300
(null) 7000
Tell Me / Show Me
GROUP BY and HAVING (continued)
You can even have a GROUP BY DEPARTMENT_ID MIN(SALARY)
10 4400
clause in the subquery !
20 6000
Tell Me / Show Me
One Last Point About Subqueries SELECT first_name, last_name, job_id
Some subqueries may return a FROM employees
single row or multiple rows, WHERE job_id =
(SELECT job_id
depending on the data values in the FROM employees
rows. If there is even a possibility of WHERE last_name = ‘Ernst’);
multiple rows, make sure you write
a multiple-row subquery.
Tell Me / Show Me
One Last Point About SELECT first_name, last_name, job_id
Subqueries (continued) FROM employees
WHERE job_id IN
It would be better to write a (SELECT job_id
multiple-row subquery. FROM employees
WHERE last_name = ‘Ernst’);
Summary
Objectives Summarized
In this lesson you have learned to:
• Use the comparison operators IN, ANY and ALL correctly in
multiple-row subqueries
• Construct and execute a multiple-row subquery in the
WHERE clause or HAVING clause
• Describe what happens if a multiple-row subquery returns a
null value
• Understand when multiple-row subqueries should be used,
and when it is safe to use a single-row subquery.
• Create a query using the EXIST and NOT EXISTS
operators to test for returned rows from the subquery.
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
Correlated Subqueries
The Oracle server
performs a correlated GET
subquery when the candidate row from outer query
subquery references a
column from a table
EXECUTE
referred to in the parent inner query using candidate row value
statement.
A correlated subquery is
USE
evaluated once for each values from inner query to qualify or
row processed by the disqualify candidate row
parent statement.
The parent statement can
be a SELECT, UPDATE
or DELETE statement.
Copyright © 2011, Oracle. All rights reserved. 4
Correlated Subqueries
Tell Me / Show Me
Correlated Subquery Example SELECT o.first_name,
o.last_name,
Whose salary is higher than the average
o.salary
salary of their department?
FROM employees o
To answer that question we need to WHERE o.salary >
write a correlated subquery. Correlated (SELECT AVG(i.salary)
subqueries are used for row-by-row FROM employees i
processing. WHERE i.department_id =
Each subquery is executed once for o.department_id);
every row of the outer query.
FIRST_NAME LAST_NAME SALARY
With a normal subquery, the inner
Steven King 24000
SELECT query runs first and executes
Alexander Hunold 9000
once, returning values to be used by the
Kevin Mourgos 5800
main query. A correlated subquery,
however, executes once for each row Eleni Zlotkey 10500
considered by the outer query. In other Ellen Abel 11000
words, the inner query is driven by the Michael Hartstein 13000
outer query. The example correlated Shelley Higgins 12000
subquery is marked in red.
Copyright © 2011, Oracle. All rights reserved. 5
Correlated Subqueries
Tell Me / Show Me
WITH clause
If you have to write a very complex query with joins and
aggregations used many times, you can write the
different parts of the statement as query blocks and
then use those same query block in a SELECT
statement. Oracle allows you to write named
subqueries in one single statement, as long as you
start your statement with the keyword WITH.
• The WITH clause retrieves the results of one or
more query blocks and stores those results for the
user who runs the query.
• The WITH clause improves performance.
• The WITH clause makes the query easier to read.
Tell Me / Show Me
WITH clause (continued)
The syntax for the WITH clause is as follows:
Tell Me / Show Me
WITH clause (continued)
Write the query for the following requirement:
To solve this query you will need to first get the total
salaries per department, then the average salary
per department and then you can list just the ones
with total salary greater than the average of all
departments.
Tell Me / Show Me
WITH clause (continued)
Let’s examine an example of a WITH clause. Let’s start by creating
two subqueries, one called dept_costs and a second called avg_cost.
Avg_cost uses the result of dept_cost and once these two subqueries
have been run the actual query itself is executed.
The query itself selects from both dept_cost and avg_cost. By
creating the subqueries first, you do not need to create two temporary
tables to hold the results of the SUM of salary per department and the
AVG of department salaries.
Tell Me / Show Me
WITH clause (continued)
WITH
dept_costs AS (
SELECT d.department_name, SUM(e.salary) AS dept_total
FROM employees e JOIN departments d
ON e.department_id = d.department_id
GROUP BY d.department_name),
avg_cost AS (
SELECT SUM(dept_total)/COUNT(*) AS dept_avg
FROM dept_costs)
SELECT *
FROM dept_costs
WHERE dept_total >
(SELECT dept_avg
FROM avg_cost)
ORDER BY department_name;
Summary
Objectives
In this lesson you have learned:
• Identify when correlated subqueries are needed.
• Construct and execute correlated subqueries.
• Construct and execute named subqueries using the
WITH clause.
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
Copy Tables Before Inserting
You will be responsible for altering tables in your schema. You will
also be responsible for restoring them just as a real Database
Administrator would assume that responsibility.
• To keep your schema tables in their original state you will
make a copy of each table to complete the practice activities
in this and later lessons.
• If you inadvertently alter a copy table you can restore a
correct version of it from the original table.
• You should name each table copy_tablename.
• The table copies will not inherit the associated primary-to-
foreign-key integrity rules (relationship constraints) of the
original tables. The column data types, however, are inherited
in the copied tables.
Tell Me / Show Me
Syntax to Create a Copy of a Table
For example:
To verify and view the copy of the table, use the following
DESCRIBE and SELECT statements:
DESCRIBE copy_f_customers
Tell Me / Show Me
INSERT
The INSERT statement is used to add new rows to a table. The
statement requires three values:
• the name of the table
• the names of the columns in the table to populate
• corresponding values for the column
Tell Me / Show Me
INSERT (continued)
The syntax shown uses INSERT to add a new customer to a Global
Fast Foods table. This statement explicitly lists each column as it
appears in the table. The values for each column are listed in the
same order. Note that number values are not enclosed in single
quotation marks.
Tell Me / Show Me
INSERT (continued)
Another way to insert values in a table is to
implicitly add them by omitting the column
names.
Tell Me / Show Me
INSERT (continued)
The INSERT statement in this example was written without explicitly
naming the columns. For clarity, however, it is best to use the column
names in an INSERT clause.
Tell Me / Show Me
Check The Table First
Before inserting data into a table, you must check several
table details. The DESCRIBE tablename syntax will return
a table summary.
TRAINING Varchar2 50 …
… … … …
Tell Me / Show Me
Table Summary
As shown in the example, the table summary provides the
following information about the columns in the table:
• columns that can have a NULL value
• columns that cannot have duplicate values
• allowable data type
• amount of data that can be entered in a column
Primary Name Type Length Precision Scale Nullable De-fault Com-
Key ments
1 ID Number 5 0 …
FIRST_NAME Varchar2 25 …
LAST_NAME Varchar2 35 …
BIRTHDATE Date 7 …
SALARY Number 8 2 …
OVERTIME_RATE Number 5 2 …
TRAINING Varchar2 50 …
… … … …
Tell Me / Show Me
Table Summary (continued)
Notice the Length column for characters and dates, and the Precision
and Scale column for numbers. Precision is the total number of digits,
and the scale is the number of digits to the right of the decimal place.
TRAINING Varchar2 50 …
… … … …
Tell Me / Show Me
Inserting Rows With Null Values
The INSERT statement need not specify every column,
as long as all the not null columns are named in the
INSERT clause, a new row will be inserted.
Tell Me / Show Me
Inserting Rows With Null Values (continued)
If a column can hold null values, it can be omitted from the INSERT
clause. An implicit insert will automatically insert a null value in that
column. To explicitly add null values to a column, use the NULL
keyword in the VALUES list for those columns that can hold null
values.
To specify empty strings and/or missing dates, use empty single
quotation marks, with not even a blank between them (' ') for
missing data.
Tell Me / Show Me
Inserting Special Values
Special values such as SYSDATE and USER can be entered
in the VALUES list of an INSERT statement.
Tell Me / Show Me
Inserting Special Values (continued)
In addition, functions and calculated expressions can also
be used in the VALUES clause.
Tell Me / Show Me
Inserting Specific Date Values
The default format model for date is DD-MON-RR. With this
format, recall that the century defaults to the nearest century
(nearest to SYSDATE) with the default time of midnight
(00:00:00).
Tell Me / Show Me
Inserting Specific Date Values (continued)
Similarly, if we want to INSERT a row with a non-default
format for a date column, we must use the TO_DATE
function to convert the date value (a character string) to a
date.
Tell Me / Show Me
Inserting Specific Date Values (continued)
A second example of TO_DATE allows the insertion of a
specific time of day, avoiding the default time of midnight.
Tell Me / Show Me
Using A Subquery To Copy Rows
Each INSERT statement we have seen so far adds
only one row to the table. But suppose we want to
copy 100 rows from one table to another ?
Tell Me / Show Me
Using A Subquery To Copy Rows (continued)
In the example shown, a new table called SALES_REPS is being
populated with copies of some of the rows and columns from the
EMPLOYEES table.
The WHERE clause is selecting those employees that have job IDs
like '%REP%'.
The number of columns and their data types in the column list of the
INSERT clause must match the number of columns and their data
types in the subquery.
The subquery is not enclosed in parentheses as is done with
subqueries in a WHERE clause of a SELECT statement.
Tell Me / Show Me
Using A Subquery To Copy Rows (continued)
If we want to copy all the data – all rows and all columns – the
syntax is even simpler.
To select all rows from the EMPLOYEES table and insert them
into the SALES_REPS table, the statement would be written as
shown:
Again, this will work only if both tables have the same number of
columns, in the same order, with the same data types.
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
INSERT INTO
USER
Transaction
Explicit
Summary
Objectives Summarized
In this lesson you have learned to:
• Give examples of why it is important to be able to alter
the data in a database
• Construct and execute INSERT statements which
insert a single row using a VALUES clause
• Construct and execute INSERT statements that use
special values, null values, and date values
• Construct and execute INSERT statements that copy
rows from one table to another using a subquery
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
UPDATE
The UPDATE statement is used to modify existing rows in a
table. It requires four values:
Tell Me / Show Me
UPDATE (continued)
The example shown uses an UPDATE statement to change
the phone number of one customer in the Global Fast Foods
database. Note that the copy_f_customers table is used in this
transaction.
UPDATE copy_f_customers
SET phone_number='4475582344'
WHERE id=123;
Tell Me / Show Me
UPDATE (continued)
We can change several columns and/or several rows in one
UPDATE statement. This example changes both the phone
number and the city for two Global Fast Foods customers.
UPDATE copy_f_customers
SET phone_number='4475582344‘,
city = ‘Chicago’
WHERE id < 200;
Tell Me / Show Me
UPDATE (continued)
Which rows would be updated in the following transaction?
UPDATE copy_f_customers
SET phone_number='9876543210';
Tell Me / Show Me
Updating a Column with a value from a Subquery
We can use the result of a single-row subquery to provide the new value for
an updated column.
UPDATE copy_f_staffs
SET salary = (SELECT salary
FROM copy_f_staffs
WHERE id = 9)
WHERE id = 12;
This example changes the salary of one employee (id = 12) to the same
salary as another employee (id = 9). As usual, the subquery executes first
and retrieves the salary for employee id=12. This salary value is then used to
update the salary for employee id=9.
9 Bob Miller 10
12 Sue Doe 10
Tell Me / Show Me
Updating Two Columns with Two Subquery Statements
To update several columns in one UPDATE statement, it is possible to write
multiple single-row subqueries, one for each column.
In this example the UPDATE statement changes the salary and staff type of
one employee (id = 12) to the same values as another employee (id = 9).
UPDATE copy_f_staffs
SET salary = (SELECT salary
FROM copy_f_staffs
WHERE id = 9),
staff_type = (SELECT staff_type
FROM copy_f_staffs
WHERE id = 9)
WHERE id = 12;
Tell Me / Show Me
Updating Rows Based On Another Table
As you may have expected, the subquery can retrieve information from
one table which is then used to update another table.
In this example, a copy of the f_staffs table was created. Then data from
the original f_staffs table was retrieved, copied, and used to populate the
copy of the f_staffs table.
UPDATE copy_f_staffs
SET salary = (SELECT salary
FROM f_staffs
WHERE id = 9)
WHERE id = 9;
Tell Me / Show Me
Updating Rows Based On The Same Table
As you already know subqueries can be either stand alone or correlated.
In a correlated subquery you are updating a row in a table based on a
select from that same table.
UPDATE employees e
SET e.department_name = (SELECT d.department_name
FROM departments d
WHERE e.department_id =
d.department_id);
Tell Me / Show Me
DELETE
The DELETE statement is used to remove existing rows in
a table. The statement requires two values:
Tell Me / Show Me
DELETE (continued)
The example shown uses the Global Fast Foods database to delete
one row, the customer with ID number 123.
All rows in the table are deleted if you omit the WHERE clause.
Tell Me / Show Me
Subquery DELETE
Subqueries can also be used in DELETE statements.
Tell Me / Show Me
Correlated Subquery DELETE
The example below deletes rows of all employees who work for a
manager that manages more than 2 departments.
Tell Me / Show Me
Integrity Constraint Errors
Integrity constraints ensure that the data conforms to a needed set of
rules. The constraints are automatically checked whenever a DML
statement which could break the rules is executed. If the any rule would
be broken, the table is not updated and an error is returned.
UPDATE copy_f_staffs
SET first_name = (SELECT first_name
FROM copy_f_staffs
WHERE id = 123);
Tell Me / Show Me
Integrity Constraint Errors (continued)
When will primary key - foreign key constraints be checked?
Tell Me / Show Me
Integrity Constraint Errors (continued)
When modifying your copy tables (for example
copy_f_customers) you may see not null constraint errors, but
you will not see any primary key – foreign key constraint errors.
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
DELETE
Integrity constraint
UPDATE
Correlated subquery UPDATE
Correlated subquery DELETE
Summary
Objectives Summarized
In this lesson you have learned to:
• Construct and execute an UPDATE statement
• Construct and execute a DELETE statement
• Construct and execute a query that uses a
subquery to update and delete data from a table
• Construct and execute a query that uses a
correlated subquery to update and delete from a
table
• Explain how foreign-key and primary-key integrity
constraints affect UPDATE and DELETE
statements
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
In this lesson, you will learn a more efficient method to update and
insert data using a sequence of conditional INSERT and UPDATE
commands in a single atomic statement.
You will also learn how to retrieve data from one single subquery
and INSERT the rows returned into more than one target table.
Tell Me / Show Me
DEFAULT
A column in a table can be given a default value. This
option prevents null values from entering the columns if a
row is inserted without a specified value for the column.
The default value must match the data type of the column.
DEFAULT can be specified for a column when the table is
created or altered.
Tell Me / Show Me
DEFAULT Example
The example below shows a default value being specified
at the time the table is created:
Tell Me / Show Me
Explicit DEFAULT with INSERT
Explicit defaults can be used in INSERT and UPDATE
statements. The INSERT example using the
DEPARTMENTS table shows the explicit use of DEFAULT.
INSERT INTO departments
(department_id, department_name, manager_id)
VALUES
(300, 'Engineering', DEFAULT);
If a default value was set for the manager_id column, Oracle
sets the column to the default value. However, if no default
value was set when the column was created, Oracle inserts
a null value.
Tell Me / Show Me
Explicit DEFAULT with UPDATE
Explicit defaults can be used in INSERT and UPDATE
statements. The UPDATE example using the Oracle
DEPARTMENTS table shows explicit use of DEFAULT.
UPDATE departments
SET manager_id = DEFAULT
WHERE department_id = 10;
Tell Me / Show Me
MERGE
Using the MERGE statement accomplishes two tasks at the
same time. MERGE will INSERT and UPDATE
simultaneously. If a value is missing, a new one is inserted. If
a value exists, but needs to be changed, MERGE will update
it.
Tell Me / Show Me
MERGE Syntax
MERGE INTO destination-table USING source-table
ON matching-condition
WHEN MATCHED THEN UPDATE
SET ……
WHEN NOT MATCHED THEN INSERT
VALUES (……);
One row at a time is read from the source table, and its column
values are compared with rows in the destination table using
the matching condition. If a matching row exists in the
destination table, the source row is used to update column(s) in
the matching destination row.
If a matching row does not exist, values from the source row are
used to insert a new row into the destination table.
Tell Me / Show Me
MERGE Example
This example uses the EMPLOYEES table (alias e) as a data
source to insert and update rows in a copy of the table named
COPY_EMP (alias c).
Tell Me / Show Me
MERGE Example (continued) EMPLOYEES (source table)
MERGE INTO copy_emp c USING EMPLOYEE_ID LAST_NAME DEPARTMENT_ID
employees e
100 King 90
ON (c.employee_id = e.employee_id)
103 Hunold 60
WHEN MATCHED THEN UPDATE
SET 142 Davies 50
c.last_name = e.last_name,
c.department_id = e.department_id COPY_EMP before the MERGE is executed
WHEN NOT MATCHED THEN INSERT EMPLOYEE_ID LAST_NAME DEPARTMENT_ID
VALUES (e.employee_id, e.last_name,
e.department_id); 100 Smith 40
103 Chang 30
EMPLOYEES rows 100 and 103 have matching
rows in COPY_EMP, and so the matching
COPY_EMP rows were updated. COPY_EMP after the MERGE has executed
EMPLOYEE_ID LAST_NAME DEPARTMENT_ID
EMPLOYEE 142 had no matching row, and so 100 King 90
was inserted into COPY_EMP.
103 Hunold 60
142 Davies 50
Tell Me / Show Me
Multi-Table Inserts
Multi-table inserts are used when the same source data should be
inserted into more than one target table. This functionality is useful
when you are working in a data warehouse environment, where it is
common to regularly move data from the operational systems into a
data warehouse for analytical reporting and analysis. Creating and
managing data warehouses is one way of managing the sometimes
very high number of rows inserted into operational systems during a
normal working day.
Imagine, for instance, how many rows your mobile/cell telephone
provider must create daily. At least one for each time you use your
mobile/cell phone, and how many calls do you make and receive a
day?
Tell Me / Show Me
Multi-Table Inserts (continued)
Then add the number of SMS’s you send and receive.
Add to that your mobile surfing and downloads of ringtones,
wallpapers, games and other mobile applications.
Multiply that number by the number of customers.
That might give you an idea of the amount of data the
telecommunication companies have to manage.
These rows may have to be inserted into more than one table in the
data warehouse, so if we can just SELECT them once and then
replicate them, that will improve the performance.
Tell Me / Show Me
Multi-Table Inserts (continued)
Multi-table inserts can be unconditional or conditional. In an
unconditional multi-table insert Oracle will insert all rows returned
by the subquery into all table insert clauses found in the statement.
Tell Me / Show Me
Multi-Table Inserts (continued)
FIRST
If you specify FIRST, then the database evaluates each WHEN
clause in the order in which it appears in the statement. For the
first WHEN clause that evaluates to true, the database executes
the corresponding INTO clause and skips subsequent WHEN
clauses for the given row.
ELSE clause
For a given row, if no WHEN clause evaluates to true, then:
If you have specified an ELSE clause, then the database
executes the INTO clause list associated with the ELSE clause.
If you did not specify an else clause, then the database takes no
action for that row.
Tell Me / Show Me
Multi-Table Inserts Syntax
Multi-table insert statement syntax is as follows:
INSERT ALL
INTO all_calls VALUES (caller_id, call_timestamp, call_duration,
call_format)
INTO police_record_calls VALUES (caller_id, call_timestamp,
recipient_caller)
SELECT caller_id, call_timestamp, call_duration, call_format , recipient_caller)
FROM calls
WHERE TRUNC(call_timestamp ) = TRUNC(SYSDATE )
Tell Me / Show Me
Multi-Table Inserts Conditional
INSERT ALL
WHEN call_ format IN (‘tlk’,’txt’,’pic’) THEN
INTO all_calls VALUES (caller_id, call_timestamp, call_duration,
call_format)
WHEN call_ format IN (‘tlk’,’txt’) THEN
INTO police_record_calls VALUES (caller_id, call_timestamp,
recipient_caller)
WHEN call_duration < 50 AND call_type = ‘tlk’ THEN
INTO short_calls VALUES (caller_id, call_timestamp, call_duration)
WHEN call_duration > = 50 AND call_type = ‘tlk’ THEN
INTO long_calls VALUES (caller_id, call_timestamp, call_duration)
SELECT caller_id, call_timestamp, call_duration, call_format , recipient_caller)
FROM calls
WHERE TRUNC(call_timestamp ) = TRUNC(SYSDATE )
Summary
Objectives Summarized
In this lesson you have learned to:
• Understand when to specify a DEFAULT value
• Construct and execute a MERGE statement
• Construct and execute DML statements using
subqueries
• Construct and execute multi-table inserts
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
Database Schema Objects
An Oracle Database can contain many different types of objects. This
section introduces the most commonly used objects, and also describes
how the Oracle Server uses the information stored in the Data Dictionary
when it is performing work as a result of the SQL statements you issue.
Some of these object types can exist independently and others can not.
Tell Me / Show Me
Database Schema Objects (continued)
Some of the object types take up space in the database, known as
Storage, and others do not. Database objects taking up Storage are
known as Segments. Tables and Indexes are examples of
Segments, as the rows stored in the tables and the column values
take up physical space on disk in the database.
Views, Constraints, Sequences, and Synonyms are just objects, the
only space they take up in the database, is the definition of those
objects, none of them have any actual data rows associated with
them.
The database stores the definitions of all database objects in the
Data Dictionary, and these definitions are accessible to all users of
the database as well as the database itself.
Tell Me / Show Me
Database Schema Objects (continued)
Have you ever wondered, how Oracle knows which columns to return from
a Query? For example, if you specify SELECT * FROM d_cds instead of
SELECT cd_number, title FROM d_cds how does Oracle know which
columns to return?
The database looks up the definition of the table used in the query,
translates the ‘*’ into the full list of columns and returns the result to you.
The database uses the Data Dictionary for all statements you issue, even if
you list the columns instead of using ‘*’. It checks that the tables you are
referencing in your statement exist in the database, it checks that the
column names are correct, it checks if you have the correct privileges to
perform the action you are requesting, and finally it uses the Data
Dictionary to decide on what is called the Execution Plan – how it will
actually perform the statement.
Tell Me / Show Me
Database Schema Objects (continued)
The Data Dictionary itself can be queried by all database users. In
Application Express it can be accessed both via SQL statements in the SQL
Workshop> SQL Commands interface and also from the SQL Workshop>
Object Browser interface.
In the SQL Commands window you have to know the names of the views you
are querying and in the Object Browser interface you simply click on the
listed objects to see the details of them. So if you wanted to see the details of
the D_CDS table you could simply click in it in the table listing:
Tell Me / Show Me
Database Schema Objects (continued)
In this example, using the Object Browser, you can see the details
of the D_CDS table, as well as all the options available to you to
view the data, see the indexes, constraints and grants on the table.
Tell Me / Show Me
Database Schema Objects (continued)
In this example, using the SQL Commands window, you must ask for a
DESCription of the table. All the extra options offered by Object Browser
are not available in this interface.
Tell Me / Show Me
Table Creation
All data in a relational database is stored in tables. When creating a
new table, use the following rules for table names and column
names:
Tell Me / Show Me
Naming Conventions
It is best to use descriptive names for tables and other database
objects. If a table will store information about students, name it
STUDENTS, not PEOPLE or CHILDREN.
Tell Me / Show Me
CREATE TABLE
To create a new table, you must have the CREATE TABLE
privilege and a storage area for it. The database administrator
uses data control language (DCL) statements to grant this
privilege to users and assign a storage area.
Tell Me / Show Me
CREATE TABLE Syntax
To create a new table consider CREATE TABLE table
(column datatype [DEFAULT expression],
the following syntax details: (column datatype [DEFAULT expression],
(……[ ] );
Tell Me / Show Me
Creating A Table Using A Subquery
CREATE TABLE tablename
A second method for creating a table is to [(column, column, …)]
apply the AS subquery clause, which both AS subquery;
creates the table and inserts rows
returned from the subquery. Two examples:
Tell Me / Show Me
Creating A Table Using A Subquery (continued)
When a copy of a table is made using a subquery, the following
rules are important:
Tell Me / Show Me
External Tables
Oracle also supports another table Oracle Database
type: External table.
Tell Me / Show Me
External Tables (continued) Oracle Database
Typically an external table is used to store
data migrated from older versions of the
databases used by a company.
When a company is implementing a new
application and database, they typically
need to import most of the data from the
old systems to the new system for normal
Read
read and write access, but there may be
access
some data that is not used frequently and
only
therefore would only need to be accessed
for read access. This kind of data could be
held in an external table.
Flat file: Flat file:
One of the many benefits for Oracle is that
External External
data held in external tables only has to be
table 1 table 2
backed up once, and then never again
unless the contents of the file change.
Backed up once at operating
system level
Copyright © 2011, Oracle. All rights reserved. 17
Creating Tables
Tell Me / Show Me
External Tables (continued)
The syntax to create an external table is very similar to that of
creating a standard table, except that it has extra syntax at the
end. Please note the new syntax, not used in standard SQL
statements for table creation.
Tell Me / Show Me
External Tables Syntax Example
Tell Me / Show Me
Data Dictionary
Two kinds of tables exists in an Oracle Database: User tables and Data
Dictionary tables. You can issue SQL statements to access both kind of
tables, and you can select, insert, update and delete data in the user tables
and you can select data in the Data Dictionary tables.
Oracle Database
User tables Data Dictionary
created by tables:
you
DICTIONARY,
containing
your data: USER_OBJECTS,
D_CDS, USER_TABLES,
D_SONGS, USER_SEGMENTS
D_EVENTS USER_INDEXES
etc. etc.
Tell Me / Show Me
Data Dictionary (continued)
The Data Dictionary tables are all owned by a special Oracle user called
SYS and only SELECT statements should be used when working with any
of these tables. To make these tables safe from accidental user access,
they all have views created which is how the Data Dictionary is accessed by
database users. If any Oracle user attempts to do inserts, updates or
deletes against any of the Data Dictionary tables, then this operation would
be disallowed, as it might compromise the integrity of the entire database.
Oracle Database
Tell Me / Show Me
Data Dictionary (continued)
When you are using the Data Dictionary views in the SQL Commands
interface, you need to know the names of the Dictionary views you are
working with. In Oracle, this is quite simple: prefix the object type you are
looking for with a USER_xxx or an ALL_xxx, where xxx is the object type.
So if you want to investigate indexes, then simply select from
USER_INDEXES, if you want information about sequences, then the
table is USER_SEQUENCES and so on.
Two very important views to remember are DICTIONARY (DICT) and
DICT_COLUMNS.
Tell Me / Show Me
Data Dictionary (continued)
Dictionary (DICT) has a listing of all the dictionary views in the database.
DICT_COLUMNS lists all of the columns of all the tables in the Data Dictionary.
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
CREATE TABLE
Data dictionary
Table
Schema
DEFAULT
Summary
Objectives Summarized
In this lesson you have learned to:
• Categorize the main database objects
• Review a table structure
• Describe how schema objects are used
• List and provide an example of each of the
number, character, and date data types
• Create a table using the appropriate data type for
each column
• Explain the use of external tables
• Use the Data Dictionary to obtain the names and
other attributes of database objects
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
Data Type Overview
Each value manipulated by Oracle has a data type. A value's
data type associates a fixed set of properties with the value.
These properties cause the database to treat values of one data
type differently from values of another.
Different data types offer several advantages:
Tell Me / Show Me
Common Data Types
The most commonly used column data types are:
• For character values: CHAR (fixed size, maximum 2000
characters); VARCHAR2 (variable size, maximum 4000
characters); CLOB (variable size, maximum 128 terabytes)
• For number values: NUMBER (variable size, maximum
precision 38 digits)
• For date and time values: DATE, TIMESTAMP ….,
INTERVAL
• For binary values (eg multimedia: JPG, WAV, MP3 and so
on): RAW (variable size, maximum 2000 bytes);
BLOB(variable size, maximum 128 terabytes).
Tell Me / Show Me
Common Data Types (continued)
The most commonly used column data types are:
• For character values, it is usually better to use VARCHAR2 or
CLOB than CHAR, because it saves space.
• For example, an employee‟s last name is „Chang‟. In a
VARCHAR2(30) column, only the 5 significant characters are
stored: C h a n g. But in a CHAR(30) column, 25 trailing
spaces would be stored as well, to make a fixed size of 30
characters.
• Number values can be negative as well as positive. For
example, NUMBER(6,2) can store any value from +9999.99
down to –9999.99.
Tell Me / Show Me
DATE-TIME Data Types
The DATE data type stores a value of centuries down to
whole seconds, but cannot store fractions of a second.
‟21-AUG-2003 17:25:30‟ is a valid value, but ‟21-AUG-
2003 17:25:30.255‟ is not.
Tell Me / Show Me
TIMESTAMP …. With [LOCAL] Time Zone
Think about the time value „17:30‟. Of course it means “half
past five in the afternoon”. But where in the world? Is it half
past five New York City time or Beijing time or Istanbul time
or …. ?
Tell Me / Show Me
TIMESTAMP …. With [LOCAL] Time Zone (continued)
TIMESTAMP WITH TIME ZONE stores a time zone value
as a displacement from Universal Coordinated Time or UCT
(previously known as Greenwich Mean Time or GMT).
Tell Me / Show Me
TIMESTAMP With … TIME ZONE Example
Tell Me / Show Me
TIMESTAMP With… TIME ZONE Example (continued)
FIRST_COLUMN SECOND_COLUMN
--------------------------------------------- --------------------------------
15-NOV-2007 08:00:00 AM -05:00 15-NOV-2007 08:00:00
Istanbul time is 7 hours ahead of EST; when it‟s 8am in New York
City, it‟s 3pm in Istanbul.
Tell Me / Show Me
INTERVAL Data Types
These store the elapsed time, or interval of time, between two
date-time values.
Tell Me / Show Me
INTERVAL YEAR … TO MONTH
CREATE TABLE time_example2
The data type syntax is: (loan_duration INTERVAL YEAR(3) TO MONTH);
Tell Me / Show Me
INTERVAL DAY … TO SECOND
Use this when you need a more CREATE TABLE time_example3
(day_duration INTERVAL DAY(3) TO SECOND);
precise difference between two
date-time values. INSERT INTO time_example3 (day_duration)
The data type syntax is: VALUES (INTERVAL „25‟ DAY(2));
INTERVAL DAY [(day_precision)]
TO SECOND SELECT sysdate + day_duration “25 Days”
FROM time_example3;
[(fractional_seconds_precision)]
-- assume today‟s date is 06-Oct-2007
day_precision is the maximum
number of digits in the DAY date-
time field. The default is 2. 25 Days
31-OCT-07
fractional_seconds_precision is the
number of digits in the fractional
part of the SECOND date-time field.
The default is 6.
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
CLOB
BLOB
TIMESTAMP
TIMESTAMP WITH TIMEZONE
TIMESTAMP WITH LOCAL TIMEZONE
INTERVAL DAY TO SECOND
INTERVAL DAY TO MONTH
Summary
Objectives Summarized
In this lesson you have learned to:
• Create a table using TIMESTAMP and
TIMESTAMP WITH TIME ZONE column data
types
• Create a table using INTERVAL YEAR TO
MONTH and INTERVAL DAY TO SECOND
column data types
• Give examples of organizations and personal
situations where it is important to know to which
time zone a date-time value refers
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
ALTER TABLE
ALTER TABLE statements are used to:
• Add a new column
• Modify an existing column
• Define a DEFAULT value for a column sdp_s09_l01_a01
• Drop a column.
Tell Me / Show Me
ALTER TABLE: Adding A Column
To add a new column, use the SQL syntax shown.
For example:
Tell Me / Show Me
ALTER TABLE: Modifying A Column
Modifying a column can include changes to a column's data
type, size, and DEFAULT value. Rules and restrictions when
modifying a column are:
Tell Me / Show Me
ALTER TABLE: Modifying A Column (continued)
• You can change the data type only if the column contains
null values.
• You can convert a CHAR column to VARCHAR2 or
convert a VARCHAR2 column to CHAR only if the column
contains null values or if you do not change the size.
• A change to the DEFAULT value of a column affects only
later insertions to the table.
Tell Me / Show Me
ALTER TABLE: Modifying A Column Example
Example: a table has been created with two columns:
Tell Me / Show Me
ALTER TABLE: Dropping A Column
When dropping a column the following rules apply:
• A column to be dropped may or may not
contain data. sdp_s09_l01_a02
• Only one column can be dropped at a time.
• You can't drop all of the columns in a table; at
least one column must remain.
• Once a column is dropped, the data values in
it cannot be recovered.
SQL syntax:
ALTER TABLE tablename DROP COLUMN
column name;
For example:
ALTER TABLE copy_f_staffs DROP COLUMN
manager_target;
Tell Me / Show Me
SET UNUSED Columns
Dropping a column from a large table can take a long time. A
quicker alternative is to mark the column as unusable. The
column values remain in the database but cannot be accessed
in any way, so the effect is the same as dropping the column.
In fact, you could add a new column to the database with the
same name as the unused column. The unused columns are
there, but invisible!
Syntax:
ALTER TABLE tablename SET UNUSED (column name);
Tell Me / Show Me
SET UNUSED Columns Example
Example:
ALTER TABLE copy_f_staffs
SET UNUSED (manager_budget);
Example:
ALTER TABLE copy_f_staffs DROP UNUSED COLUMNS;
Tell Me / Show Me
ALTER TABLE Summarized
This chart summarizes the uses of the ALTER TABLE command.
Syntax Outcomes Concerns
ALTER TABLE tablename ADD (column Adds a new column to a table You cannot specify where the column is
name datatype [DEFAULT expression], to appear in the table. It becomes the
column name datatype [DEFAULT last column.
expression], …
ALTER TABLE tablename MODIFY Used to change a column‟s A change to the default value of a column
(column name datatype [DEFAULT datatype, size, and default value affects only subsequent insertions to the
expression], column name datatype, … table.
ALTER TABLE tablename DROP Used to drop a column from a The table must have at least one column
COLUMN column name; table remaining in it after it is altered. Once
dropped, the column cannot be
recovered.
ALTER TABLE tablename SET Used to mark one or more Does not restore disk space. Columns
UNUSED (column name); columns so they can be dropped are treated as if they were dropped.
later
ALTER TABLE tablename DROP Removes from the table all Once set unused, there is no access to
UNUSED COLUMNS columns currently marked as the columns; no data displayed using
unused DESCRIBE. Permanent removal; no
rollback.
Tell Me / Show Me
DROP TABLE
The DROP TABLE statement removes the definition of an
Oracle table. The database loses all the data in the table
and all the indexes associated with it. When a DROP
TABLE statement is issued:
Tell Me / Show Me
DROP TABLE (continued)
Only the creator of the table or a user with DROP ANY
TABLE privilege (usually only the DBA) can remove a table.
Tell Me / Show Me
FLASHBACK TABLE
If you drop a table by mistake there is a way of bringing that table
and its data back.
Each database user has their own recyclebin into which dropped
objects are now moved, and they can be recovered from here with
the FLASHBACK TABLE command.
Tell Me / Show Me
FLASHBACK TABLE (continued)
For example, if you drop the EMPLOYEES table in error, you can
restore it by simply issuing the command:
As the owner of a table you can issue the flashback command, and if
the table that you are restoring had any indexes, then these are also
restored.
It is possible to see what objects you have that you can restore, by
querying the data dictionary view USER_RECYCLEBIN.
Tell Me / Show Me
FLASHBACK TABLE (continued)
The USER_RECYCLEBIN view can be queried like all other data
dictionary views:
Any indexes that were dropped along with the original table, will
also have been restored.
Copyright © 2011, Oracle. All rights reserved. 18
Modifying a Table
Tell Me / Show Me
RENAME
To change the name of a table, use the RENAME
statement. This can be done only by the owner of
the object or by the DBA.
Example:
Tell Me / Show Me
TRUNCATE
Truncating a table removes all rows from a table and releases the
storage space used by that table. When using the TRUNCATE
TABLE statement:
The DELETE statement can also remove rows from a table, but it
does not release storage space. TRUNCATE is faster than DELETE
because it does not generate rollback information.
Tell Me / Show Me
COMMENT ON TABLE
You can add a comment of up to 2,000 characters about a column,
table, or view by using the COMMENT statement. The comment is
stored in the data dictionary and can be viewed in one of the
following data dictionary views in the COMMENTS column:
Comments on columns:
• ALL_COL_COMMENTS
• USER_COL_COMMENTS
Comments on tables:
• ALL_TAB_COMMENTS
• USER_TAB_COMMENTS
Tell Me / Show Me
COMMENT ON TABLE Examples
Syntax:
COMMENT ON TABLE tablename | COLUMN table.column
IS 'place your comment here';
Example:
COMMENT ON TABLE employees
IS 'Western Region only';
Tell Me / Show Me
COMMENT ON TABLE Examples (continued)
TABLE_NAME COMMENTS
-------------------- ------------------------------
EMPLOYEES Western Region only
Tell Me / Show Me
Flashback Query
You may discover that somehow data in a table has been
inappropriately changed. Luckily, Oracle has a facility that allows you
to view row data at specific points in time, so you can compare
different versions of a row over time.
You can use the FLASHBACK QUERY facility to examine what the
rows looked like BEFORE those changes were applied.
Tell Me / Show Me
Flashback Query (continued)
When Oracle changes data, it always keeps a copy of what
the amended data looked like before any changes were
made. So it keeps a copy of the old column value for a
column update, it keeps the entire row for a delete and it
keeps nothing for an insert statement.
Tell Me / Show Me
Flashback Query (continued)
You can look at older versions of data by using the
VERSIONS clause in a SELECT statement. For example:
SELECT employee_id,
first_name ||‟ „|| last_name AS “NAME”,
versions_operation AS “OPERATION”,
versions_starttime AS "START_DATE",
versions_endtime AS "END_DATE",
salary
FROM employees
VERSIONS BETWEEN SCN MINVALUE AND MAXVALUE
WHERE employee_id = 1;
Tell Me / Show Me
Flashback Query (continued)
The best way to demonstrate FLASHBACK QUERY is with an example.
The contents of the employees table is as follows for employee_id 1.
Tell Me / Show Me
Flashback Query (continued)
SELECT employee_id,
first_name ||‟ „||last_name AS “NAME”,
versions_operation AS “OPERATION”,
versions_starttime AS "START_DATE",
versions_endtime AS "END_DATE",
salary
FROM employees
VERSIONS BETWEEN SCN MINVALUE AND
MAXVALUE
WHERE employee_id = 1;
Tell Me / Show Me
Flashback Query (continued)
Then you can update the row:
SELECT employee_id,
first_name ||‟ „||last_name AS “NAME”,
versions_operation AS “OPERATION”,
versions_starttime AS "START_DATE",
versions_endtime AS "END_DATE",
salary
FROM employees
VERSIONS BETWEEN SCN MINVALUE AND
MAXVALUE
WHERE employee_id = 1;
Tell Me / Show Me
Flashback Query (continued)
SELECT employee_id,
first_name ||‟ „||last_name AS “NAME”,
versions_operation AS “OPERATION”,
versions_starttime AS "START_DATE",
versions_endtime AS "END_DATE",
salary
FROM employees
VERSIONS BETWEEN SCN MINVALUE AND
MAXVALUE
WHERE employee_id = 1;
EMPLOYEE_ID NAME OPERATION START_DATE END_DATE SALARY
Tell Me / Show Me
Flashback Query (continued)
Summary
Objectives Summarized
In this lesson you have learned to:
• Explain why it is important to be able to modify a table
• Explain and provide an example for each of the DDL
statements ALTER, DROP, RENAME, and TRUNCATE
and the effect each has on tables and columns
• Construct a query and execute the ALTER TABLE
commands ADD, MODIFY, and DROP
• Explain and perform FLASHBACK QUERY on a table
• Explain and perform FLASHBACK table operations
Summary
Objectives Summarized (continued)
In this lesson you have learned to:
• Track the changes to data over a period of time
• Explain the rationale for using TRUNCATE versus
DELETE for tables
• Add a comment to a table using the COMMENT ON
TABLE command
• Name the changes that can and cannot be made to
modify a column
• Explain when and why the SET UNUSED statement is
advantageous
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
Write the Query Query Result:
Problem:
Produce a listing of all tables
whose first two characters in
the name of the table is D_.
The tables must be owned by
the current Oracle User.
Tables Used:
User_tables
Tell Me / Show Me
Write the Query Query Result:
Problem:
Create a listing of the first
character of the first name, a
space and the last name of
all employees.
Tables Used:
Employees
Tell Me / Show Me
Write the Query
Tell Me / Show Me
Write the Query
Tables Used:
Employees
Tell Me / Show Me
Write the Query
Tell Me / Show Me
Write the Query
Tables Used:
Employees, Jobs
Tell Me / Show Me
Write the Query
Tables Used:
Employees, Jobs
Copyright © 2011, Oracle. All rights reserved. 10
Ensuring Quality Query Results
Tell Me / Show Me
Write the Query
Tables Used:
Employees, Departments
Tell Me / Show Me
Write the Query
Tables Used:
Employees, Departments
Tell Me / Show Me
Write the Query
Tables Used:
Employees
Tell Me / Show Me
Fix the Query
Tell Me / Show Me
Write the Query
Tell Me / Show Me
Write the Query
Problem:
Query Result:
Create a listing of employee
first and last names, and
the first occurrence of:
commission_pct,
manager_id or -1. So if an
employee gets commission,
display the commission_pct
column, if no commission
then display his manager_id
and if he has neither
commission nor manager
then the number -1. Tables
Used:
Employees
Copyright © 2011, Oracle. All rights reserved. 16
Ensuring Quality Query Results
Tell Me / Show Me
Fix the Query
Tell Me / Show Me
Write the Query
Tables Used:
Employees, Departments
Tell Me / Show Me
Write the Query
Tell Me / Show Me
Write the Query
Tables Used:
Employees
Tell Me / Show Me
Write the Query
Tables Used:
Employees, Departments
Tell Me / Show Me
Write the Query
Tables Used:
Employees, Departments,
Employees
Tell Me / Show Me
Write the Query
Tables Used:
Employees
Tell Me / Show Me
Write the Query
Tables Used:
Employees, Departments
Tell Me / Show Me
Write the Query
Tables Used:
Employees, Departments
Copyright © 2011, Oracle. All rights reserved. 25
Ensuring Quality Query Results
Tell Me / Show Me
Write the Query
Problem:
Query
Create a listing of
Result:
department names, job_ids,
the monthly salary cost for
the departments and also
the sum of salaries per
department, per job_id and
a grand total sum of
salaries at the bottom of the
listing.
(Hint: Cube)
Tables Used:
Employees, Departments
Copyright © 2011, Oracle. All rights reserved. 26
Ensuring Quality Query Results
Tell Me / Show Me
Write the Query Query Result:
Problem:
Expand the previous listing
to also show if the
department_id or job_id was
used to create the subtotals
shown in the output.
(Hint: Cube, Grouping)
Tables Used:
Employees, Departments
Tell Me / Show Me
Write the Query
Tables Used:
Employees, Departments,
Locations
Copyright © 2011, Oracle. All rights reserved. 28
Ensuring Quality Query Results
Problem:
Create a report that lists
employee names as shown
and department ids. In the
same report, list the
department ids and
department names and
finally the cities. The rows
should not be joined, just all
listed in the same report.
(Hint: Union)
Tables Used:
Employees, Departments,
Locations
Copyright © 2011, Oracle. All rights reserved. 29
Ensuring Quality Query Results
Tell Me / Show Me
Write the Query
Tables Used:
f_regular_menus,
f_promotional_menus
Tell Me / Show Me
Write the Query
Tables Used:
Departments, Employees
Summary
Objectives Summarized
In this lesson you have learned to:
• Create a query to produce specified data
• Modify a query to produce specified data
Summary
Practice Guide
There is no lesson practice.
A database is only as reliable as the data that is in it. Constraints are used
to prevent invalid data entry into tables. Would it make sense to have
negative salary values or six students with the same student ID or two
tables that no longer reference each other? Without rules, how could you
trust the integrity of the database? In the next three lessons, you will study
how to create the constraints that enforce the "rules." You will also learn
how to manage them and view constraints definitions in the data dictionary.
Tell Me / Show Me
Constraints In General
So, what exactly is a constraint? Think of constraints as database
rules. All constraint definitions are stored in the data dictionary.
Constraints prevent the deletion of a table if there are
dependencies from other tables. Constraints enforce rules on the
data whenever a row is inserted, updated, or deleted from a table.
Constraints are important and naming them is also important.
Although you could name a constraint "bubbles" or "squeak,"
you'd soon find it difficult to distinguish one constraint from
another and would end up redoing a lot of work.
Tell Me / Show Me
Creating Constraints
Recall the SQL syntax for creating a table. In the
CREATE TABLE statement shown below, each column
and its data type is defined. You use the CREATE TABLE
statement to establish constraints for each column in the
table.
Tell Me / Show Me
Constraints at the Column Level
A column-level constraint references a single column. To establish a column-
level constraint the constraint must be defined in the CREATE TABLE
statement as part of the column definition. Examine the following SQL
statement that establishes a column-level constraint.
Tell Me / Show Me
Naming Constraints
Every constraint in the database has a name. When a constraint is
created, it can be given a name, such as clients_client_num_pk, or given
no name, in which case the system gives the constraint a name, such as
SYS_C00585417.
Tell Me / Show Me
Naming Constraints at the Column Level
It is best to name constraints yourself because system-generated names
are not easy to recognize. Look at this table definition:
Tell Me / Show Me
Constraint Naming Example
This example shows both a user-named constraint and a system-named
constraint:
Tell Me / Show Me
Constraints at the Table Level
Table-level constraints are listed separately from the
column definitions in the CREATE TABLE statement.
Table-level constraint definitions are listed after all the
table columns have been defined. In the example shown, sdp_s10_l01_a01
the unique constraint is listed last in the CREATE TABLE
statement.
Tell Me / Show Me
Basic Rules For Constraints
• Constraints that refer to more than one column (a composite
key) must be defined at the table level
• The NOT NULL constraint can be specified only at the
column level, not the table level
• UNIQUE, PRIMARY KEY, FOREIGN KEY and CHECK
constraints can be defined at either the column or table level
• If the word CONSTRAINT is used in a CREATE TABLE
statement, you must give the constraint a name
Tell Me / Show Me
Examine the Violations
Tell Me / Show Me
Five Types Of Constraint
There can be five types of constraint within an Oracle
database. Each type enforces a different kind of rule.
In the rest of this lesson you will learn about NOT NULL
and UNIQUE constraints. The next lesson will teach you
about the other three types.
Tell Me / Show Me
NOT NULL Constraint
A column defined with a NOT NULL constraint requires that for every row
entered into the table, there must be a value for that column. For
example, if the email column in an employees table was defined as NOT
NULL, every employee entered into the table MUST have a value in the
email column.
When defining NOT NULL columns, it is customary to use the suffix _nn
in the constraint name. For example, the constraint name for the NOT
NULL email column in the employees table could be emp_email_nn.
Tell Me / Show Me
UNIQUE Constraint
A UNIQUE constraint requires that every value in a column or set
of columns (a composite key) be unique; that is, no two rows of a
table can have duplicate values. For example, it may be
important for a business to ensure that no two people have the
same email address. The email column could be defined using a
UNIQUE constraint. The column or set of columns that is defined
as UNIQUE is called a unique key. If the combination of two
columns must not be the same for any entry, the constraint is
said to be a composite unique key. Stating that all combinations
of email and last name must be UNIQUE is an example of a
composite unique key. The word "key" refers to the columns, not
constraint names.
Tell Me / Show Me
CLIENT_ FIRST LAST PHONE EMAIL
Unique Constraint NUMBER _NAM _NAM
E E
Example
5922 Hiram Peters 371583224 hpeters@yahoo.com
An example of UNIQUE: 9
5857 Serena Jones 703533590 serena.jones@jones.co
0 m
If the email column in the 6133 Lauren Vigil 407222009 lbv@lbv.net
0
table is defined with a
UNIQUE constraint, no
other client entry can have INSERT INTO copy_d_clients (client_number, first_name,
Last_name, phone, email)
an identical email. What if VALUES (7234, „Lonny‟, „Vigil‟, 4072220091, „lbv@lbv.net‟);
two clients live in the same
ORA-00001: unique constraint
household and share an (USWA_SKHS_SQL01_T01.CLIENT_EMAIL_UK) violated
email address?
Tell Me / Show Me
Defining UNIQUE Constraints
When defining UNIQUE constraints, it is customary to use the
suffix _uk in the constraint name. For example, the constraint
name for the UNIQUE email column in the employees table
could be emp_email_uk.
Tell Me / Show Me
CLIENT_ FIRST_ LAST_ PHONE EMAIL
Composite Unique Key NUMBER NAME NAME
UNIQUE constraints allow the input 5922 Hiram Peters 3715832249 hpeters@yahoo.com
of nulls unless the column also has
a NOT NULL constraint defined. A 5857 Serena Jones 7035335900 serena.jones@jones.com
null in a column (or in all columns
of a composite unique key) always 6133 Lauren Vigil 4072220090 lbv@lbv.net
satisfies a UNIQUE constraint
because nulls are not considered 7234 Lonny Vigil 4072220091 lbv@lbv.net
equal to anything.
Tell Me / Show Me
Constraints Created at Table Creation
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
Constraint
Column level constraint
NOT NULL constraints
UNIQUE constraints
REFERENCES
Table level constraint
UNIQUE KEY
FOREIGN KEY
PRIMARY KEY
CHECK constraint
Summary
Objectives Summarized
In this lesson you have learned to:
• Define the term "constraint" as it relates to data
integrity
• State when it is possible to define a constraint at the
column level, and when it is possible at the table level
• State why it is important to give meaningful names to
constraints
• State which data integrity rules are enforced by NOT
NULL and UNIQUE constraints
• Write a CREATE TABLE statement which includes
NOT NULL and UNIQUE constraints at the table and
column levels
• Explain how constraints are created at the time of table
creation
Copyright © 2011, Oracle. All rights reserved. 21
Defining NOT NULL and UNIQUE Constraints
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
PRIMARY KEY Constraints
A PRIMARY KEY constraint is a column or set
of columns that uniquely identifies each row in
a table. No primary-key value can appear in
more than one row in the table. To satisfy a
PRIMARY KEY constraint, both of the
following conditions must be true:
Tell Me / Show Me
PRIMARY KEY Constraints (continued)
PRIMARY KEY constraints can be defined at the column or
the table level. However, if a composite PRIMARY KEY is
created, it must be defined at the table level.
Tell Me / Show Me
PRIMARY KEY Constraints (continued)
In a CREATE TABLE statement, the column-level PRIMARY KEY
constraint syntax is stated:
Note that the column-level simply refers to the area in the CREATE
TABLE statement where the columns are defined. The table level
refers to the last lines in the statement below where the individual
columns are defined.
Tell Me / Show Me
PRIMARY KEY Constraints (continued)
To define a composite PRIMARY KEY, you must define the
constraint at the table level rather than the column level. An example
of a composite unique-key constraint name is:
Tell Me / Show Me
FOREIGN KEY (REFERENTIAL INTEGRITY)
Constraints
Tell Me / Show Me
Stating a Foreign Key
To state a FOREIGN KEY constraints use statements such as:
Tell Me / Show Me
Viewing a Foreign Key
The table containing the foreign key is called the "child" table
and the table containing the referenced key is called the
"parent" table. In the tables shown, D_CLIENTS primary-key
client_number also appears in D_EVENTS as a foreign-key
column.
D_CLIENTS - Parents
CLIENT_ FIRST_NAME LAST_NAME PHONE EMAIL
NUMBER
5922 Hiram Peters 3715832249 hpeters@yahoo.com
5857 Serena Jones 7035335900 serena.jones@jones.com
6133 Lauren Vigil 4072220090 lbv@lbv.net
D_EVENTS - Child
ID NAME EVENT_ DESCRIPTION COST VENUE_ID PACKAGE_CODE THEME_CODE CLIENT_
DATE NUMBER
100 Peters 14-MAY-04 Party for 200, red, 8000 100 112 200 5922
Graduation white, blue motif
105 Vigil Wedding 28-APR-04 Black tie at Four 10000 220 200 200 6133
Seasons Hotel
Tell Me / Show Me
Referential-integrity Constraint
To satisfy a referential-integrity constraint, a foreign-key value
must match an existing value in the parent table or be NULL. In
the example, note that a primary-key value can exist without a
corresponding foreign-key value; however, a foreign-key must
have a corresponding primary key.
D_CLIENTS - Parents
CLIENT_ FIRST_NAME LAST_NAME PHONE EMAIL
NUMBER
5922 Hiram Peters 3715832249 hpeters@yahoo.com
5857 Serena Jones 7035335900 serena.jones@jones.com
6133 Lauren Vigil 4072220090 lbv@lbv.net
D_EVENTS - Child
ID NAME EVENT_ DESCRIPTION COST VENUE_ID PACKAGE_CODE THEME_CODE CLIENT_
DATE NUMBER
100 Peters 14-MAY-04 Party for 200, red, 8000 100 112 200 5922
Graduation white, blue motif
105 Vigil Wedding 28-APR-04 Black tie at Four 10000 220 200 200 6133
Seasons Hotel
Tell Me / Show Me
Referential-Integrity Constraint Rule
The rule is: before you define a referential-integrity constraint in
the child table, the referenced UNIQUE or PRIMARY KEY
constraint on the parent table must already be defined. In other
words, you must first have a parent primary key defined before
you can create a foreign key in a child table.
D_CLIENTS - Parents
CLIENT_ FIRST_NAME LAST_NAME PHONE EMAIL
NUMBER
5922 Hiram Peters 3715832249 hpeters@yahoo.com
5857 Serena Jones 7035335900 serena.jones@jones.com
6133 Lauren Vigil 4072220090 lbv@lbv.net
D_EVENTS - Child
ID NAME EVENT_ DESCRIPTION COST VENUE_ID PACKAGE_CODE THEME_CODE CLIENT_
DATE NUMBER
100 Peters 14-MAY-04 Party for 200, red, 8000 100 112 200 5922
Graduation white, blue motif
105 Vigil Wedding 28-APR-04 Black tie at Four 10000 220 200 200 6133
Seasons Hotel
Tell Me / Show Me
FOREIGN KEY Constraint
To define a FOREIGN KEY constraint, it is good practice to use
the suffix _fk in the constraint name.
For example, the constraint name for the FOREIGN KEY column
song_id in the DJ on Demand table named d_track_listings could
be named d_track_list_ song_id_fk.
Tell Me / Show Me
FOREIGN KEY Constraint Syntax
The syntax for defining a FOREIGN KEY constraint requires a
reference to the table and column in the parent table. A
FOREIGN KEY constraint in a CREATE TABLE statement
can be defined as follows.
Column-level syntax:
song_id NUMBER(5) CONSTRAINT d_track_list_ song_id_fk
REFERENCES d_songs(id)
Table-level syntax:
CONSTRAINT d_track_list_ song_id_fk FOREIGN KEY
(song_id)
REFERENCES d_songs(id)
Tell Me / Show Me
ON DELETE CASCADE - Maintaining Referential Integrity
Using the ON DELETE CASCADE option when defining a foreign key enables the
dependent rows in the child table to be deleted when a row in the parent table is
deleted. If the foreign key does not have an ON DELETE CASCADE option,
referenced rows in the parent table cannot be deleted. In other words, the child table
FOREIGN KEY constraint includes the ON DELETE CASCADE permission allowing its
parent to delete rows that it refers to.
D_CLIENTS - Parents
CLIENT_ FIRST_NAME LAST_NAME PHONE EMAIL
NUMBER
5922 Hiram Peters 3715832249 hpeters@yahoo.com
5857 Serena Jones 7035335900 serena.jones@jones.com
6133 Lauren Vigil 4072220090 lbv@lbv.net
D_EVENTS - Child
ID NAME EVENT_ DESCRIPTION COST VENUE_ID PACKAGE_CODE THEME_CODE CLIENT_
DATE NUMBER
100 Peters 14-MAY-04 Party for 200, red, 8000 100 112 200 5922
Graduation white, blue motif
105 Vigil Wedding 28-APR-04 Black tie at Four 10000 220 200 200 6133
Seasons Hotel
Tell Me / Show Me
ON DELETE CASCADE
If the song_id column in D_TRACK_LISTINGS was created with
the ON DELETE CASCADE option specified, the DELETE
statement issued on the D_SONGS table will execute. If the ON
DELETE CASCADE option was not specified when the song_id
column in D_TRACK_LISTINGS was created, the attempt to delete
song_id = 47 will fail.
D_TRACK_LISTINGS
Tell Me / Show Me
Column-level ON DELETE CASCADE Syntax
song_id NUMBER(5) CONSTRAINT d_track_list_ song_id_fk
REFERENCES d_songs(id) ON DELETE CASCADE
D_TRACK_LISTINGS
Tell Me / Show Me
ON DELETE SET NULL
Rather than having the rows in the child table deleted when
using an ON DELETE CASCADE option, the child rows can
be filled with null values using the ON DELETE SET NULL
option.
Tell Me / Show Me
CHECK Constraints
The CHECK constraint explicitly defines a condition
that must be met. To satisfy the constraint, each row in
the table must make the condition either True or
unknown (due to a null). The condition of a CHECK
constraint can refer to any column in the specified
table, but not to columns of other tables.
Tell Me / Show Me
CHECK Constraint Example
CREATE d_cds (cd_number NUMBER CONSTRAINT
d_cds_cd_num_range
CHECK (cd_number BETWEEN 10 AND 999) ,
year NUMBER(4) CONSTRAINT d_cds_year_min
CHECK (year > 1996) ,
producer VARCHAR2(10) CONSTRAINT d_cds_prod_list
CHECK (producer IN ('Old Town Records','The Music Man',
'Middle Earth Records','R&B Inc','Tunes Are US')) ;
Tell Me / Show Me
CHECK Constraint Conditions
• A CHECK constraint must only be on the row where the
constraint is defined.
• A CHECK constraint cannot be used in queries that refer to
values in other rows.
• The CHECK constraint cannot contain calls to the functions
SYSDATE, UID, USER, or USERENV. The statement
CHECK(SYSDATE >'05-MAY-99') is not allowed
• The CHECK constraint cannot use the pseudocolumns
CURRVAL, NEXTVAL, LEVEL, or ROWNUM. The statement
CHECK(NEXTVAL > 0) is not allowed.
• A single column can have multiple CHECK constraints that
reference the column in its definition. There is no limit to the
number of CHECK constraints that you can define on a column.
Tell Me / Show Me
CHECK Constraint Syntax
CHECK constraints can be defined at the column level
or the table level.
Column-level syntax:
salary NUMBER(8,2) CONSTRAINT f_staffs_min_salary
CHECK (salary > 0)
Table-level syntax:
CONSTRAINT f_staffs_min_salary CHECK (salary > 0)
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
Summary
Objectives Summarized
In this lesson you have learned to:
• Provide an example of a PRIMARY KEY, FOREIGN
KEY and CHECK constraint
• Explain the purpose of defining PRIMARY KEY,
FOREIGN KEY and CHECK constraints
• Demonstrate the creation of constraints at the
column level and table level in a CREATE TABLE
statement
• Evaluate a business problem requiring the addition
of a PRIMARY KEY and FOREIGN KEY constraint
and writing the code to execute the change
• Query the data dictionary for
USER_CONSTRAINTS and interpret the
information returned
Copyright © 2011, Oracle. All rights reserved. 24
PRIMARY KEY, FOREIGN KEY and CHECK Constraints
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
Managing Constraints
The ALTER TABLE statement is used to make changes to constraints in
existing tables. These changes can include adding or dropping
constraints, enabling or disabling constraints, and adding a NOT NULL
constraint to a column. The guidelines for making changes to constraints
are:
• You can add, drop, enable or disable a constraint, but you cannot
modify its structure.
• You can add a NOT NULL constraint to an existing column by using
the MODIFY clause of the ALTER TABLE statement. MODIFY is
used because NOT NULL is a column-level change.
• You can define a NOT NULL constraint only if the table is empty or if
the column has a value for every row.
Tell Me / Show Me
The ALTER statement requires:
• name of the table
• name of the constraint
• type of constraint
• name of the column affected by the constraint
Tell Me / Show Me
Adding Constraints
To add a constraint to an existing table, use the
following SQL syntax:
Tell Me / Show Me
Adding Constraints (continued)
If the constraint is a FOREIGN KEY constraint, the REFERENCES
keyword must be included in the statement:
Tell Me / Show Me
Adding Constraints Example
Consider the DJs on Demand database. The primary key from the D_CLIENTS table is
entered in the D_EVENTS table as a foreign key. The following example demonstrates
the syntax to add this foreign key to the D_EVENTS table:
D_EVENTS
ID NAME EVENT_ DESCRIPTION COST VENUE_ID PACKAGE_CODE THEME_CODE CLIENT_
DATE NUMBER
100 Peters 14-MAY-04 Party for 200, red, 8000 100 112 200 5922
Graduation white, blue motif
105 Vigil Wedding 28-APR-04 Black tie at Four 10000 220 200 200 6133
Seasons Hotel
Tell Me / Show Me
Adding Constraints Conditions
If the constraint is a NOT NULL constraint, the ALTER
TABLE statement uses MODIFY in place of ADD. NOT
NULL constraints can be added only if the table is empty
or if the column has a value for every row:
Tell Me / Show Me
Why Enable and Disable Constraints?
To enforce the rules defined by integrity constraints, the
constraints should always be enabled. In certain situations,
however, it is desirable to temporarily disable the integrity
constraints of a table temporarily for performance reasons, such
as:
Tell Me / Show Me
Dropping Constraints
To drop a constraint, you need to know the name of the constraint. If
you do not know it, you can find the constraint name from the
USER_CONSTRAINTS and USER_CONS_COLUMNS in the data
dictionary.
Tell Me / Show Me
Disabling Constraints
By default, whenever an integrity constraint is defined in a
CREATE or ALTER TABLE statement, the constraint is
automatically enabled (enforced) by Oracle unless it is
specifically created in a disabled state using the DISABLE
clause.
Tell Me / Show Me
Using the DISABLE Clause
You can use the DISABLE clause in both the ALTER TABLE
statement and the CREATE TABLE statement.
Tell Me / Show Me
Using the CASCADE Clause
The CASCADE clause disables dependent integrity
constraints. If the constraint is later enabled, the dependent
constraints are not automatically enabled.
Tell Me / Show Me
Enabling Constraints
To activate an integrity constraint currently disabled, use the
ENABLE clause in the ALTER TABLE statement. ENABLE ensures
that all incoming data conforms to the constraint.
You can use the ENABLE clause in both the CREATE TABLE
statement and the ALTER TABLE statement.
Tell Me / Show Me
Enabling Constraint Considerations
If you enable a constraint, that constraint applies to all the data
in the table.
All the data in the table must fit the constraint. If you enable a
UNIQUE KEY or PRIMARY KEY constraint, a UNIQUE or
PRIMARY KEY index is created automatically.
This is like switching the constraint back on, after you switched it
off.
Tell Me / Show Me
Cascading Constraints
Cascading referential-integrity constraints allow you to define the
actions the database server takes when a user attempts to
delete or update a key to which existing foreign keys point. The
CASCADE CONSTRAINTS clause is used along with the DROP
COLUMN clause. It drops all referential-integrity constraints that
refer to the primary and unique keys defined on the dropped
columns. It also drops all multicolumn constraints defined on the
dropped columns. If an ALTER TABLE statement does not
include the CASCADE CONSTRAINTS option, any attempt to
drop a primary key or multicolumn constraint will fail. Remember,
you can’t delete a parent value if child values exist in other
tables.
Tell Me / Show Me
When CASCADE is Not Required
If all columns referenced by the constraints defined on the
dropped columns are also dropped, then CASCADE
CONSTRAINTS is not required. For example, assuming that no
other referential constraints from other tables refer to column PK,
it is valid to submit the following statement without the CASCADE
CONSTRAINTS clause:
Tell Me / Show Me
Viewing Constraints
After creating a table, you can confirm its existence by
issuing a DESCRIBE command. The only constraint that
you can verify using DESCRIBE is the NOT NULL
constraint.
Tell Me / Show Me
Viewing Constraints SELECT constraint_name, constraint_type
(continued) FROM user constraints
WHERE table_name = ‘ANIMALS’;
To view all constraints on your table,
query the USER_CONSTRAINTS CONSTRAINT_NAME CONSTRAINT_TYPE
table. ANIMALS_ADMIT_NN C Check Constraint
Tell Me / Show Me
Viewing Constraints With The Data Dictionary
You can browse the Data Dictionary using Oracle Application
Express. Below is a summary of the steps used to browse the
Data Dictionary.
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
ALTER TABLE
DISABLE CONSTRAINT
CASCADE clause
ENABLE CONSTRAINT
DROP COLUMN
CASCADE RESTRAINTS clause
DROP CONSTRAINT
Summary
Objectives Summarized
In this lesson you have learned to:
• List four different functions that the ALTER
statement can perform on constraints
• Write ALTER TABLE statements to add, drop,
disable and enable constraints
• Name a business function that would require a
DBA to drop, enable and/or disable a constraint
or use the CASCADE syntax
• Query the data dictionary for
USER_CONSTRAINTS and interpret the
information returned
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
View
A view, like a table, is a CREATE VIEW view_employees
database object. However, AS SELECT first_name, last_name, email
FROM employees
views are not “real" tables. WHERE employee_id BETWEEN 100 and 124;
They are logical
representations of existing FIRST_NAME LAST_NAME EMAIL
tables or of another view. Steven King SKING
Neena Kochhar NKOCHHAR
Views contain no data of their Lex De Haan LDEHAAN
own. They function as a Alexander Hunold AHUNOLD
window through which data Bruce Ernst BERNST
from tables can be viewed or Diana Lorentz DLORENTZ
Kevin Mourgos KMOURGOS
changed. The tables on which
a view is based are called
"base" tables. The view is a
query stored as a SELECT
statement in the data
dictionary.
Copyright © 2011, Oracle. All rights reserved. 5
Creating Views
Tell Me / Show Me
Why Use Views?
• Views restrict access to base table data because the view can
display selective columns from the table.
• Views can be used to reduce the complexity of executing queries
based on more complicated SELECT statements. For example,
the creator of the view can construct join statements that retrieve
data from multiple tables. The user of the view neither sees the
underlying code nor how to create it. The user, through the view,
interacts with the database using simple queries.
• Views can be used to retrieve data from several tables, providing
data independence for users. Users can view the same data in
different ways.
• Views provide groups of users with access to data according to
their particular permissions or criteria.
Tell Me / Show Me
Creating A View
To create a view, embed a subquery within the CREATE VIEW statement.
The syntax of a view statement is as follows:
Example
CREATE OR REPLACE VIEW view_of_animals
AS SELECT animal_name…;
Tell Me / Show Me
OR REPLACE re-creates the view if it already exists
Creating A View (continued)
FORCE creates the view regardless of whether
or not the base tables exists
CREATE [OR REPLACE]
[FORCE| NOFORCE] VIEW NOFORCE creates the view only if the base table
view_name exists (default)
view_name name of view
[(alias [, alias]...)] alias specifies a name for each expression
AS subquery selected by the view’s query
Tell Me / Show Me
Guidelines for Creating A View
• The subquery that defines the view can contain
complex SELECT syntax.
• The subquery that defines the view cannot contain an
ORDER BY clause. The ORDER BY clause is
specified when you retrieve data from the view.
• You can use the OR REPLACE option to change the
definition of the view without having to drop it or
regrant object privileges previously granted on it.
• Aliases can be used for the column names in the
subquery.
Tell Me / Show Me
CREATE VIEW Features
There are two classifications Feature Simple Views Complex Views
for views: simple and Number of One One or more
complex. The table tables used to
derive data
summarizes the features of
Can contain No Yes
each view. functions
Can contain No Yes
groups of data
Can perform Yes Not always
DML
operations
(INSERT,
UPDATE,
DELETE)
through a view
Tell Me / Show Me
Simple View
The view shown below is an example of a simple view. The
subquery derives data from only one table and it does not
contain a join function or any group functions. Because it is a
simple view, INSERT, UPDATE, DELETE and MERGE
operations affecting the base table could possibly be performed
through the view.
Tell Me / Show Me
Simple View (continued)
Column names in the SELECT statement can have aliases as
shown below. Note that aliases can also be listed after the
CREATE VIEW statement and before the SELECT subquery.
Tell Me / Show Me
Simple View (continued)
It is possible to create a view regardless of whether or not the
base tables exist. Adding the word FORCE to the CREATE VIEW
statement creates the view.
Tell Me / Show Me
Complex View
Complex views are views that can contain group functions and
joins. The following example creates a view that derives data from
two tables.
Tell Me / Show Me
Complex View (continued)
Group functions can also be added to complex-view statements.
Tell Me / Show Me
Modifying A View
To modify an existing view without having to re-create it, use
the OR REPLACE option in the CREATE VIEW statement.
The old view is replaced by the new version. For example:
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
Alias
Complex review
CREATE VIEW
FORCE
NOFORCE
REPLACE
Simple view
Subquery
View
VIEW_NAME
Summary
Objectives Summarized
In this lesson you have learned to:
• List three uses for views from the standpoint of a
database administrator
• Explain, from a business perspective, why it is
important to be able to create and use logical subsets
of data derived from one or more tables
• Create a view with and without column aliases in the
subquery using a single base table
• Create a complex view that contains group functions
to display values from two tables
• Retrieve data from a view
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
In this lesson, you will learn how to allow data access and at the
same time ensure data security.
Tell Me / Show Me
DML Statements And Views
The DML operations INSERT, UPDATE and DELETE can be
performed on simple views. These operations can be used to
change the data in the underlying base tables. If you create a
view that allows users to view restricted information using the
WHERE clause, users can still perform DML operations on all
of the view's columns.
Tell Me / Show Me
DML Statements And
Views (Continued)
For example, the view CREATE VIEW view_dept50 AS
SELECT department_id, employee_id, first_name,
shown at right was
last_name, salary
created for the managers FROM employees
of department 50 from the WHERE department_id = 50;
Oracle database. The
SQL Statement (All DDL statements are auto committed.)
intent of this view is to
allow managers of select * from view_dept50;
department 50 to see
information about their SQL Query Results
DEPARTMENT_ID EMPLOYEE_ID FIRST_N LAST_ SALARY
employees. AME NAME
Tell Me / Show Me
Controlling Views
Using the view as stated, it is possible to INSERT, UPDATE, and
DELETE information for all departments.
This may not be what the DBA intended when the view was
created.
Tell Me / Show Me
Views With CHECK Option
The WITH CHECK OPTION ensures that DML operations
performed on the view stay within the domain of the view. Any
attempt to change the department number for any row in the view
fails because it violates the WITH CHECK OPTION constraint.
Notice in the example below that the WITH CHECK OPTION
CONSTRAINT was given the name view_dept50_check.
Tell Me / Show Me
Views With READ ONLY
The WITH READ ONLY option ensures that no DML
operations occur through the view. Any attempt to execute
an INSERT, UPDATE or DELETE statement will result in an
Oracle server error.
Tell Me / Show Me
DML Restrictions
Simple views and complex views differ in SELECT rownum, first_name
FROM employees
their ability to allow DML operations WHERE emloyee_id
through a view. BETWEEN 100 AND 105;
ROWNUM FIRST_NAME
For simple views, DML operations can be 1 Steven
performed through the view.
2 Neena
3 Lex
For complex views, DML operations are 4 Alexander
not always allowed. 5 Bruce
Tell Me / Show Me
DML Restrictions (continued)
5 Bruce
Tell Me / Show Me
DML Restrictions (continued)
Tell Me / Show Me
DML Restrictions (continued)
Tell Me / Show Me
What’s Next in Computing?
Moore's Law--which states that the number of
transistors on a given chip can be doubled every
two years--has been the guiding principle of
progress in electronics and computing since
Moore first formulated the famous prediction in 1965.
Many people are wondering the same thing and working to turn their
dreams into reality.
Let’s look into the future of computing and technology. It's your future
and you will be a part of it.
Tell Me / Show Me
Future Trends To Consider
Wireless technologies -- when can we pull the plug?
How big is big? What technologies are being developed to store
large quantities of information?
How much is too much? What are the trends in storing personal
data and what are the issues being addressed related to personal
privacy?!
What is data mining? How can businesses target product
advertising gleaned from data stored about your buying habits or
Internet browsing preferences?
How can we make computers know how we see and feel?
What technologies are being developed to protect copyrighted
material?
How small is small? What are the limits to miniaturizing computer
technologies? Can a phone, computer, and camera be integrated
into a wrist watch?
Tell Me / Show Me
Terminology
Key term used in this lesson include:
ROWNUM
WITH CHECK OPTION
WITH READ ONLY
Summary
Objectives Summarized
In this lesson you have learned to:
• Write and execute a query that performs DML
operations on a simple view
• Name the conditions that restrict your ability to
modify a view using DML operations
• Write and execute a query using the WITH
CHECK OPTION clause
• Explain the use of WITH CHECK OPTION as it
applies to integrity constraints and data
validation
• Apply the WITH READ ONLY option to a view to
restrict DML operations
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
Deleting A View
Because a view contains no data of its own,
removing it does not affect the data in the
underlying tables. If the view was used to
INSERT, UPDATE or DELETE data in the past,
these changes to the base tables remain.
Tell Me / Show Me
Inline Views
Inline views are also referred to as queries in
the FROM clause.
Tell Me / Show Me
Inline Views (continued)
As shown in the example below, the FROM clause
contains a SELECT statement that retrieves data
much like any SELECT statement. The data
returned by the subquery is given an alias (p),
which is then used in conjunction with the main
query to return selected columns from both query sources.
Tell Me / Show Me
TOP-N-ANALYSIS
Top-n-analysis is a SQL operation used to rank results. The use of top-n-
analysis is useful when you want to retrieve the top-n records, or top 4
records, of a result set returned by a query.
The top-n-analysis query uses an inline subquery to return a result set. You
can use ROWNUM in your query to assign a row number to the result set.
The main query then uses ROWNUM to order the data and return the top
four.
Tell Me / Show Me
TOP-N-ANALYSIS (continued)
SELECT ROWNUM as RANK, year, title
FROM (SELECT year, title
FROM d_cds
ORDER BY year)
WHERE ROWNUM <= 4;
In the example above, the inline subquery first selects the list of years and titles of the
DJ on Demand's CDs:
(SELECT year, title FROM d_cds ,,,,,,)
Then the inline subquery orders the years from oldest to newest.
(SELECT …… ORDER BY year)
The outer query WHERE clause is used to restrict the number of rows returned and
must use a < or <= operator.
WHERE ROWNUM <= 4;
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
INLINE VIEW
DROP VIEW
TOP-N ANALYSIS
Summary
Objectives Summarized
In this lesson you have learned to:
• Create and execute a SQL statement that removes a view
• Create and execute a query to create an inline view
• Create and execute a top-n-analysis query
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
The Sequence Object
You already know how to create two kinds of database objects, the TABLE
and the VIEW.
As you’ll recall, primary keys must be unique for each row. The sequence
is generated and incremented (or decremented) by an internal Oracle
routine. This can be a time-saving object because it reduces the amount of
code you need to write.
Tell Me / Show Me
The Sequence Object (continued)
Sequence numbers are stored and generated independently of
tables. Therefore, the same sequence can be used for multiple
tables.
To create a SEQUENCE:
CREATE SEQUENCE sequence
[INCREMENT BY n]
[START WITH n]
[{MAXVALUE n | NOMAXVALUE}]
[{MINVALUE n | NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n | NOCACHE}];
Tell Me / Show Me
sequence is the name of the sequence generator
Sequence Syntax (object)
INCREMENT BY n specifies the interval between
CREATE SEQUENCE sequence numbers where n is an
sequence integer (If this clause is omitted, the
sequence increments by 1.)
[INCREMENT BY n] START WITH n specifies the first sequence number to
be generated (If this clause is omitted,
[START WITH n] the sequence starts with 1.)
MAXVALUE n specifies the maximum value the
[{MAXVALUE n | sequence can generate
NOMAXVALUE specifies a maximum value of 10^27
NOMAXVALUE}] for an ascending sequence and -1 for a
descending sequence (default)
[{MINVALUE n |
MINVALUE n specifies the minimum sequence value
NOMINVALUE}] NOMINVALUE specifies a minimum value of 1 for an
ascending sequence and –(10^26) for
[{CYCLE | NOCYCLE}] a descending sequence (default)
CYCLE | specifies whether the sequence
[{CACHE n | NOCACHE}]; NOCYCLE continues to generate values after
reaching its maximum or minimum
value (NOCYCLE is the default option.)
CAHCE n | specifies how many values the Oracle
NOCACHE server pre-allocates and keep in
memory. (By default, the Oracle server
caches 20 values.) If the system
crashes, the values are lost.
Tell Me / Show Me
Creating A Sequence
In the SEQUENCE created for the London CREATE SEQUENCE runner_id_seq
Marathon runners, the numbers will INCREMENT BY 1
increment by 1, starting with the number 1. START WITH 1
In this case, beginning the sequence with MAXVALUE 50000
1 is probably the best starting point. It is a NOCACHE
NOCYCLE;
tradition that the best runner in the elite
group wears number 1. For other
situations, such as department IDs and
employee IDs, the starting number may be
assigned differently.
Tell Me / Show Me
Creating A Sequence (continued)
The NOCACHE option prevents values
CREATE SEQUENCE runner_id_seq
in the SEQUENCE from being cached in INCREMENT BY 1
memory, which in the event of system START WITH 1
failure prevents numbers preallocated MAXVALUE 50000
and held in memory from being lost. NOCACHE
NOCYCLE;
Tell Me / Show Me
Confirming Sequences
To verify that a sequence was created, query the USER_OBJECTS
data dictionary. To see all of the SEQUENCE settings, query the
USER_SEQUENCES data dictionary as shown below. List the
value names in the SELECT statement as shown below.
Tell Me / Show Me
NEXTVAL And CURRVAL Pseudocolumns
The NEXTVAL pseudocolumn is used to extract
successive sequence numbers from a specified
sequence. You must qualify NEXTVAL with the
sequence name.
Tell Me / Show Me
NEXTVAL And CURRVAL Pseudocolumns (continued)
The example below inserts a new department in the
DEPARTMENTS table. It uses the
DEPARTMENTS_SEQ sequence for generating a
new department number as follows:
Tell Me / Show Me
NEXTVAL And CURRVAL Pseudocolumns (continued)
Suppose now you want to hire employees to staff the new
department. The INSERT statement to be executed for all new
employees can include the following code:
Tell Me / Show Me
NEXTVAL And CURRVAL Pseudocolumns (continued)
The CURRVAL pseudocolumn in the example below is used to
refer to a sequence number that the current user has just
generated. NEXTVAL must be used to generate a sequence
number in the current user’s session before CURRVAL can be
referenced. You must qualify CURRVAL with the sequence
name. When sequence.CURRVAL is referenced, the last value
generated by that user’s process is returned.
Tell Me / Show Me
Using A Sequence
After you create a sequence, it generates sequential numbers for
use in your tables. Reference the sequence values by using the
NEXTVAL and CURRVAL pseudocolumns.
Tell Me / Show Me
Using A Sequence (continued)
You cannot use NEXTVAL and CURRVAL in the following
contexts:
Tell Me / Show Me
Using A Sequence (continued)
To continue our London Marathon example, the following
syntax would be used to insert a new participant's information
into the runners' table. The runner's identification number
sdp_s12_l03_a02
would be generated by retrieving the NEXTVAL from the
sequence.
Tell Me / Show Me
Using A Sequence (continued)
To view the current value for the runners_id_seq, CURRVAL is used.
Note the use of the DUAL table in this example. Oracle Application
Developer will not execute this query, but you should understand how
this works.
SELECT runner_id_seq.CURRVAL
FROM dual;
Tell Me / Show Me
Nonsequential Numbers
Although sequence generators issue sequential numbers without
gaps, this action occurs independent of a database commit or
rollback. Gaps (nonsequential numbers) can be generated by:
Tell Me / Show Me
Viewing the Next Value
If the sequence was created with NOCACHE, it is possible
to view the next available sequence value without
incrementing it by querying the USER_SEQUENCES
table.
Tell Me / Show Me
Modifying A Sequence
As with the other database objects you've created, a SEQUENCE
can also be changed using the ALTER SEQUENCE statement.
What if the London Marathon exceeded the 50,000 runner
registrations and you needed to add more numbers? The
sequence could be changed to increase the MAXVALUE without
changing the existing number order.
Tell Me / Show Me
Modifying A Sequence (continued)
Some validation is performed when you alter a
sequence. For example, a new MAXVALUE that is less than the current
sequence number cannot be executed.
ERROR at line 1:
ORA-04009: MAXVALUE cannot be made to be less than the current
value
Tell Me / Show Me
ALTER SEQUENCE Guidelines
A few guidelines apply when executing an ALTER
SEQUENCE statement. They are:
• You must be the owner or have the ALTER privilege for
the sequence in order to modify it.
• Only future sequence numbers are affected by the
ALTER SEQUENCE statement.
• The START WITH option cannot be changed using
ALTER SEQUENCE. The sequence must be dropped
and re-created in order to restart the sequence at a
different number.
Tell Me / Show Me
Removing A Sequence
To remove a sequence from the data
dictionary, use the DROP SEQUENCE
statement. You must be the owner of
the sequence or have DROP ANY
SEQUENCE privileges to remove it. sdp_s12_l03_a03
Once removed, the sequence can no
longer be referenced.
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
NEXTVAL
CURRVAL
INCREMENT BY
Sequences
CACHE/ NOCACHE
MAXVALUE
NOMAXVALUE
CREATE SEQUENCE
STARTS WITH
CYCLE/ NOCYCLE
MINVALUE
NO MINVALUE
Summary
Objectives Summarized
In this lesson you have learned to:
• List at least three useful characteristics of a
sequence
• Write and execute a SQL statement that creates a
sequence
• Query the data dictionary using
USER_SEQUENCES to confirm a sequence
definition
• Apply the rules for using NEXTVAL to generate
sequential unique numbers in a table
• List the advantages and disadvantages of caching
sequence values
• Name three reasons why gaps can occur in a
sequence
Copyright © 2011, Oracle. All rights reserved. 25
Sequences
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
Indexes
An Oracle Server index is a schema object that can speed up the retrieval of
rows by using a pointer.
Indexes can be created explicitly or automatically. If you do not have an
index on the column you’re selecting, then a full table scan occurs.
An index provides direct and fast access to rows in a table. Its purpose is to
reduce the necessity of disk I/O (input/output) by using an indexed path to
locate data quickly. The index is used and maintained automatically by the
Oracle Server. Once an index is created, no direct activity is required by the
user.
Tell Me / Show Me
Indexes (continued)
Indexes are logically ID TITLE DURATION ARTIST TYPE_CODE
and physically 45 It’s Finally 5 min The Hobbits 12
independent of the Over
table they index. This 46 I’m Going 2 min Jane Pop 12
to Miss My
means that they can be Teacher
created or dropped at 47 Hurrah for 3 min The Jubilant 77
any time and have no Today Trio
effect on the base 48 Meet Me 6 min Bobby West 1
tables or other indexes. At the
Altar
49 Let’s 8 min The Celebrants 77
Note: When you drop Celebrate
50 All These 10 min Diana Crooner 88
a table, corresponding Years
indexes are also
dropped.
Tell Me / Show Me
Types Of Indexes
Two types of indexes can be created:
Tell Me / Show Me
Creating An Index
Create an index on one or more columns by issuing the
CREATE INDEX statement:
Tell Me / Show Me
Creating An Index (continued)
For example, to improve the speed of query access to the
TITLE column in the DJ on Demand D_CDS table:
Tell Me / Show Me
When To Create An Index
An index should be created only if:
Tell Me / Show Me
When Not To Create An Index
When deciding whether or not to create an index, more is
not always better. Each DML operation (INSERT, UPDATE,
DELETE) that is performed on a table with indexes means
that the indexes must be updated. The more indexes you
have associated with a table, the more effort it takes to
update all the indexes after the DML operation.
Tell Me / Show Me
When Not To Create An Index (continued)
It is usually not worth creating an index if:
• The table is small
• The columns are not often used as a condition in the
query
• Most queries are expected to retrieve more than 2-4 % of
the rows in the table
• The table is updated frequently
• The indexed columns are referenced as part of an
expression
Tell Me / Show Me
Composite Index
A composite index (also called a "concatenated" index) is an
index that you create on multiple columns in a table. Columns
in a composite index can appear in any order and need not be
adjacent in the table.
Tell Me / Show Me
Composite Index (continued)
Null values are not included in the composite index.
Tell Me / Show Me
Confirming Indexes
Confirm the existence of indexes from the USER_INDEXES
data dictionary view. You can also check the columns
involved in an index by querying the
USER_IND_COLUMNS view.
Tell Me / Show Me
Confirming Indexes
SELECT ic.index_name,
ic.column_name,
ic.column_position col_pos,
ix.uniqueness
FROM user_indexes ix, user_ind_columns ic
WHERE ic.index_name = ix.index_name
AND ic.table_name = 'EMPLOYEES';
Tell Me / Show Me
Function-based Indexes
A function-based index stores the indexed values and uses
the index based on a SELECT statement to retrieve the
data.
Tell Me / Show Me
Function-based Indexes (continued)
Function-based indexes are useful when you don't know in what
case the data was stored in the database. For example, you can
create a function-based index that can be used with a SELECT
statement using UPPER in the WHERE clause. The index will
be used in this search.
SELECT *
FROM employees
WHERE UPPER(last_name) = ’KING’;
Tell Me / Show Me
Function-based Indexes (continued)
Function-based indexes defined with the
UPPER(column_name) or LOWER(column_name) keywords
allow case-insensitive searches.
Tell Me / Show Me
Function-based Indexes (continued)
For example, the following statement allows for case-
insensitive searches using the index:
SELECT *
FROM d_partners
WHERE UPPER(last_name) = ’CHO’;
Tell Me / Show Me
Function-based Indexes (continued)
To ensure that the Oracle Server uses the index rather than performing a full
table scan, be sure that the value of the function is not null in subsequent
queries. For example, the following statement is guaranteed to use the index,
but without the WHERE clause the Oracle Server may perform a full table
scan:
SELECT *
FROM d_partners
WHERE UPPER (last_name) IS NOT NULL
ORDER BY UPPER (last_name);
The Oracle Server treats indexes with columns marked DESC as function-
based indexes. The columns marked DESC are sorted in descending order.
Tell Me / Show Me
Function-based Indexes (continued)
Tell Me / Show Me
Function-based Indexes (continued)
Tell Me / Show Me
Function-based Indexes (continued)
Tell Me / Show Me
Function-based Indexes (continued)
Tell Me / Show Me
Removing An Index
You cannot modify indexes. To change an index, you must drop it and then
re-create it. Remove an index definition from the data dictionary by issuing
the DROP INDEX statement. To drop an index, you must be the owner of
the index or have the DROP ANY INDEX privilege. If you drop a table,
indexes and constraints are automatically dropped, but views and
sequences remain.
In the syntax:
index is the name of the index
Tell Me / Show Me
SYNONYM
In SQL, as in language, a synonym is a word or
expression that is an accepted substitute for another word.
Synonyms are used to simplify access to objects by
creating another name for the object. Synonyms can make
referring to a table owned by another user easier and
shorten lengthy object names. For example, to refer to the
amys_copy_d_track_listings table in your classmate's
schema, you can prefix the table name with the name of
the user who created it followed by a period and then the
table name, as in USMA_SBHS_SQL01_S04.amy.
Tell Me / Show Me
SYNONYM (continued)
Creating a synonym eliminates the need to qualify the object
name with the schema and provides you with an alternative
name for a table, view, sequence, procedure, or other
objects. This method can be especially useful with lengthy
object names, such as views. The database administrator
can create a public synonym accessible to all users and can
specifically grant the CREATE PUBLIC SYNONYM privilege
to any user, and that user can create public synonyms.
Tell Me / Show Me
SYNONYM (continued)
CREATE [PUBLIC] SYNONYM synonym
FOR object;
In the syntax:
• PUBLIC: creates a synonym accessible to all users
• synonym: is the name of the synonym to be created
• object: identifies the object for which the synonym is
created
Tell Me / Show Me
SYNONYM Guidelines
• The object cannot be contained in a package.
• A private synonym name must be distinct from all other
objects owned by the same user.
To remove a synonym:
Tell Me / Show Me
Confirming A SYNONYM
The existence of synonyms can be confirmed by querying
the USER_SYNONYMS data dictionary view.
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
DROP INDEX
Synonym
CREATE PUBLIC SYNONYM
Non- unique index
Unique index
Composite index
Confirming index
Function- based index
Summary
Objectives Summarized
In this lesson you have learned to:
• Define an index and its use as a schema object
• Define ROWID and its use in locating
information in a database
• Name the conditions that cause an index to be
created automatically
• Create and execute a CREATE INDEX and
DROP INDEX statement
• Create function-based indexes
• Create private and public synonyms
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
Controlling User Access
In a multiple-user environment, you want to maintain
security of the database access and use. With Oracle
Server database security, you can do the following:
Tell Me / Show Me
Database Security
Database security can be classified into two categories:
• system security
• data security
System security covers access and use of the database at the system
level, such as creating users, usernames and passwords, allocating disk
space to users, and granting the system privileges that users can
perform such as creating tables, views and sequences. There are more
than 100 distinct system privileges.
Tell Me / Show Me
Privileges and Schemas
Privileges are the right to execute particular SQL statements. The
DBA is a high-level user with the ability to grant users access to
the database and its objects. Users require system privileges to
gain access to the database. They require object privileges to
manipulate the content of the objects in the database. Users can
also be given the privilege to grant additional privileges to other
users or to roles, which are named groups of related privileges.
Tell Me / Show Me
Privileges and Schemas (continued)
A schema is a collection of objects, such as tables, views,
and sequences. The schema is owned by a database user
and has the same name as that user.
In this course, your schema name is a combination of your
city, state/country, your school name, course name and
student number.
Tell Me / Show Me
System Security
This level of security covers access System Privilege Operations Authorized
and use of the database at the CREATE USER Grantee can create other
system level. There are more than Oracle users (a privilege
required for a DBA role)
100 distinct system privileges. DROP USER Grantee can drop
another user
DROP ANY TABLE Grantee can drop a table
System privileges such as the ability in any schema
BACKUP ANY TABLE Grantee can backup any
to create or remove users, remove table in any schema with
tables or backup tables are usually the export utility
held only by the DBA. SELECT ANY TABLE Grantee can query
tables, views, or
snapshots in any
schema
The table on the right lists some of CREATE ANY TABLE Grantee can create
the system privileges which the DBA tables in any schema
Tell Me / Show Me
System Privileges
The DBA creates the user by System Privilege Operations Authorized
executing the CREATE USER CREATE USER Grantee can create other
Oracle users (a privilege
statement. The user does not required for a DBA role.)
have any privileges at this point. DROP USER Grantee can drop
The DBA can then grant another user.
DROP ANY TABLE Grantee can drop a table
required privileges to that user. in any schema.
BACKUP ANY TABLE Grantee can backup any
table in any schema with
CREATE USER user the export utility.
SELECT ANY TABLE Grantee can query
IDENTIFIED BY password; tables, views, or
snapshots in any
schema.
CREATE USER scott CREATE ANY TABLE Grantee can create
tables in any schema.
IDENTIFIED BY ur35scott;
Tell Me / Show Me
System Privileges (continued)
Using the ALTER USER statement, a user can change
their password.
Tell Me / Show Me
User System Privileges
The DBA uses the GRANT System Privilege Operations Authorized
statement to allocate system CREATE SESSION Connect to the database
privileges to the user. System CREATE TABLE Create tables in the
user’s schema.
privileges determine what the
CREATE SEQUENCE Create a sequence in
user can do at the database the user’s schema.
level. Once the user has been CREATE VIEW Create a view in the
user’s schema.
granted the privileges, the user CREATE PROCEDURE Create a procedure,
can immediately use those function, or package in
privileges. the user’s schema.
Tell Me / Show Me
User System Privileges (continued)
A user must have a CREATE SESSION privilege as well as
having a user id if they are to be able to access a database.
Tell Me / Show Me
Object Security
This level of security covers access and use
of the database objects and the actions
users can have on those objects.
sdp_s13_l03_a02
Tell Me / Show Me
Object Privileges Object Table View Sequence Procedure
Privilege
Each object has a ALTER X X
DELETE X X
particular set of EXECUTE X
grantable privileges. INDEX X X
INSERT X X
The table below lists the REFERENCE X
privileges for various S
SELECT X X X
objects. It is important to UPDATE X X
note the following four
points regarding object
privileges:
1. The only privileges that apply to a sequence are SELECT and
ALTER.
Remember, a sequence uses ALTER to change the
INCREMENT, MAXVALUE, CACHE/NOCACHE, or
CYCLE/NOCYCLE options.
START WITH cannot be changed using ALTER.
Copyright © 2011, Oracle. All rights reserved. 14
Controlling User Access
Tell Me / Show Me
Object Privileges (continued)
2. You can grant UPDATE, REFERENCES, and INSERT on
individual columns on a table. For example:
GRANT UPDATE (auth_expense)
ON d_partners TO allison_plumb
3. A SELECT privilege can be restricted by creating a view with a
subset of columns and granting the SELECT privilege only on
the view. You can't grant SELECT on individual columns.
Object Table View Sequence Procedure
Privilege
ALTER X X
DELETE X X
EXECUTE X
INDEX X X
INSERT X X
REFERENCES X
SELECT X X X
UPDATE X X
Tell Me / Show Me
Object Privileges (continued)
• A privilege granted on a synonym is converted to a privilege
on the base table referenced by the synonym. In other words,
a synonym is simply a new, easier-to-use name. Using this
name to grant a privilege is the same as granting the privilege
on the table itself.
Tell Me / Show Me
The PUBLIC Keyword
An owner of a table can grant access to all users by using
the PUBLIC keyword.
The example shown below allows all users on the system
to query data from Alice’s DEPARTMENTS table.
GRANT select
ON alice.departments
TO PUBLIC;
Tell Me / Show Me
The PUBLIC Keyword (continued)
If a statement does not use the full name of an object, the
Oracle server implicitly prefixes the object name with the
current user’s name (or schema). If user Scott queries the
DEPARTMENTS table, for example, the system selects from
the SCOTT.DEPARTMENTS table.
If a statement does not use the full name of an object, and
the current user does not own an object of that name, the
system prefixes the object name with PUBLIC.
For example, if user Scott queries the USER_OBJECTS
table, and Scott does not own such a table, the system
selects from the data dictionary view by way of the
PUBLIC.USER_OBJECTS public synonym.
Tell Me / Show Me
Confirming Granted Privileges
If you attempt to perform an unauthorized operation, such
as deleting a row from a table for which you do not have the
DELETE privilege, the Oracle server does not permit the
operation to take place.
Tell Me / Show Me
View Privileges Data Dictionary View Description
ROLE_SYS_PRIVS System privileges
You can access the data granted to roles
dictionary to view the ROLE_TAB_PRIVS Table privileges
privileges that you have. granted to roles
USER_ROLE_PRIVS Roles accessible by
The chart shown describes the user
various data dictionary USER_TAB_PRIVS_MADE Object privileges
granted on the
views. user’s objects
USER_TAB_PRIVS_RECD Object privileges
granted to the user
Using Oracle Application USER_COL_PRIVS_MADE Object privileges
Express Developer, enter granted on the
columns of the
USER_ROLE_PRIVS, user’s objects
select the magnifying glass, USER_COL_PRIVS_RECD Object privileges
then select any item to granted to the user
on specific columns
Query By Example. Their USER_SYS_PRIVS Lists system
privileges will be returned. privileges granted to
the user
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
System privileges
Object privileges
System security
Schema
Role
Object security
Privilege
WITH GRANT OPTION
GRANT privilege
PUBLIC privilege
Database link
CREATE SESSION privilege
Summary
Objectives Summarized
In this lesson you have learned to:
• Compare the difference between object privileges
and system privileges
• Construct the two commands required to enable a
user to have access to a database
• Construct and execute a GRANT… ON …TO
statement to assign privileges to objects in their
schema to other users and/or PUBLIC
• Query the data dictionary to confirm privileges
granted
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
Roles
A role is a named group of related
SQL> CREATE ROLE manager;
privileges that can be granted to a
user. This method makes it Role created.
easier to revoke and maintain
privileges. A user can have SQL> GRANT create table, create view TO
manager;
access to several roles, and
several users can be assigned Grant succeeded.
the same role. Roles are typically
created for a database SQL> GRANT manager TO jennifer_cho;
application.
Grant succeeded.
Tell Me / Show Me
Roles (continued)
Use the following syntax to SQL> CREATE ROLE manager;
create a role: Role created.
After the role is created, the DBA can use the GRANT statement to assign
the role to users as well as assign privileges to the role. The example
shown creates a manager role and then allows managers to create tables
and views. It then grants the role to a user. Now the user can create tables
and views. If users have multiple roles granted to them, they receive all of
the privileges associated with all of the roles.
Note: The CREATE ROLE is a system privilege that has not been issued to
Academy classrooms.
Tell Me / Show Me
Characteristics Of Roles
• They are named
groups of related
privileges. Users
• They can be granted to
users. Manager
Tell Me / Show Me
Granting Object Privileges
Use the following syntax to Syntax Defined
grant object privileges: object_priv is an object privilege to be
granted
column_list specifies a column from a table
GRANT object_priv
or view on which privileges are
[(column_list)] granted
ON object_name ON object_name is the object on which the
privileges are granted
TO {user|role|PUBLIC}
TO user|role identifies the user or role to
[WITH GRANT OPTION]; whom the privilege is granted
PUBLIC grants object privileges to all
users
WITH GRANT OPTION Allows the grantee to grant the
object privileges to other users
and roles
Tell Me / Show Me
Object Privileges Guidelines
• To grant privileges on an object,
the object must be in your own Syntax Defined
schema, or you must have been object_priv is an object privilege to be
granted the object privileges granted
column_list specifies a column from a
WITH GRANT OPTION. table or view on which
• An object owner can grant any privileges are granted
Tell Me / Show Me
GRANT Examples
Scott King (username 1. GRANT select
scott_king) has created a ON d_songs
TO PUBLIC;
d_songs table. In Example 1 on
the right, all users are granted 2. GRANT update (title, artist)
permission to SELECT from ON d_songs
Scott's d_songs table. TO jennifer_cho, manager;
3. SELECT *
FROM scott_king.d_songs;
Example 2 grants UPDATE
privileges to Jennifer and to the 4. CREATE SYNONYM songs
manager role on specific FOR scott_king.d_songs;
columns in Scott's d_songs
5. SELECT *
table. FROM songs;
Tell Me / Show Me
GRANT Examples (continued)
If Jennifer now wants to SELECT data from
1. GRANT select
Scott's table, the syntax she must use is ON d_songs
listed in Example 3. TO PUBLIC;
Tell Me / Show Me
WITH GRANT OPTION
A privilege that is granted using the WITH GRANT OPTION clause
can be passed on to other users and roles by the grantee. Object
privileges granted using the WITH GRANT OPTION clause are
revoked when the grantor’s privilege is revoked.
The example below gives user Scott access to your d_songs table
with the privileges to query the table and add rows to the table.
The example also allows Scott to give others these privileges:
Tell Me / Show Me
The PUBLIC Keyword
An owner of a table can grant access to all users by using the
PUBLIC keyword. The example shown below allows all users on the
system to query data from Jason’s d_songs table:
GRANT select
ON jason_tsang.d_songs
TO PUBLIC;
Tell Me / Show Me
DELETE Object
If you attempt to perform an unauthorized operation, such as
deleting a row from a table on which you do not have the DELETE
privilege, the Oracle Server does not permit the operation to take
place.
If you receive the Oracle Server error message “table or view does
not exist,” you have done one of the following:
Tell Me / Show Me
View Privileges Data Dictionary View Description
ROLE_SYS_PRIVS System privileges granted to
You can access the roles
data dictionary to ROLE_TAB_PRIVS Table privileges granted to
view the privileges roles
USER_ROLE_PRIVS Roles accessible by the user
that you have. The USER_TAB_PRIVS_MADE Object privileges granted on
chart at right the user’s objects
describes various USER_TAB_PRIVS_RECD Object privileges granted to
the user
data dictionary views. USER_COL_PRIVS_MADE Object privileges granted on
the columns of the user’s
objects
USER_COL_PRIVS_RECD Object privileges granted to
the user on specific columns
USER_SYS_PRIVS Lists system privileges
granted to the user
Tell Me / Show Me
Revoking Object Privileges
You can remove privileges granted to other users by using the
REVOKE statement. When you use the REVOKE statement, the
privileges that you specify are revoked from the users that you
name and from any other users to whom those privileges were
granted through the WITH GRANT OPTION clause.
Tell Me / Show Me
Revoking Object Privileges (continued)
Use the following syntax to revoke object privileges:
Tell Me / Show Me
With Grant Option
The example below revokes SELECT and INSERT privileges
given to user Scott on the d_songs table.
Tell Me / Show Me
With Grant Option (continued)
For example, if user A grants SELECT privileges on a table
to user B, including the WITH GRANT OPTION clause,
user B can grant to user C the SELECT privilege including
the WITH GRANT OPTION clause as well. Now, user C
can grant to user D the SELECT privilege.
UserA
Grants select
UserB
Grants select
UserD
Tell Me / Show Me
With Grant Option (continued)
However, if user A revokes privileges from user B, then
those privileges granted to users C and D are also
revoked.
Grants select
UserB
Grants select
UserD
Tell Me / Show Me
Private and Public Synonyms
As mentioned earlier in this lesson, you can create a
synonym to eliminate the need to qualify the object name
with the schema and provide you with an alternative
name for a table, view, sequence, procedure or other
objects.
Synonyms can be either private (the default) or public. A
public synonym can be created by Database
Administrators, or database users who have been given
the privileges to do so, but not everyone can
automatically create public synonyms.
Note: The CREATE PUBLIC SYNONYM privilege has not been granted to
Academy students.
Tell Me / Show Me
Roles and Privileges
Tell Me / Show Me
Database Links
A database link is a pointer that defines a one-way
communication path from one Oracle database to another
Oracle database. The link pointer is actually defined as an
entry in a data dictionary table. To access the link, you must
be connected to the local database that contains the data
dictionary entry.
Tell Me / Show Me
Database Links (continued)
A database link connection is “one-way” in the sense that a
client connected to local database A can use a link stored in
database A to access information in remote database B, but
users connected to database B cannot use the same link to
access data in database A.
CREATE DATABASE LINK – In Oracle Application Express,
there is no constant connection to the database, and as a
result, this feature is not available.
Local Remote
scott_king HQ_ACME.COM
SELECT * FROM database
emp@HQ_ACME.COM
Tell Me / Show Me
Database Links (continued)
If local users on database B want to access data on
database A, they must define a link that is stored in the data
dictionary of database B. A database link connection gives
local users access to data on a remote database. For this
connection to occur, each database in the distributed
system must have a unique global database name. The
global database name uniquely identifies a database server
in a distributed system.
Tell Me / Show Me
Database Links (continued)
The great advantage of database links is that they allow
users to access another user’s objects in a remote database
so that they are bounded by the privilege set of the object’s
owner. In other words, a local user can access a remote
database without having to be a user on the remote
database.
HQ.ACME.COM.
Tell Me / Show Me
Database Links (continued)
Typically, the Database Administrator is responsible for creating the
database link. The dictionary view USER_DB_LINKS contains
information on links to which a user has access. Once the database
link is created, you can write SQL statements against the data in the
remote site. If a synonym is set up, you can write SQL statements
using the synonym. For example:
Summary
Objectives Summarized
In this lesson you have learned to:
• Explain what a ROLE is and what its advantages are
• Construct a statement to create a ROLE and GRANT
privileges to it
• Construct a GRANT .. ON .. TO.. WITH GRANT OPTION
statement to assign privileges to objects in their schema to
other users and/or PUBLIC
• Construct and execute a statement to REVOKE object
privileges from other users and/or from PUBLIC
• Distinguish between privileges and roles
• Explain the purpose of a database link
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
You already know how to perform simple pattern matching using LIKE and
wildcards. Sometimes you might need to look for very complex text strings
such as finding the word “Winchester” in a specified text or extracting all
URLs from a piece of text. Other times you might be asked to do a more
complex search such as finding all words whose every second character is
a vowel.
Tell Me / Show Me
Regular Expressions
The use of regular expressions is based on the use of meta
characters.
The next slides list the meta characters and provide a brief
explanation of each.
Tell Me / Show Me
META Characters
Symbol Description
Tell Me / Show Me
META Characters (continued)
Symbol Description
Tell Me / Show Me
Regular Expression Examples
A simple regular expression is very similar to the wildcard
searches you are already familiar with. Let‟s take a look at an
example: let‟s look for the letter „a‟ followed by the letter „c‟.
Tell Me / Show Me
Regular Expression Examples (continued)
The strings in red would match the search string „a.c‟
The other examples fail either due to them being the wrong
character in the wrong place or in the wrong case (uppercase not
lowercase as specified in the search string).
Tell Me / Show Me
Regular Expression Examples (continued)
Assume you were asked to list all employees with a first name of
Stephen or Steven. If you used standard Oracle wildcard searching,
this would be hard to achieve, but with regular expressions, you could
simply specify '^Ste(v|ph)en$„.
“^” specifies the start of the string that is being searched
Uppercase “S”
lowercase “t”
lowercase “e”
“(“ starts a group
lowercase “v”
“|” specifies an OR
lowercase “p”
Lowercase “h”
“)” finishes the group of choices,
lowercase “e”
lowercase “n”
“$” specifies the end of the string that is being searched
Tell Me / Show Me
Regular Expression Functions
Oracle provides a set of SQL functions that you can use to search and
manipulate strings using regular expressions. You can use these
functions on any data type that holds character data such as CHAR,
CLOB and VARCHAR2. A regular expression must be enclosed in
single quotation marks.
Name Description
REGEXP_LIKE Similar to the LIKE operator, but performs regular
expression matching instead of simple pattern matching
Tell Me / Show Me
Regular Expression Function Examples
Use of the regular expression REGEXP_LIKE could be
used to solve the problem of listing either Steven or
Stephen:
SELECT first_name, last_name
FROM employees
WHERE REGEXP_LIKE (first_name, '^Ste(v|ph)en$');
Tell Me / Show Me
Regular Expression Function Examples (continued)
Searching for addresses that don‟t start with a number and
listing the position of the first non-alpha character in that
address could be done like this:
SELECT street_address,
REGEXP_INSTR(street_address,'[^[:alpha:]]')
FROM locations
WHERE REGEXP_INSTR(street_address,'[^[:alpha:]]')> 1;
Tell Me / Show Me
Regular Expression Function Examples (continued)
REGEXP_INSTR(street_address,'[^[:alpha:]]')
Tell Me / Show Me
Regular Expression Function Examples (continued)
To return only the first word in a column containing a sentence you
could issue following statement:
Tell Me / Show Me
Regular Expression Function Examples (continued)
REGEXP_SUBSTR(street_address , ' [^ ]+ ')
“[“ specifies the start of the expression
“^” indicates NOT
“ “ indicates a space
“]” ends the expression
“+” indicates one or more
“ “ indicates a space
Tell Me / Show Me
Regular Expression Function Examples (continued)
Regular expressions could also be used as part of the application
code to ensure that only valid data is stored in the database. It is
possible to include a call to a regular expression function in, for
instance, a CHECK constraint. So if you want to ensure that no
email addresses without „@‟ were captured in a table in your
database, you could simply add the following check constraint:
This would ensure that all email addresses include an “@” sign.
Tell Me / Show Me
Regular Expressions in Check Constraints
This constraint will ensure that all phone numbers are in the
format of (XXX) XXX-XXXX.
Tell Me / Show Me
Regular Expressions in Check Constraints (continued)
Tell Me / Show Me
Regular Expressions in Check Constraints
(continued)
So the following row would work:
Tell Me / Show Me
Regular Expressions in Check Constraints (continued)
Another use of Regular expressions in a check constraint could be to
make sure a VARCHAR2 or CHAR column does not allow numbers:
Tell Me / Show Me
Regular Expressions in Check Constraints (continued)
So, the contact name „Natacha Hansen‟ would be accepted by the
database, because the number returned by regexp_instr would be 0.
Tell Me / Show Me
Subexpressions
Tell Me / Show Me
Subexpressions (continued)
A C D
B
Copyright © 2011, Oracle. All rights reserved. 23
Regular Expressions
Tell Me / Show Me
Subexpressions (continued)
Tell Me / Show Me
Subexpressions (continued)
Imagine you are working with DNA sequences, and
you have to find the offset (position from the start) of
a specific sequence, starting with gtc followed by tcac
and then aaag, in that order. This could easily be
done with the REGEXP_INSTR function, which would
return the position where a match is found.
SELECT
REGEXP_INSTR('ccacctttccctccactcagttctcacctgtaaagcgtccctccct
catccccatgcccccttaccctgcagggtagagtaggctagaaaccagagagctccaag
ctccatctgtggagaggtgccatccttgggctgcgagagaggagaatttgcccaaagctg
cctgtttgaacgatggagacatgattgcccgtaaagggtcctgtctcacaaaggagatgtc
tttcgagagtaccggttacgggttaaaaggtcatgagacttcgatcattacgatcgtggttaa
cacacatatgagtatagagacacattggccaagagttgagattgagag',
'(gtc(tcac)(aaag))',1,1,0,'i„,1) "Position"
FROM DUAL;
Tell Me / Show Me
Subexpressions (continued)
SELECT
REGEXP_INSTR('ccacctttccctccactcagttctcacctgtaaagcgtccctccctcatccccatgcccccttaccctg
cagggtagagtaggctagaaaccagagagctccaagctccatctgtggagaggtgccatccttgggctgcgagagaggag
aatttgcccaaagctgcctgtttgaacgatggagacatgattgcccgtaaagggtcctgtctcacaaaggagatgtctttcgag
agtaccggttacgggttaaaaggtcatgagacttcgatcattacgatcgtggttaacacacatatgagtatagagacacattgg
ccaagagttgagattgagag', -- The string you are searching in
'(gtc(tcac)(aaag))', -- The subexpressions, here we have 3
1, -- Start position of search
1, -- Identifies occurrence of pattern you are
searching for. 1 means First occurrence
0, -- Return option. The position of the character following
the occurrence is returned. 0 is position of match and 1 means
the character position after the occurrence is returned.
'i„, -- Case insensitive or not
0) "Position“ -- Which subexpression you want returned, 1, 2 or 3
would be valid values in this example, as we have 3
subexpressions
FROM DUAL;
Tell Me / Show Me
REGEXP_COUNT
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
REGULAR EXPRESSIONS
Subexpressions
Summary
Objectives Summarized
In this lesson you have learned to:
• Describe regular expressions
• Use regular expressions to search, match, and replace
strings in SQL statements
• Construct and execute regular expressions and check
constraints
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
In this lesson you will learn how the process of changing data is
managed and how changes to a database are committed or
cancelled.
Tell Me / Show Me
Transactions
Transactions are a fundamental concept of all database systems.
Transactions allow users to make changes to data then decide whether to
save or discard the work.
Database transactions bundle multiple steps into one logical unit of work.
A transaction consists of one of the following:
Tell Me / Show Me
Transaction Analogy
A bank database contains balances for various customer accounts, as
well as total deposit balances for other branches. Suppose a customer
wants to withdraw and transfer money from their account and deposit it
into another customer’s account at a different branch.
Tell Me / Show Me
Controlling Transactions
Transactions are controlled using the following statements:
COMMIT: Represents the point in time where the user has made all the
changes he or she wants to have logically grouped together, and
because no mistakes have been made, the user is ready to save the
work. When a COMMIT statement is issued, the current transaction ends
making all pending changes permanent.
ROLLBACK: Enables the user to discard changes made to the
database. When a ROLLBACK statement is issued, all pending changes
are discarded.
SAVEPOINT: Creates a marker in a transaction, which divides the
transaction into smaller pieces.
ROLLBACK TO SAVEPOINT: Allows the user to roll back the current
transaction to a specified a savepoint. If an error was made, the user can
issue a ROLLBACK TO SAVEPOINT statement discarding only those
changes made after the SAVEPOINT was established.
Tell Me / Show Me
Transaction Example
In the example shown, the user has issued an UPDATE statement
and immediately created SAVEPOINT one. After an INSERT
statement and an UPDATE statement, the user realized that a
WHERE clause was not included in the last UPDATE. To remedy
the mistake, the user issued a ROLLBACK TO SAVEPOINT one.
The data is now restored to its state at SAVEPOINT one.
UPDATE d_cds
SET cd_number = 96
WHERE title = 'Graduation Songbook';
SAVEPOINT one;
INSERT INTO d_cds(cd_number, title, producer, year)
VALUES(100, 'Go For It', 'The Music Man', 2004) );
UPDATE d_cds
SET cd_number = 101;
ROLLBACK TO SAVEPOINT one;
COMMIT;
Tell Me / Show Me
When Does a Transaction Start or End?
A transaction begins with the first DML (INSERT,
UPDATE, DELETE or MERGE) statement.
A transaction ends when one of the following occurs:
• A COMMIT or ROLLBACK statement is issued
• A DDL(CREATE, ALTER, DROP, RENAME or
TRUNCATE) statement is issued
• A DCL(GRANT or REVOKE) statement is issued
• The user exits iSQL*Plus or SQL*Plus
• A machine fails or the system crashes
After one transaction ends, the next executable SQL statement automatically
starts the next transaction. A DDL statement or a DCL statement is
automatically committed and therefore implicitly ends a transaction. Every
data change made during a transaction is temporary until the transaction is
committed.
Tell Me / Show Me
Data Consistency
Imagine spending several hours making changes
to employee data only to find out that someone else was entering information that
conflicted with your changes!
To prevent such disruptions or conflicts and to allow multiple users to access the
database at the same time, database systems employ an automatic
implementation called "read consistency."
Read consistency guarantees a consistent view of the data by all users at all
times. Readers do not view data that is in the process of being changed. Writers
are ensured that the changes to the database are done in a consistent way.
Changes made by one writer do not destroy or conflict with changes another
writer is making.
Tell Me / Show Me
Read Consistency
Read consistency is an automatic implementation.
A partial copy of the database is kept in undo segments. When
User A issues an insert, update or delete operation to the
database, the Oracle server takes a snapshot (copy) of the data
before it is changed and writes it to an undo (rollback) segment.
User B still sees the database as it existed before the changes
started; s/he views the undo segment’s snapshot of the data.
Before changes are committed to the database, only the user who
is changing the data sees the changes; everyone else sees the
snapshot in the undo segment. This guarantees that readers of the
data see consistent data that is not currently undergoing change.
Tell Me / Show Me
Changes Visible
When a DML statement is committed, the change made to the
database becomes visible to anyone executing a SELECT
statement.
Tell Me / Show Me
COMMIT, ROLLBACK and SAVEPOINT
COMMIT and ROLLBACK ensure data consistency, making it
possible to preview data changes before making changes
permanent and a way to group logically related operations.
Tell Me / Show Me
COMMIT, ROLLBACK and
SAVEPOINT (Continued) Controlling Transactions
In the transaction shown in
Time COMMIT
the graphic, a DELETE
Transaction
statement was issued and
then SAVEPOINT A was DELETE
Tell Me / Show Me
COMMIT, ROLLBACK and
SAVEPOINT (Continued)
Controlling Transactions
In the example, following
SAVEPOINT A, the user issues Time COMMIT
Tell Me / Show Me
COMMIT, ROLLBACK and
SAVEPOINT (Continued) Controlling Transactions
Adding other SAVEPOINTS
Time COMMIT
creates additional markers
Transaction
for rollback points. If a user
DELETE
issues a ROLLBACK without
a ROLLBACK TO SAVEPOINT A
ROLLBACK ROLLBACK
To SAVEPOINT B To SAVEPOINT A ROLLBACK
Tell Me / Show Me
Implicit Transaction Processing
Automatic commit of data changes occurs under the following
circumstances:
Tell Me / Show Me
Locking
It is important to prevent data from being changed by more than
one user at a time. Oracle uses locks that prevent destructive
interaction between transactions accessing the same resource,
either a user object (such as tables or rows) or a system object not
visible to users (such as shared data structures and data dictionary
rows).
Tell Me / Show Me
How the Oracle Database Locks Data
Oracle locking is performed automatically and requires no user
action. Implicit locking occurs for SQL statements as necessary,
depending on the action requested. Implicit locking occurs for all
SQL statements except SELECT.
The users can also lock data manually, which is called explicit
locking.
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
Transaction
Commit
Savepoint
Rollback
Read consistency
Locks
Summary
Objectives Summarized
In this lesson you have learned to:
• Define the terms COMMIT, ROLLBACK, and
SAVEPOINT as they relate to data transactions
• List three advantages of the COMMIT, ROLLBACK,
and SAVEPOINT statements
• Explain why it is important, from a business
perspective, to be able to control the flow of
transaction processing
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
Join Commands
The two sets of commands or syntax which can be used to
make connections between tables in a database:
Tell Me / Show Me
ORACLE Proprietary Joins
To query data from more than one table using the Oracle proprietary
syntax, use a join condition in the WHERE clause.
Tell Me / Show Me
ORACLE Proprietary Joins (continued)
Imagine the problem arising from having two students in the same class
with the same last name. When needing to speak to "Jackson," the teacher
clarifies which "Jackson" by prefacing the last name with the first name. To
make it easier to read a Join statement and to speed up database access,
it is good practice to preface the column name with the table name. This is
called "qualifying your columns." The combination of table name and
column name helps eliminate ambiguous names when two tables contain a
column with the same column name. Note: When the same column name
appears in both tables, the column name must be prefaced with the name
of the table.
Tell Me / Show Me
Join Syntax Example SELECT d_play_list_items.event_id,
In the example at right, d_play_list_items.song_id,
which two tables are d_track_listings.cd_number
being joined? Which FROM d_play_list_items,
identical columns do d_track_listings
these tables share? WHERE d_play_list_items.song_id =
d_track_listings.song_id;
Tell Me / Show Me
EQUIJOIN SELECT d_play_list_items.song_id,
d_play_list_items.event_id,
Sometimes called a "simple" or "inner"
d_track_listings.cd_number
join, an equijoin is a table join that FROM d_play_list_items,
combines rows that have the same d_track_listings
values for the specified columns. In the WHERE d_play_list_items.song_id =
example shown, the what, where and d_track_listings.song_id;
Tell Me / Show Me
Cartesian Product Join
If two tables in a join query have no join condition specified in the
WHERE clause or the join condition is invalid, the Oracle Server
returns the Cartesian product of the two tables. This is a
combination of each row of one table with each row of the other. A
Cartesian product always generates many rows and is rarely
useful. For example, the Cartesian product of two tables, each with
100 rows, has 10,000 rows! This may not be what you were trying
to retrieve.
Tell Me / Show Me
Generating a Cartesian Product
Cartesian
product:
20x8=160 rows
Tell Me / Show Me
Restricting Rows In a Join
As with single-table queries, the WHERE clause
can be used to restrict the rows considered in
one or more tables of the join. The query shown
uses the AND operator to restrict the rows
returned. Compare this result with the previous
query.
SONG_ID EVENT_ID CD_NUMBER
45 100 92
SELECT d_play_list_items.song_id,
46 100 93
47 100 91
d_play_list_items.event_id,
d_track_listings.cd_number
FROM d_play_list_items,
d_track_listings
WHERE d_play_list_items.song_id =
d_track_listings.song_id
AND d_play_list_items.event_id <
105;
Copyright © 2011, Oracle. All rights reserved. 11
Cartesian Product and the Join Operations
Tell Me / Show Me
Aliases
Working with lengthy column and table names can be TRACK PLAYLIST
45 45
cumbersome. Fortunately, there is a way to shorten the
syntax using aliases. To distinguish columns that have 46 46
identical names but reside in different tables, use 47 47
column aliases. Column aliases were used in the query
below. When there are no shared column names
between two tables, there is no need to add the table
name to it.
Tell Me / Show Me
Table Alias
Another way to make statements easier to read is to use
table aliases. A table alias is just like a column alias, as in,
it renames an object within a statement. It is created by
entering the new name for the table just after the table
name in the from-clause. However, if a table alias is used in
the FROM clause, then that table alias must be substituted
for the table name throughout the SELECT statement.
Tell Me / Show Me
Terminology
Key terms used in this lesson include:
Alias
Cartesian product
Equijoin
Joint conditions
Proprietary join
Summary
Objectives Summarized
In this lesson you have learned to:
• Name the Oracle proprietary joins and their
ANSI/ISO SQL: 1999 counterparts
• Describe the purpose of join conditions
• Construct and execute a SELECT statement that
results in a Cartesian product
• Construct and execute SELECT statements to
access data from more than one table using an
equijoin
• Construct and execute SELECT statements that add
search conditions using the AND operator
• Apply the rule for using column aliases in a join
statement
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course outline in Section 0ne.
Tell Me / Show Me
Nonequijoin
Example:
A company pays its employees who earn 00-15 Logged = 15 Paid
an hourly wage in 15-minute increments. 16-30 Logged = 30 Paid
One table stores the hours and minutes 31-45 Logged = 45 Paid
recorded by a time clock and another 46-60 Logged = 60 Paid
table stores the pay range. If the minutes
worked is between 0 and 15, the worker is
paid for 15 minutes. If the minutes worked
is between 16 and 30, the worker is paid
for 30 minutes. If the minutes worked is
between 31 and 45, the worker is paid for
45 minutes. If the minutes worked is
between 46 and 60, the worker is paid for
1 hour
Tell Me / Show Me
Nonequijoin (continued)
Tell Me / Show Me
D_EVENTS
ID NAME EVENT_DATE DESCRIPTION COST VENUE_ID PACKAGE_ THEME_ CLIENT_
CODE CODE NUMBE
R
100 Peters 14-MAY-04 Party for 200 8000 100 112 200 5922
Graduation
100 Vigils 28-APR-04 Black tie, Four 10000 220 200 200 6133
Wedding Seasons
Summary
Objective Summarized
In this lesson you have learned to:
• Construct and execute a SELECT statement to
access data from more than one table using a
nonequijoin
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
Outer Join
An outer join is used to see rows that have a corresponding value in another
table plus those rows in one of the tables that have no matching value in the
other table. To indicate which table may have missing data, use a plus sign
(+) after the table's column name in the WHERE clause of the query.
Note that an outer join cannot use the IN operator or be linked to another
condition by the OR operator.
EMPLOYEE_ID LAST_NAME DEPARTMENT_ID DEPARTMENT_ID DEPARTMENT_NAME
100 King 90 90 Executive
101 Kochhar 90 110 Accounting
102 De Haan 90 190 Contracting
178 Grant 210 Human Resources
DEPARTMENT_ID LAST_NAME
20 Hartstein
20 Fay
110 Higgins
110 Gietz
Grant
Tell Me / Show Me
Join With Plus Sign EMPLOYEE_ID LAST_NAME DEPARTMENT_ID
100 King 90
The query below uses the plus 101 Kochhar 90
sign to indicate the table whose 102 De Haan 90
column is missing data. The 178 Grant
variations of the outer join are
shown.
DEPARTMENT_ID DEPARTMENT_NAME
90 Executive
SELECT table1.column, 110 Accounting
table2.column 190 Contracting
FROM table1, table2 210 Human Resources
***
SELECT d.department_id, e.last_name
WHERE table1.column(+) =
FROM employees e, departments d
table2.column;
WHERE e.department_id = d.department_id (+);
***
WHERE table1.column = DEPARTMENT_ID LAST_NAME
table2.column(+); 20 Hartstein
*** 20 Fay
110 Higgins
NEVER table1.column(+) = 110 Gietz
table2.column(+); Grant
Summary
Objective Summarized
In this lesson you have learned to:
• Create and execute a SELECT statement to access data
from more than one table using an outer join
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
Unit Testing
If two things are tested at once and the test fails, it is
difficult or impossible to work out what has caused the
failure. So it is important to test only one thing at a time.
This is commonly referred to as unit testing.
Tell Me / Show Me
What Could Be Tested?
When testing a database there is a range of different things
that need to be tested.
• Columns should be tested that they contain the correct
data type.
• Columns should be tested that they can accommodate
the largest amount of data that might be entered.
• Constraints should be checked that they only constrain
or limit data that they are supposed and not more or
less data.
Tell Me / Show Me
What Should Be Tested?
It is frequently unrealistic to test every column and every
constraint in every table in a database if it is a large
database. A random spread of tests, that check some
columns and some constraints, should be carried out.
Tell Me / Show Me
Designing Tests
Before you carry out a test you should
have a good idea of what result you
expect to see if the database is working
as expected. This should be documented
before you carry out the test in a table
similar to the one shown:
Test Date Test Description Input Expected Output Result/Discre Action
Number pancy
22 19/07/06 Confirm NOT NULL INSERT
constraint on INTO jobs
JOB_TITLE in JOBS (job_id,
table job_title,
min_salary,
max_salary)
VALUES
(222,NULL,1
00,200)
Tell Me / Show Me
Running Tests
Once you have designed your test, you can
run it and record your results:
Summary
Practice Guide
The link for the lesson practice guide can be found in the
course resources in Section 0.
Tell Me / Show Me
Scope of the Final Project
The Final Project consists of the following
steps:
Tell Me / Show Me
Evaluation of the Final Project
Each group will present their database to the class. Your
group will be evaluated according the Final Project Rubric.
Make sure that you read it carefully and understand how
you will be assessed.
Summary
Objective Summarized
In this lesson, you have learned to:
• Apply SQL concepts to create a functional database
appropriate for a small business
Problem:
Tables Used:
user_constraints,
user_cons_columns
Problem:
Add a foreign constraint between DEPT and
EMP so that only valid departments can be
entered in the EMP table, but make sure you
can delete any row from the DEPT table.
Problem:
Produce a report that returns the
last name, salary, department
number and average salary of all
the departments where salary is
greater than the average salary.
Tables Used:
Employees, Departments
Problem:
Create a view named V2 that returns the
highest salary, lowest salary, average salary
and department name.
Tables Used:
emp, dept
Problem:
Create a view named Dept_Managers_view that
returns a listing of department names along with
the manager initial and surname for that
department.
Tables Used:
Employees, departments
Problem:
The following statement contains errors.
Fix them and run the code to get the displayed result.
Statement:
DROP V3 views;
Problem:
Create a sequence named ct_seq with all
the default values. Run the statements
and fix the error. Correct the statement to
return the subsequent number.
Code:
CREATE SEQUENCE ct_seq;
SELECT ct_seq.currval
FROM dual;
Problem:
Look at the insert statement and fix the error.
Code:
INSERT emp
(employee_id,first_name,last_name,email,phone_number,
hire_date,job_id,salary,commission_pct,manager_id,department_id)
VALUS
(currval.ct_seq,'Kaare‟,'Hansen‟,'KHANSEN‟,'44965 832123‟,sysdate
,'Manager‟,6500,null,100,10)
Problem:
Fix the error in the SQL statement to create the index as
shown in the screenshot.
Code:
CREATE INX emp indx FOR TABLE emp(employee_id
DESC, UPPR(SUBST(firstname,1.1 ||” “||astname)
Problem:
Write the SQL statement to list all
the user tables which contains the
name PRIV.
Tables Used:
dictionary
Problem:
Give select access to public on the EMP
table, and verify the grant by running this
query. The query contains errors that you
must fix before you can run the select
statement.
Code:
GRANT SELECT ON emp TO PUBLIC
SELECT *
FROM usr_tab_privs
WHERE tablename = “emp”
Problem:
Complete the follwoing query using
regular expressions to return only the
numbers from the following string:
'Oracle Academy9547d6905%&^ db
apex'.
Statement:
SELECT REGEXP_REPLACE('Oracle
Academy9547d6905%&^ db apex‟
YOUR CODE HERE) regexpreplace
FROM DUAL
Copyright © 2011, Oracle. All rights reserved. 19
Ensuring Quality Query Results - Advanced
Techniques
Tell Me / Show Me
Write the Code
Problem:
Amend the previous query using
regular expressions to return the
number of digits from the following
string: 'Oracle
Academy9547d6905%&^ db‟
Statement:
SELECT REGEXP_REPLACE('Oracle
Academy9547d6905%&^ db apex‟
YOUR CODE HERE) regexpreplace
FROM DUAL
Copyright © 2011, Oracle. All rights reserved. 20
Ensuring Quality Query Results - Advanced
Techniques
Tell Me / Show Me
Write the Code
Problem:
Amend the query again to return only the non-numeric
characters.
Statement:
SELECT REGEXP_REPLACE('Oracle
Academy9547d6905%&^ db apex‟ YOUR CODE HERE)
regexpreplace
FROM DUAL
Problem:
Using Oracle proprietary joins,
construct a statement that returns
all the employee_id‟s joined to all
the department_names.
Tables Used:
Employees, departments
Problem:
Still using Oracle Joins, correct the
previous statement so that it returns
only the name of the department
that the employee actually works in.
Tables Used:
Employees, departments
Problem:
Still using Oracle Joins, construct
a query that lists the employees
last name, the department name,
the salary and the country name of
all employees.
Tables Used:
Employees, departments,
locations and countries
Problem:
Still using Oracle join syntax, alter
the previous query so that it also
includes the employee record of
the employee with no
department_id, „Grant‟.
Tables Used:
Employees, departments,
locations and countries