Tải bản đầy đủ (.pdf) (50 trang)

Tài liệu OCA: Oracle Database 11g Administrator Certified Associate- P5 ppt

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (633.44 KB, 50 trang )

Using Other Single-Row Functions

131
Parameter Description
BG_JOB_ID
Returns the job ID (that is,
DBA_JOBS
) if the session was created
by a background process. Returns
NULL
if the session is a fore-
ground session. See also
FG_JOB_ID
.
CLIENT_IDENTIFIER
Returns the client session identifier in the global context. It can
be set with the
DBMS_SESSION
built-in package.
CLIENT_INFO
Returns the 64 bytes of user session information stored by
DBMS_APPLICATION_INFO
.
CURRENT_BIND
Returns bind variables for fine-grained auditing.
CURRENT_SCHEMA
Returns the current schema as set by
ALTER SESSION SET
CURRENT_SCHEMA
or, by default, the login schema/ID.
CURRENT_SCHEMAID


Returns the numeric ID for
CURRENT_SCHEMA
.
CURRENT_SQL
Returns the SQL that triggered fine-grained auditing (use only
within scope inside the event handler for fine-grained auditing).
CURRENT_SQL_LENGTH
Returns the length of the current SQL that triggered fine-
grained auditing.
DB_DOMAIN
Returns the contents of the
DB_DOMAIN

init.ora
parameter.
DB_NAME
Returns the contents of the
DB_NAME

init.ora
parameter.
DB_UNIQUE_NAME
Returns the contents of the
DB_UNIQUE_NAME

init.ora

parameter.
ENTRYID
Returns the auditing entry identifier

ENTERPRISE_IDENTITY
Returns OID DN for enterprise users, for local users NULL.
FG_JOB_ID
Returns the job ID of the current session if a foreground pro-
cess created it. Returns
NULL
if the session is a background
session. See also
BG_JOB_ID
.
GLOBAL_CONTEXT_MEMORY
Returns the number in the SGA by the globally accessible
context.
GLOBAL_UID
Returns the global user ID from OID.
HOST
Returns the hostname of the machine from where the client
connected. This is not the same terminal in
V$SESSION
.
table 2.14 Parameters in the
USERENV
Namespace (continued)
95127c02.indd 131 2/18/09 6:46:45 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
132

Chapter 2
N
Using Single-Row Functions

Parameter Description
IDENTIFICATION_TYPE
Returns how the user is set to authenticate in the database:
LOCAL
,
EXTERNAL
, or
GLOBAL.
INSTANCE
Returns the instance number for the instance to which the
session is connected. This is always
1
unless you are running
Oracle Real Application Clusters.
INSTANCE_NAME
Returns the name of the instance.
IP_ADDRESS
Returns the IP address of the machine from where the client
connected.
ISDBA
Returns
TRUE
if the user connected
AS SYSDBA
.
LANG
Returns the ISO abbreviation for the language name.
LANGUAGE
Returns a character string containing the language and terri-
tory used by the session and the database character set in the

form
language_territory.characterset.
MODULE
Returns the application name set through
DBMS_APPLICATION_INFO
.
NETWORK_PROTOCOL
Returns the network protocol being used as specified in the
PROTOCOL=
section of the connect string or
tnsnames.ora

definition.
NLS_CALENDAR
Returns the calendar for the current session.
NLS_CURRENCY
Returns the currency for the current session.
NLS_DATE_FORMAT
Returns the date format for the current session.
NLS_DATE_LANGUAGE
Returns the language used for displaying dates.
NLS_SORT
Returns the binary or linguistic sort basis.
NLS_TERRITORY
Returns the territory for the current session.
OS_USER
Returns the operating-system username for the current session.
POLICY_INVOKER
Returns the invoker of row-level security-policy functions.
PROXY_ENTERPRISE_

IDENTITY
Returns OID DN when the proxy user is an enterprise user.
table 2.14 Parameters in the
USERENV
Namespace (continued)
95127c02.indd 132 2/18/09 6:46:45 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Using Other Single-Row Functions

133
Parameter Description
PROXY_GOLBAL_UID
Returns the global user ID from OID for Enterprise User Secu-
rity proxy users.
PROXY_USER
Returns the name of the database user who opened the current
session for the session user.
PROXY_USERID
Returns the numeric ID for the database user who opened the
current session for the session user.
SERVER_HOST
Returns the hostname of the machine where the instance is
running.
SERVICE_NAME
Returns the name of the service where the session is connected.
SESSION_USER
Returns the database username for the current session.
SESSION_USERID
Returns the numeric database user ID for the current session.
SESSIONID

Returns the auditing session identifier AUDSID. This parameter
is out of scope for distributed queries.
SID
Returns the session number (same as the SID from
V$SESSION
).
STATEMENT_ID
Returns the auditing statement identifier.
TERMINAL
Returns the terminal identifier for the current session. This is
the same as the terminal in
V$SESSION
.
Here are few more examples of
SYS_CONTEXT
in the
USERENV
namespace:
SELECT SYS_CONTEXT(‘USERENV’, ‘OS_USER’),
SYS_CONTEXT(‘USERENV’, ‘CURRENT_SCHEMA’),
SYS_CONTEXT(‘USERENV’, ‘HOST’),
SYS_CONTEXT(‘USERENV’, ‘NLS_TERRITORY’)
FROM dual;
SYS_CONTEXT(‘USERENV’,’OS_USER’)
SYS_CONTEXT(‘USERENV’,’CURRENT_SCHEMA’)
SYS_CONTEXT(‘USERENV’,’HOST’)
SYS_CONTEXT(‘USERENV’,’NLS_TERRITORY’)
--------------------------------------------
table 2.14 Parameters in the
USERENV

Namespace (continued)
95127c02.indd 133 2/18/09 6:46:45 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
134

Chapter 2
N
Using Single-Row Functions
oracle
HR
linux04.mycompany.corp
AMERICA
SYS_GUID
SYS_GUID()
generates a globally unique identifier as a RAW value. This function is useful
for creating a unique identifier to identify a row.
SYS_GUID()
returns a 32-bit hexadecimal
representation of the 16-byte RAW value.
SELECT SYS_GUID() FROM DUAL;
SYS_GUID()
--------------------------------
CDA78A020D6E43A6AB743A5CE8CB8C55
SELECT SYS_GUID() FROM DUAL;
SYS_GUID()
--------------------------------
DC7C19A3AD264CE184C64194E65F83E5
UID
UID
takes no parameters and returns the integer user ID for the current user connected to

the session. The user ID uniquely identifies each user in a database and can be selected from
the
DBA_USERS
view.
SQL> SHOW USER
USER is “BTHOMAS”
SELECT username, account_status
FROM dba_users
WHERE user_id = UID;
USERNAME ACCOUNT_STATUS
---------------- ---------------
BTHOMAS OPEN
95127c02.indd 134 2/18/09 6:46:45 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Using Other Single-Row Functions

135
USER
USER
takes no parameters and returns a character string containing the username for the
current user.
SELECT default_tablespace, temporary_tablespace
FROM dba_users
WHERE username = USER;
DEFAULT_TABLESPACE TEMPORARY_TABLESPACE
------------------------------ ---------------------
USERS TEMP
USERENV
USERENV
(

opt
) takes a single argument, where
opt
is one of the following options:
ISDBA
ÛN
returns
TRUE
if the
SYSDBA
role is enabled in the current session.
SESSIONID
ÛN
returns the
AUDSID
auditing session identifier.
ENTRYID
ÛN
returns the auditing entry identifier if auditing is enabled for the instance (the
init.ora
parameter
AUDIT_TRAIL
is set to
TRUE
).
INSTANCE
ÛN
returns the instance identifier to which the session is connected. This option
is useful only if you are running the Oracle Parallel Server and have multiple instances.
LANGUAGE

ÛN
returns the language, territory, and database character set. The delimiters are
an underscore (
_
) between language and territory and a period (
.
) between the terri-
tory and character set.
LANG
ÛN
returns the ISO abbreviation of the session’s language.
TERMINAL
ÛN
returns a VARCHAR2 string containing information corresponding to the
operating system identifier for the current session’s terminal.
The option can appear in uppercase, lowercase, or mixed case. The
USERENV
function
has been deprecated since Oracle 9i. It is recommended to use the
SYS_CONTEXT
function
with the built-in
USERENV
namespace instead.
VSIZE
VSIZE(x)
takes a single argument, where
x
is an expression. This function returns the size
in bytes of the internal representation of the

x
.
SELECT last_name, first_name,
VSIZE(last_name) ln_size, VSIZE(first_name) fn_size
FROM employees
WHERE last_name like ‘K%’;
95127c02.indd 135 2/18/09 6:46:45 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
136


LAST_NAME FIRST_NAME LN_SIZE FN_SIZE
------------ -------------------- ---------- ----------
Kaufling Payam 8 5
Khoo Alexander 4 9
King Janette 4 7
King Steven 4 6
Kochhar Neena 7 5
Kumar Sundita 5 7
Since the database character set is single-byte, the byte used for each character is
1
;
hence, the size shown here is actually the number of characters in the input. For multibyte
characters, this would be different.
Summary
This chapter introduced single-row functions. It started by discussing the functions avail-
able in Oracle 11g to handle
NULL
s. Then it discussed the single-row functions available in
Oracle 11g by grouping them into character, numeric, date, and conversion functions.

You learned that single-row functions return a value for each row as it is retrieved from
the table. You can use single-row functions to interpret
NULL
values, format output, convert
datatypes, transform data, perform date arithmetic, give environment information, and
perform trigonometric calculations.
You can use single-row functions in the
SELECT
,
WHERE
, and
ORDER BY
clauses of
SELECT

statements. I covered the rich assortment of functions available in each datatype category
and some functions that work on any datatype.
The
NVL
,
NVL2
, and
COALESCE
functions interpret
NULL
values.
The single-row character functions operate on character input. The
INSTR
function returns
the position of a substring within the string. The

SUBSTR
function returns a portion of
the string.
INSTR
and
SUBSTR
are great for extracting part of the input string.
REPLACE

and
TRANSLATE
transform the input.
Single-row numeric functions operate on numeric input.
FLOOR
,
CEIL
,
ROUND
, and
TRUNC

get the nearest number.
FLOOR
,
CEIL
, and
ROUND
return the nearest integer, whereas
ROUND


returns a value rounded to certain digits of precision.
REMAINDER
and
MOD
are similar
functions.
Date functions operate on datetime values.
SYSDATE
and
SYSTIMESTAMP
values return the
current date and time.
MONTHS_BETWEEN
finds the number of months between two date val-
ues.
ADD_MONTHS
is a commonly used function and can add months to or subtract months
from a date. You can use
ROUND
and
TRUNC
on datetime values to find the nearest date,
month, or year.
Of the conversion functions,
TO_CHAR
and
TO_DATE
are the most commonly used. I also
reviewed the format codes that can be used with numeric and datetime values.
The

DECODE
function evaluates a condition, and you can easily build
IF…THEN…ELSE
logic
into SQL using the
DECODE
function.
95127c02.indd 136 2/18/09 6:46:45 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.


137
Exam Essentials
Understand where single-row functions can be used. Single-row functions can be used in
the
SELECT
,
WHERE
, and
ORDER BY
clauses of
SELECT
statements.
Know the effects that
NULL
values can have on arithmetic and other functions. Any arith-
metic operation on a
NULL
results in a
NULL

. This is true of most functions as well. Use the
NVL
,
NVL2
, and
COALESCE
functions to deal with
NULL
s.
Review the character-manipulation functions. Understand the arguments and the result
of using character-manipulation functions such as
INSTR
,
SUBSTR
,
REPLACE
, and
TRANSLATE
.
Understand the numeric functions. Know the effects of using
TRUNC
and
ROUND
with
-n
as
the second argument. Also practice using
LENGTH
and
INSTR

, which return a numeric result,
inside
SUBSTR
and other character functions.
Know how date arithmetic works. When adding or subtracting numeric values from a
DATE datatype, whole numbers represent days. Also, the date/time intervals
INTERVAL
YEAR TO MONTH
and
INTERVAL DAY TO SECOND
can be added or subtracted from date/time
datatypes. You need to know how to interpret and create expressions that add intervals to
or subtract intervals from dates.
Know the datatypes for the various date/time functions. Oracle has many date/time func-
tions to support the date/time datatypes. You need to know the return datatypes for these
functions.
SYSDATE
and
CURRENT_DATE
return a DATE datatype.
CURRENT_TIMESTAMP
and
SYSTIMESTAMP
return a TIMESTAMP WITH TIME ZONE datatype.
LOCALTIMESTAMP

returns a TIMESTAMP datatype.
Know the format models for converting dates to/from character strings. In practice, you
can simply look up format codes in a reference. For the certification exam, you must have
them memorized.

Understand the use of the
DECODE
function.
DECODE
acts like a case statement in C, Pascal,
or Ada. Learn how this function works and how to use it.
95127c02.indd 137 2/18/09 6:46:45 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
138

Review Questions
Review Questions
1. You want to display each project’s start date as the day, week, number, and year. Which
statement will give output like the following?
Tuesday Week 23, 2008
A. SELECT proj_id, TO_CHAR(start_date, ‘DOW Week WOY YYYY’) FROM projects;
B. SELECT proj_id, TO_CHAR(start_date,’Day’||’ Week’||’ WOY, YYYY’) FROM
projects;
C. SELECT proj_id, TO_CHAR(start_date, ‘Day” Week” WW, YYYY’) FROM projects;
D. SELECT proj_id, TO_CHAR(start_date, ‘Day Week# , YYYY’) FROM projects;
E. You can’t calculate week numbers with Oracle.
2. What will the following statement return?
SELECT last_name, first_name, start_date
FROM employees
WHERE hire_date < TRUNC(SYSDATE) – 5;
A. Employees hired within the past five hours
B. Employees hired within the past five days
C. Employees hired more than five hours ago
D. Employees hired more than five days ago
3. Which assertion about the following statements is most true?

SELECT name, region_code||phone_number
FROM customers;
SELECT name, CONCAT(region_code,phone_number)
FROM customers;
A. If REGION_CODE is NULL, the first statement will not include that customer’s PHONE_
NUMBER.
B. If REGION_CODE is NULL, the second statement will not include that customer’s PHONE_
NUMBER.
C. Both statements will return the same data.
D. The second statement will raise an error if REGION_CODE is NULL for any customer.
4. Which single-row function could you use to return a specific portion of a character string?
A. INSTR
B. SUBSTR
C. LPAD
D. LEAST
95127c02.indd 138 2/18/09 6:46:45 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Review Questions

139
5. The data in the PRODUCT table is as described here. The bonus amount is calculated as the
lesser of 5 percent of the base price or 20 percent of the surcharge.
sku name division base_price surcharge
1001 PROD-1001 A 200 50
1002 PROD-1002 C 250
1003 PROD-1003 C 240 20
1004 PROD-1004 A 320
1005 PROD-1005 C 225 40
Which of the following statements will achieve the desired results?
A. SELECT sku, name, LEAST(base_price * 1.05, surcharge * 1.2)

FROM products;
B. SELECT sku, name, LEAST(NVL(base_price,0) * 1.05, surcharge * 1.2)
FROM products;
C. SELECT sku, name, COALESCE(LEAST(base_price*1.05, surcharge * 1.2),
base_price * 1.05)
FROM products;
D. A, B, and C will all achieve the desired results.
E. None of these statements will achieve the desired results.
6. Which function(s) accept arguments of any datatype? (Choose all that apply.)
A. SUBSTR
B. NVL
C. ROUND
D. DECODE
E. SIGN
7. What will be returned by SIGN(ABS(NVL(-32,0)))?
A. 1
B. 32
C. –1
D. 0
E. NULL
95127c02.indd 139 2/18/09 6:46:45 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
140

Review Questions
8. The SALARY table has the following data:
LAST_NAME FIRST_NAME SALARY
------------ -------------------- ----------
Mavris Susan 6500
Higgins Shelley 12000

Tobias Sigal
Colmenares Karen 2500
Weiss Matthew 8000
Mourgos Kevin 5800
Rogers Michael 2900
Stiles Stephen 3200
Consider the following SQL, and choose the best option:
SELECT last_name, NVL2(salary, salary, 0) N1,
NVL(salary,0) N2
FROM salary;
A. Column N1 and N2 will have different results.
B. Column N1 will show zero for all rows, and column N2 will show the correct salary
values, and zero for Tobias.
C. The SQL will error out because the number of arguments in the NVL2 function is
incorrect.
D. Columns N1 and N2 will show the same result.
9. Which two functions could you use to strip leading characters from a character string?
(Choose two.)
A. LTRIM
B. SUBSTR
C. RTRIM
D. INSTR
E. STRIP
10. What is the result of MOD(x1, 4), if x1 is 11?
A. –1
B. 3
C. 1
D. REMAINDER(11,4)
95127c02.indd 140 2/18/09 6:46:45 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

Review Questions

141
11. Which two SQL statements will replace the last two characters of last_ nam e with ‘XX‘ in
the employees table when executed? (Choose two.)
A. SELECT RTRIM(last_name, SUBSTR(last_name, LENGTH(last_name)-1)) || ‘XX’
new_col FROM employees;
B. SELECT REPLACE(last_name, SUBSTR(last_name, LENGTH(last_name)-1), ‘XX’)
new_col FROM employees;
C. SELECT REPLACE(SUBSTR(last_name, LENGTH(last_name)-1), ‘XX’) new_col
FROM employees;
D. SELECT CONCAT(SUBSTR(last_name, 1,LENGTH(last_name)-2), ‘XX’) new_col
FROM employees;
12. Which date components does the CURRENT_TIMESTAMP function display?
A. Session date, session time, and session time zone offset
B. Session date and session time
C. Session date and session time zone offset
D. Session time zone offset
13. Using the SALESPERSON_REVENUE table described here, which statements will properly dis-
play the TOTAL_REVENUE (CAR_SALES + WARRANTY_SALES) of each salesperson?
Column Name salesperson_id car_sales warranty_sales
Key Type pk
NULL
s/Unique
NN NN
FK Table
Datatype NUMBER NUMBER NUMBER
Length 10 11,2 11,2
A. SELECT salesperson_id, car_sales, warranty_sales, car_sales + warranty_
sales total_sales

FROM salesperson_revenue;
B. SELECT salesperson_id, car_sales, warranty_sales, car_sales +
NVL2(warranty_sales,0) total_sales
FROM salesperson_revenue;
C. SELECT salesperson_id, car_sales, warranty_sales, NVL2(warranty_sales,
car_sales + warranty_sales, car_sales) total_sales
FROM salesperson_revenue;
D. SELECT salesperson_id, car_sales, warranty_sales, car_sales +
COALESCE(car_sales, warranty_sales, car_sales + warranty_sales) total_
sales
FROM salesperson_revenue;
95127c02.indd 141 2/18/09 6:46:46 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
142

Review Questions
14. What will be the result of executing the following SQL, if today’s date is February 28, 2009?
SELECT ADD_MONTHS(‘28-FEB-09’, -12) from dual;
A. 28-FEB-10
B. 28-FEB-08
C. 29-FEB-08
D. 28-JAN-08
15. Consider the following two SQL statements, and choose the best option:
1. SELECT TO_DATE(‘30-SEP-07’,’DD-MM-YYYY’) from dual;
2. SELECT TO_DATE(‘30-SEP-07’,’DD-MON-RRRR’) from dual;
A. Statement 1 will error; 2 will produce result.
B. The resulting date value from the two statements will be the same.
C. The resulting date value from the two statements will be different.
D. Both statements will generate an error.
16. What will the following SQL statement return?

SELECT COALESCE(NULL,’Oracle ‘,’Certified’) FROM dual;
A. NULL
B. Oracle
C. Certified
D. Oracle Certified
17. Which expression will always return the date one year later than the current date?
A. SYSDATE + 365
B. SYSDATE + TO_YMINTERVAL(‘01-00’)
C. CURRENT_DATE + 1
D. NEW_TIME(CURRENT_DATE,1,’YEAR’)
E. None of the above
18. Which function will return a TIMESTAMP WITH TIME ZONE datatype?
A. CURRENT_TIMESTAMP
B. LOCALTIMESTAMP
C. CURRENT_DATE
D. SYSDATE
95127c02.indd 142 2/18/09 6:46:46 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Review Questions

143
19. Which statement would change all occurrences of the string ‘IBM’ to the string ’SUN’ in
the DESCRIPTION column of the VENDOR table?
A. SELECT TRANSLATE(description, ‘IBM’, ‘SUN’) FROM vendor
B. SELECT CONVERT(description, ‘IBM’, ‘SUN’) FROM vendor
C. SELECT EXTRACT(description, ‘IBM’, ‘SUN’) FROM vendor
D. SELECT REPLACE(description, ‘IBM’, ‘SUN’) FROM vendor
20. Which function implements IF…THEN…ELSE logic?
A. INITCAP
B. REPLACE

C. DECODE
D. IFELSE
95127c02.indd 143 2/18/09 6:46:46 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
144

Answers to Review Questions
Answers to Review Questions
1. C. Double quotation marks must surround literal strings like ”Week”.
2. D. The TRUNC function removes the time portion of a date by default, and whole numbers
added to or subtracted from dates represent days added or subtracted from that date.
TRUNC(SYSDATE) –5 means five days ago at midnight.
3. C. The two statements are equivalent.
4. B. SUBSTR returns part of the string. INSTR returns a number. LPAD adds to a character
string. LEAST does not change an input string.
5. C. Options A and B do not account for NULL surcharges correctly and will set the bonus
to NULL where the surcharge is NULL. In option B, the NVL function is applied to the base_
price column instead of the surcharge column. In option C, the LEAST function will
return a NULL if surcharge is NULL, in which case BASE_PRICE * 1.05 would be returned
from the COALESCE function.
6. B, D. ROUND does not accept character arguments. SUBSTR accepts only character argu-
ments. SIGN accepts only numeric arguments.
7. A. The functions are evaluated from the innermost to outermost, as follows:
SIGN(ABS(NVL(-32,0))) = SIGN(ABS(-32)) = SIGN(32) = 1
8. D. The NVL function returns zero if the salary value is NULL, or else it returns the original
value. The NVL2 function returns the second argument if the salary value is not NULL. If
NULL, the third argument is returned.
9. A, B. RTRIM removes trailing (not leading) characters. INSTR returns a number. STRIP is not
a valid Oracle function. SUBSTR with second argument greater than 1 removes leading char-
acters from a string.

10. B. MOD returns the number remainder after division. The REMAINDER function is similar to
MOD but will use the ROUND function in the algorithm; hence, the result of REMAINDER(11,4)
would be –1. MOD uses FLOOR in the algorithm.
11. A, D. The SUBSTR function in option A would return the last two characters of the last
name. These two characters are right-trimmed using the RTRIM function. The result would
be the first portion of the last name and is concatenated to ‘XX’. Option B also would do
the same as A, but would replace all the occurrences of the last two characters (Paululul
will be PaXXXXXX instead of PaululXX). Option C would return only the last two characters
of the last name. The SUBSTR function in option D would return the first character through
the last –2 characters. ‘XX‘ is concatenated to the result.
12. A. The CURRENT_TIMESTAMP function returns the session date, session time, and session
time zone offset. The return datatype is TIMESTAMP WITH TIME ZONE.
95127c02.indd 144 2/18/09 6:46:46 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Answers to Review Questions

145
13. C. Option A will result in NULL TOTAL_SALES for rows where there are NULL WARRANTY_
SALES. Option B is not the correct syntax for NVL2, because it requires three arguments.
With option C, if WARRANTY_SALES is NULL, then CAR_SALES is returned; otherwise, CAR_
SALES+WARRANTY_SALES is returned. The COALESCE function returns the first non-NULL
argument and could be used to obtain the desired results, but the first argument here is
CAR_SALES, which is not NULL, and therefore COALESCE will always return CAR_SALES.
14. C. The ADD_MONTHS function returns the date d plus i months. If <d> is the last day of the month
or the resulting month has fewer days, then the result is the last day of the resulting
month.
15. C. Statement 1 will result in 30-SEP-0007, and statement 2 will result in 30-SEP-2007.
The RR and RRRR formats derive the century based on the current date if the century is not
specified. The YY format will use the current century, and the YYYY format expects the cen-
tury in the input.

16. B. The COALESCE function returns the first non-NULL parameter, which is the character
string ‘Oracle ‘.
17. E. Option A will not work if there is a February 29 (leap year) in the next 365 days. Option
B will always add one year to the present date, except if the current date is February 29
(leap year). Option C will return the date one day later. NEW_TIME is used to return the
date/time in a different time zone. ADD_MONTHS (SYSDATE,12) can be used to achieve the
desired result.
18. A. LOCALTIMESTAMP does not return the time zone. CURRENT_DATE and SYSDATE return nei-
ther fractional seconds nor a time zone; they both return the DATE datatype.
19. D. CONVERT is used to change from one character set to another. EXTRACT works on date/
time datatypes. TRANSLATE changes all occurrences of each character with a positionally
corresponding character, so ‘I like IBM’ would become ‘S like SUN’.
20. C. The INITCAP function capitalizes the first letter in each word. The REPLACE function
performs search-and-replace string operations. There is no IFELSE function. The DECODE
function is the one that implements IF…THEN…ELSE logic.
95127c02.indd 145 2/18/09 6:46:46 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
95127c02.indd 146 2/18/09 6:46:46 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Chapter
3
Using Group
Functions
ORACLE DATABASE 11g:
SQL FUNDAMENTALS I EXAM OBJECTIVES
COVERED IN THIS CHAPTER:
Reporting Aggregated Data Using the Group Functions
Identify the available group functions

Describe the use of group functions


Group data by using the GROUP BY clause

Include or exclude the grouped rows by using the

HAVING clause
95127c03.indd 147 2/17/09 11:38:10 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
As explained in the previous chapter, functions are programs
that take zero or more arguments and return a single value. The
exam focuses on two types of functions: single-row and aggre-
gate (group) functions. Single-row functions were covered in Chapter 2, “Using Single-Row
Functions.” Group functions are covered in this chapter.
Group functions differ from single-row functions in how they are evaluated. Single-row
functions are evaluated once for each row retrieved. Group functions are evaluated on
groups of one or more rows at a time.
In this chapter, you will explore which group functions are available in SQL, the rules
for how to use them, and what to expect on the exam about aggregating data and group
functions. You will also explore nesting function calls together. SQL allows you to nest
group functions within calls to single-row functions, as well as nest single-row functions
within calls to group functions.
Group-Function Fundamentals
Group functions are sometimes called aggregate functions and return a value based on a num-
ber of inputs. The exact number of inputs is not determined until the query is executed and
all rows are fetched. This differs from single-row functions, in which the number of inputs is
known at parse time—before the query is executed. Because of this difference, group functions
have slightly different requirements and behavior than single-row functions.
Group functions do not consider
NULL
values, except the

COUNT(*)
and
GROUPING
functions.
You may apply the
NVL
function to the argument of the group function to substitute a value
for
NULL
and hence be included in the processing of the group function. If the dataset contains
all
NULL
values or there are no rows in the dataset, the group function returns
NULL
(the only
exception to this rule is
COUNT
—it returns zero).
Most of the group functions can be applied either to
ALL
values or to only the
DISTINCT

values for the specified expression. When
ALL
is specified, all non-
NULL
values are applied to
the group function. When
DISTINCT

is specified, only one of each non-
NULL
value is applied
to the function. If you do not specify
ALL
or
DISTINCT
, the default is
ALL
.
To better understand the difference of
ALL
vs.
DISTINCT
, let’s look at a few rows from the
EMPLOYEES
table:
SELECT first_name, salary
FROM employees
WHERE first_name LIKE ‘D%’
ORDER BY salary;
95127c03.indd 148 2/17/09 11:38:10 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Utilizing Aggregate Functions

149
FIRST_NAME SALARY
-------------------- ----------
Donald 2600
Douglas 2600

Diana 4200
David 4800
David 6800
Daniel 9000
David 9500
Danielle 9500
Den 11000
The
SALARY
column contains nine values. Two employees have 2,600 and 9,500 each. When
you count unique entries in the
SALARY
column, there are seven, since two are duplicates. The
following SQL shows a few examples. The
COUNT
function is used to get a count, and the
SUM

function is used to find the total. (I’ll discuss these functions later in the chapter.) When the
UNIQUE
keyword is used, the 2,600 and 9,500 are included in the result only once.
SELECT COUNT(salary) cnt_nu, COUNT(DISTINCT salary) cnt_uq,
SUM(salary) sum_nu, SUM(DISTINCT salary) sum_uq
FROM employees
WHERE first_name LIKE ‘D%’;
CNT_NU CNT_UQ SUM_NU SUM_UQ
---------- ---------- ---------- ----------
9 7 60000 47900
Unlike with single-row functions, you cannot use programmer-written
functions on grouped data.

Utilizing Aggregate Functions
As with single-row functions, Oracle offers a rich variety of aggregate functions. These
functions can appear in the
SELECT
,
ORDER BY
, or
HAVING
clauses of
SELECT
statements.
When used in the
SELECT
clause, they usually require a
GROUP BY
clause as well. If no
GROUP
BY
clause is specified, the default grouping is for the entire result set. Group functions can-
not appear in the
WHERE
clause of a
SELECT
statement. The
GROUP BY
and
HAVING
clauses of
SELECT
statements are associated with grouping data. I’ll discuss the

GROUP BY
clause before
you learn about the various group functions.
95127c03.indd 149 2/17/09 11:38:10 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
150

Chapter 3

Using Group Functions
You almost certainly will encounter a certification-exam question that tests
whether you will incorrectly put a group function in the
WHERE
clause.
Grouping Data with GROUP BY
As the name implies, group functions work on data that is grouped. You tell the database
how to group or categorize the data with a
GROUP BY
clause. Whenever you use a group func-
tion in the
SELECT
clause of a
SELECT
statement, you must place all nongrouping/nonconstant
columns in the
GROUP BY
clause. If no
GROUP BY
clause is specified (only group functions and
constants appear in the

SELECT
clause), the default grouping becomes the entire result set.
When the query executes and the data is fetched, it is grouped based on the
GROUP BY
clause,
and the group function is applied.
The basic syntax of using a group function in the
SELECT
statement is as follows:
SELECT [column names], group_function (column_name), … … …
FROM table
[WHERE condition]
[GROUP BY column names]
[ORDER BY column names]
In the following example, you find the total number of employees from the
EMPLOYEES
table:
SELECT COUNT(*) FROM employees;
COUNT(*)
----------
107
Since you did not have any other column in the
SELECT
clause, you didn’t need to specify
the
GROUP BY
clause. Suppose you want to find out the number of employees in each depart-
ment; you can include
department_id
in the

SELECT
clause:
SELECT department_id, COUNT(*) “#Employees”
FROM employees;
SELECT department_id, COUNT(*) “#Employees”
*
ERROR at line 1:
ORA-00937: not a single-group group function
Since you used an aggregate function and nonaggregated column, Oracle gave an error
and is telling you to group the data. Here you have to use the
GROUP BY
clause. If you include
95127c03.indd 150 2/17/09 11:38:10 AM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

×